text
stringlengths
5
1.04M
#include "z80/cpu.hpp" void Z80::CPU::xor_a() { uint8_t v = REGISTER(REG_AF).getUpper(); v ^= v; REGISTER(REG_AF).setUpper(v); this->setFlags( ZERO_FLAG ); this->clearFlags( CARRY_FLAG | SUBTRACT_FLAG | HALFCARRY_FLAG ); this->incrementPC(1); this->clock.incrementMachineCycles(1); }
/* * SPDX-License-Identifier: MIT * * Copyright (c) 2021 Bart Bilos * For conditions of distribution and use, see LICENSE file */
// // Copyright (c) 2013-2021 The SRS Authors // // SPDX-License-Identifier: MIT or MulanPSL-2.0 // #ifndef SRT_TO_RTMP_H #define SRT_TO_RTMP_H #include <srs_core.hpp> #include <memory> #include <string> #include <thread> #include <queue> #include <map> #include <mutex> #include <condition_variable> #include <srs_kernel_ts.hpp> #include <srs_app_rtmp_conn.hpp> #include <srs_raw_avc.hpp> #include <srs_protocol_utility.hpp> #include <unordered_map> #include "srt_data.hpp" #include "ts_demux.hpp" #include "srt_log.hpp" #define SRT_VIDEO_MSG_TYPE 0x01 #define SRT_AUDIO_MSG_TYPE 0x02 typedef std::shared_ptr<SrsSimpleRtmpClient> RTMP_CONN_PTR; typedef std::shared_ptr<SrsRawH264Stream> AVC_PTR; typedef std::shared_ptr<SrsRawAacStream> AAC_PTR; #define DEFAULT_VHOST "__default_host__" #define QUEUE_DEF_TIMEOUT 500 #define QUEUE_LEN_MAX 100 typedef struct { unsigned char* _data; int _len; int64_t _dts; char _type; char reserve[3]; } rtmp_packet_info_s; class rtmp_packet_queue { public: rtmp_packet_queue(); ~rtmp_packet_queue(); void set_queue_timeout(int64_t queue_timeout); void insert_rtmp_data(unsigned char* data, int len, int64_t dts, char media_type); bool get_rtmp_data(rtmp_packet_info_s& packet_info); private: bool is_ready(); private: int64_t _queue_timeout; int64_t _queue_maxlen; int64_t _first_packet_t; int64_t _first_local_t; std::multimap<int64_t, rtmp_packet_info_s> _send_map;//key:dts, value:rtmp_packet_info }; class rtmp_client : public ts_media_data_callback_I, public std::enable_shared_from_this<rtmp_client> { public: rtmp_client(std::string key_path); virtual ~rtmp_client(); int receive_ts_data(SRT_DATA_MSG_PTR data_ptr); int64_t get_last_live_ts(); std::string get_url(); srs_error_t connect(); void close(); private: virtual int on_data_callback(SRT_DATA_MSG_PTR data_ptr, unsigned int media_type, uint64_t dts, uint64_t pts); private: srs_error_t on_ts_video(std::shared_ptr<SrsBuffer> avs_ptr, uint64_t dts, uint64_t pts); srs_error_t on_ts_audio(std::shared_ptr<SrsBuffer> avs_ptr, uint64_t dts, uint64_t pts); virtual srs_error_t write_h264_sps_pps(uint32_t dts, uint32_t pts); virtual srs_error_t write_h264_ipb_frame(char* frame, int frame_size, uint32_t dts, uint32_t pts); virtual srs_error_t write_audio_raw_frame(char* frame, int frame_size, SrsRawAacStreamCodec* codec, uint32_t dts); int get_sample_rate(char sound_rate); srs_error_t rtmp_write_work(); private: virtual srs_error_t rtmp_write_packet(char type, uint32_t timestamp, char* data, int size); private: std::string _key_path; std::string _url; std::string _vhost; std::string _appname; std::string _streamname; TS_DEMUX_PTR _ts_demux_ptr; private: AVC_PTR _avc_ptr; std::string _h264_sps; bool _h264_sps_changed; std::string _h264_pps; bool _h264_pps_changed; bool _h264_sps_pps_sent; private: std::string _aac_specific_config; AAC_PTR _aac_ptr; private: RTMP_CONN_PTR _rtmp_conn_ptr; bool _connect_flag; int64_t _last_live_ts; private: rtmp_packet_queue _rtmp_queue; }; typedef std::shared_ptr<rtmp_client> RTMP_CLIENT_PTR; class srt2rtmp : public ISrsCoroutineHandler { public: static std::shared_ptr<srt2rtmp> get_instance(); srt2rtmp(); virtual ~srt2rtmp(); srs_error_t init(); void release(); void insert_data_message(unsigned char* data_p, unsigned int len, const std::string& key_path); void insert_ctrl_message(unsigned int msg_type, const std::string& key_path); void insert_log_message(LOGGER_LEVEL level, const std::string& log_content); private: SRT_DATA_MSG_PTR get_data_message(); virtual srs_error_t cycle(); int handle_ts_data(SRT_DATA_MSG_PTR data_ptr); void handle_close_rtmpsession(const std::string& key_path); void handle_log_data(SRT_DATA_MSG_PTR data_ptr); void check_rtmp_alive(); private: static std::shared_ptr<srt2rtmp> s_srt2rtmp_ptr; std::shared_ptr<SrsCoroutine> _trd_ptr; std::mutex _mutex; //std::condition_variable_any _notify_cond; std::queue<SRT_DATA_MSG_PTR> _msg_queue; std::unordered_map<std::string, RTMP_CLIENT_PTR> _rtmp_client_map; int64_t _lastcheck_ts; public: static std::mutex _srt_error_mutex; static std::map<std::string, int> _srt_error_map; }; #endif
#include <iostream> #include "hwork221219.h" using namespace std; namespace hwork221219 { void task16051() { int number = 0; int minDigit = INT_MAX; int amount = 0; while (number != 0) { int digit = number % 10; if (digit % 2 == 0 && digit < minDigit) { minDigit = digit; } if (digit % 2 == 0) { ++amount; } number /= 10; } if (amount == 0) { cout << "NO"; } else { cout << minDigit; } } void task7382() { int x = 0; cin >> x; if (x >= 0 && x <= 6) { cout << "B"; } if (x >= 12 && x <= 18) { cout << "D"; } } void task7469() { int number = 0; int amount = 0; int max = INT_MIN; for (int i = 0; i < 4; i++) { cin >> number; if (number % 2 == 1) { ++amount; } if (number % 2 == 1 && number > max) { max = number; } } if (amount == 0) { cout << "NO"; } else { cout << max << " " << amount; } } void task5948() { int number = 0; int min = INT_MAX; cin >> number; while (number != 0) { int digit = number % 10; if (digit < min) { min = digit; } } cout << min; } void task9176() { int number = 0; int max = INT_MIN; int sum = 0; for (int i = 0; i < 4; i++) { cin >> number; if (number < 0) { sum += number; } if (number > max) { max = number; } } cout << max << " " << sum; } }
//===-test_xor2d_dnnl.cc-----------------------------------------------------------===// // // Copyright (C) 2019-2020 Alibaba Group Holding Limited. // // 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. // ============================================================================= // clang-format off // Testing CXX Code Gen using ODLA API on dnnl // RUN: %halo_compiler -target cxx -o %data_path/test_xor2d/test_data_set_0/input_0.cc -x onnx -emit-data-as-c %data_path/test_xor2d/test_data_set_0/input_0.pb // RUN: %halo_compiler -target cxx -o %data_path/test_xor2d/test_data_set_0/output_0.cc -x onnx -emit-data-as-c %data_path/test_xor2d/test_data_set_0/output_0.pb // RUN: %halo_compiler -target cxx -o %data_path/test_xor2d/test_data_set_0/input_1.cc -x onnx -emit-data-as-c %data_path/test_xor2d/test_data_set_0/input_1.pb // RUN: %halo_compiler -target cxx -batch-size 1 %halo_compile_flags %data_path/test_xor2d/model.onnx -o %t.cc // RUN: %cxx -c -fPIC -o %t.o %t.cc -I%odla_path/include // RUN: %cxx -g %s %t.o %t.bin -I%T -I%odla_path/include -I%unittests_path -I%data_path/test_xor2d/test_data_set_0 %odla_link %device_link -lodla_dnnl -o %t_dnnl.exe -Wno-deprecated-declarations // RUN: %t_dnnl.exe 0.0001 0 dnnl %data_path/test_xor2d | FileCheck %s // CHECK: Result Pass // clang-format on // XFAIL: * #include "test_xor2d_dnnl.cc.tmp.main.cc.in"
/* Copyright (c) 2009-2016, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #ifndef EL_TWOSIDEDTRMM_UNBLOCKED_HPP #define EL_TWOSIDEDTRMM_UNBLOCKED_HPP namespace El { namespace twotrmm { template<typename T> void LUnb( UnitOrNonUnit diag, Matrix<T>& A, const Matrix<T>& L ) { EL_DEBUG_CSE // Use the Variant 4 algorithm // (which annoyingly requires conjugations for the Her2) const Int n = A.Height(); const Int lda = A.LDim(); const Int ldl = L.LDim(); T* ABuffer = A.Buffer(); const T* LBuffer = L.LockedBuffer(); vector<T> a10Conj( n ), l10Conj( n ); for( Int j=0; j<n; ++j ) { const Int a21Height = n - (j+1); // Extract and store the diagonal values of A and L const T alpha11 = ABuffer[j+j*lda]; const T lambda11 = ( diag==UNIT ? 1 : LBuffer[j+j*ldl] ); // a10 := a10 + (alpha11/2)l10 T* a10 = &ABuffer[j]; const T* l10 = &LBuffer[j]; for( Int k=0; k<j; ++k ) a10[k*lda] += (alpha11/T(2))*l10[k*ldl]; // A00 := A00 + (a10' l10 + l10' a10) T* A00 = ABuffer; for( Int k=0; k<j; ++k ) a10Conj[k] = Conj(a10[k*lda]); for( Int k=0; k<j; ++k ) l10Conj[k] = Conj(l10[k*ldl]); blas::Her2 ( 'L', j, T(1), a10Conj.data(), 1, l10Conj.data(), 1, A00, lda ); // a10 := a10 + (alpha11/2)l10 for( Int k=0; k<j; ++k ) a10[k*lda] += (alpha11/T(2))*l10[k*ldl]; // a10 := conj(lambda11) a10 if( diag != UNIT ) for( Int k=0; k<j; ++k ) a10[k*lda] *= Conj(lambda11); // alpha11 := alpha11 * |lambda11|^2 ABuffer[j+j*lda] *= Conj(lambda11)*lambda11; // A20 := A20 + a21 l10 T* a21 = &ABuffer[(j+1)+j*lda]; T* A20 = &ABuffer[j+1]; blas::Geru( a21Height, j, T(1), a21, 1, l10, ldl, A20, lda ); // a21 := lambda11 a21 if( diag != UNIT ) for( Int k=0; k<a21Height; ++k ) a21[k] *= lambda11; } } template<typename T> void UUnb( UnitOrNonUnit diag, Matrix<T>& A, const Matrix<T>& U ) { EL_DEBUG_CSE // Use the Variant 4 algorithm const Int n = A.Height(); const Int lda = A.LDim(); const Int ldu = U.LDim(); T* ABuffer = A.Buffer(); const T* UBuffer = U.LockedBuffer(); for( Int j=0; j<n; ++j ) { const Int a21Height = n - (j+1); // Extract and store the diagonal values of A and U const T alpha11 = ABuffer[j+j*lda]; const T upsilon11 = ( diag==UNIT ? 1 : UBuffer[j+j*ldu] ); // a01 := a01 + (alpha11/2)u01 T* a01 = &ABuffer[j*lda]; const T* u01 = &UBuffer[j*ldu]; for( Int k=0; k<j; ++k ) a01[k] += (alpha11/T(2))*u01[k]; // A00 := A00 + (u01 a01' + a01 u01') T* A00 = ABuffer; blas::Her2( 'U', j, T(1), u01, 1, a01, 1, A00, lda ); // a01 := a01 + (alpha11/2)u01 for( Int k=0; k<j; ++k ) a01[k] += (alpha11/T(2))*u01[k]; // a01 := conj(upsilon11) a01 if( diag != UNIT ) for( Int k=0; k<j; ++k ) a01[k] *= Conj(upsilon11); // A02 := A02 + u01 a12 T* a12 = &ABuffer[j+(j+1)*lda]; T* A02 = &ABuffer[(j+1)*lda]; blas::Geru( j, a21Height, T(1), u01, 1, a12, lda, A02, lda ); // alpha11 := alpha11 * |upsilon11|^2 ABuffer[j+j*lda] *= Conj(upsilon11)*upsilon11; // a12 := upsilon11 a12 if( diag != UNIT ) for( Int k=0; k<a21Height; ++k ) a12[k*lda] *= upsilon11; } } } // namespace twotrmm } // namespace El #endif // ifndef EL_TWOSIDEDTRMM_UNBLOCKED_HPP
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "peridot/lib/module_manifest/module_facet_reader_impl.h" #include "lib/cmx_facet_parser/cmx_facet_parser.h" #include "lib/fsl/io/fd.h" #include "lib/json/json_parser.h" #include "lib/sys/cpp/component_context.h" #include "peridot/lib/fidl/json_xdr.h" #include "peridot/lib/module_manifest/module_manifest_xdr.h" #include "src/lib/pkg_url/fuchsia_pkg_url.h" #include "src/lib/pkg_url/url_resolver.h" namespace modular { namespace { constexpr char kModuleFacetName[] = "fuchsia.module"; } // namespace ModuleFacetReaderImpl::ModuleFacetReaderImpl(fuchsia::sys::LoaderPtr loader) : loader_(std::move(loader)) {} ModuleFacetReaderImpl::~ModuleFacetReaderImpl() {} void ModuleFacetReaderImpl::GetModuleManifest(const std::string& module_url, GetModuleManifestCallback callback) { auto canonical_url = component::CanonicalizeURL(module_url); loader_->LoadUrl(canonical_url, [canonical_url, callback = std::move(callback)]( fuchsia::sys::PackagePtr package) { if (!package) { callback({}); return; } fxl::UniqueFD fd = fsl::OpenChannelAsFileDescriptor(std::move(package->directory)); component::FuchsiaPkgUrl pkg_url; std::string cmx_path; if (pkg_url.Parse(package->resolved_url)) { if (!pkg_url.resource_path().empty()) { // If the url has a resource, assume that's the cmx. cmx_path = pkg_url.resource_path(); } else { // It's possible the url does not have a resource, in which case // either the cmx exists at meta/<package_name.cmx> or it does not // exist. cmx_path = pkg_url.GetDefaultComponentCmxPath(); } } else { callback({}); return; } component::CmxFacetParser facet_parser; json::JSONParser json_parser; if (!facet_parser.ParseFromFileAt(fd.get(), cmx_path, &json_parser)) { FXL_LOG(WARNING) << "Could not parse CMX manifest " << cmx_path << ": " << json_parser.error_str(); callback({}); return; } const auto& mod_facet = facet_parser.GetSection(kModuleFacetName); if (mod_facet.IsNull()) { callback({}); return; } fuchsia::modular::ModuleManifestPtr module_manifest; auto mod_facet_str = JsonValueToString(mod_facet); if (!XdrRead(mod_facet_str, &module_manifest, XdrModuleManifest)) { FXL_LOG(WARNING) << "Unable to parse manifest module facet for " << package->resolved_url << ": " << mod_facet_str; callback({}); return; } // TODO(MF-94): Deprecate ModuleManfiest.binary in favour of getting it // from the cmx manifest. module_manifest->binary = canonical_url; callback(std::move(module_manifest)); }); } } // namespace modular
// 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 "lite/operators/assign_value_op.h" #include <vector> #include "lite/core/op_lite.h" #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace operators { bool AssignValueOpLite::CheckShape() const { CHECK_OR_FALSE(param_.Out); auto shape = param_.shape; auto int32_values = param_.int32_values; auto fp32_values = param_.fp32_values; size_t shape_num = 1; for (int i = 0; i < shape.size(); i++) { shape_num *= shape[i]; } CHECK_OR_FALSE(shape_num == int32_values.size() || shape_num == fp32_values.size()); return true; } bool AssignValueOpLite::InferShapeImpl() const { std::vector<int> shape = param_.shape; std::vector<int64_t> out_shape; for (size_t i = 0; i < shape.size(); i++) out_shape.push_back(shape[i]); param_.Out->Resize(out_shape); return true; } bool AssignValueOpLite::AttachImpl(const cpp::OpDesc &op_desc, lite::Scope *scope) { param_.shape = op_desc.GetAttr<std::vector<int>>("shape"); param_.dtype = op_desc.GetAttr<int>("dtype"); param_.fp32_values = op_desc.GetAttr<std::vector<float>>("fp32_values"); param_.int32_values = op_desc.GetAttr<std::vector<int>>("int32_values"); auto out = op_desc.Output("Out").front(); param_.Out = scope->FindVar(out)->GetMutable<lite::Tensor>(); return true; } } // namespace operators } // namespace lite } // namespace paddle REGISTER_LITE_OP(assign_value, paddle::lite::operators::AssignValueOpLite);
/* Copyright 2005-2015 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Threading Building Blocks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #include "tbb/recursive_mutex.h" #include "itt_notify.h" namespace tbb { void recursive_mutex::scoped_lock::internal_acquire( recursive_mutex& m ) { #if _WIN32||_WIN64 switch( m.state ) { case INITIALIZED: // since we cannot look into the internal of the CriticalSection object // we won't know how many times the lock has been acquired, and thus // we won't know when we may safely set the state back to INITIALIZED // if we change the state to HELD as in mutex.cpp. thus, we won't change // the state for recursive_mutex EnterCriticalSection( &m.impl ); break; case DESTROYED: __TBB_ASSERT(false,"recursive_mutex::scoped_lock: mutex already destroyed"); break; default: __TBB_ASSERT(false,"recursive_mutex::scoped_lock: illegal mutex state"); break; } #else int error_code = pthread_mutex_lock(&m.impl); if( error_code ) tbb::internal::handle_perror(error_code,"recursive_mutex::scoped_lock: pthread_mutex_lock failed"); #endif /* _WIN32||_WIN64 */ my_mutex = &m; } void recursive_mutex::scoped_lock::internal_release() { __TBB_ASSERT( my_mutex, "recursive_mutex::scoped_lock: not holding a mutex" ); #if _WIN32||_WIN64 switch( my_mutex->state ) { case INITIALIZED: LeaveCriticalSection( &my_mutex->impl ); break; case DESTROYED: __TBB_ASSERT(false,"recursive_mutex::scoped_lock: mutex already destroyed"); break; default: __TBB_ASSERT(false,"recursive_mutex::scoped_lock: illegal mutex state"); break; } #else int error_code = pthread_mutex_unlock(&my_mutex->impl); __TBB_ASSERT_EX(!error_code, "recursive_mutex::scoped_lock: pthread_mutex_unlock failed"); #endif /* _WIN32||_WIN64 */ my_mutex = NULL; } bool recursive_mutex::scoped_lock::internal_try_acquire( recursive_mutex& m ) { #if _WIN32||_WIN64 switch( m.state ) { case INITIALIZED: break; case DESTROYED: __TBB_ASSERT(false,"recursive_mutex::scoped_lock: mutex already destroyed"); break; default: __TBB_ASSERT(false,"recursive_mutex::scoped_lock: illegal mutex state"); break; } #endif /* _WIN32||_WIN64 */ bool result; #if _WIN32||_WIN64 result = TryEnterCriticalSection(&m.impl)!=0; #else result = pthread_mutex_trylock(&m.impl)==0; #endif /* _WIN32||_WIN64 */ if( result ) my_mutex = &m; return result; } void recursive_mutex::internal_construct() { #if _WIN32||_WIN64 InitializeCriticalSectionEx(&impl, 4000, 0); state = INITIALIZED; #else pthread_mutexattr_t mtx_attr; int error_code = pthread_mutexattr_init( &mtx_attr ); if( error_code ) tbb::internal::handle_perror(error_code,"recursive_mutex: pthread_mutexattr_init failed"); pthread_mutexattr_settype( &mtx_attr, PTHREAD_MUTEX_RECURSIVE ); error_code = pthread_mutex_init( &impl, &mtx_attr ); if( error_code ) tbb::internal::handle_perror(error_code,"recursive_mutex: pthread_mutex_init failed"); pthread_mutexattr_destroy( &mtx_attr ); #endif /* _WIN32||_WIN64*/ ITT_SYNC_CREATE(&impl, _T("tbb::recursive_mutex"), _T("")); } void recursive_mutex::internal_destroy() { #if _WIN32||_WIN64 switch( state ) { case INITIALIZED: DeleteCriticalSection(&impl); break; case DESTROYED: __TBB_ASSERT(false,"recursive_mutex: already destroyed"); break; default: __TBB_ASSERT(false,"recursive_mutex: illegal state for destruction"); break; } state = DESTROYED; #else int error_code = pthread_mutex_destroy(&impl); __TBB_ASSERT_EX(!error_code,"recursive_mutex: pthread_mutex_destroy failed"); #endif /* _WIN32||_WIN64 */ } } // namespace tbb
#include <iostream> #include <ostream> #include <sstream> #include <thread> #include <memory> #include <cstddef> #include "SomeClass.h" using namespace std; struct SomeStruct { int Value; }; namespace Value { thread_local SomeStruct ThreadLocalSomeStruct = {}; static SomeClass g_staticSomeClass = SomeClass(20, L"g_staticSomeClass"); } void ChangeAndPrintValue(int value) { wstringstream wsStr(L""); wsStr << L"ChangeAndPrintValue thread id: '" << this_thread::get_id() << L"'"; SomeClass sc(value, wsStr.str().c_str()); wcout << L"Old value is " << Value::ThreadLocalSomeStruct.Value << L". Thread id: '" << this_thread::get_id() << L"'." << endl; Value::ThreadLocalSomeStruct.Value = value; wcout << L"New value is " << Value::ThreadLocalSomeStruct.Value << L". Thread id: '" << this_thread::get_id() << L"'." << endl; } void LocalStatic(int value) { static SomeClass sc(value, L"LocalStatic sc"); wcout << L"Local Static sc value: '" << sc.GetValue() << L"'." << endl << endl; } int main(int argc, const char * argv[]) { SomeClass sc1(1, L"_pmain sc1"); wcout << L"sc1 value: '" << sc1.GetValue() << L"'." << endl << endl; { SomeClass sc2(2, L"_pmain sc2"); wcout << L"sc2 value: '" << sc2.GetValue() << L"'." << endl << endl; } LocalStatic(1000); LocalStatic(5000); ChangeAndPrintValue(20); auto thr = thread(ChangeAndPrintValue, 40); thr.join(); SomeClass* p_dsc = new SomeClass(1000, L"_pmain p_dsc"); const std::size_t arrIntSize = 5; int* p_arrInt = new int[arrIntSize]; for (int i = 0; i < arrIntSize; i++) { wcout << L"i: '" << i << L"'. p_arrInt[i] = '" << p_arrInt[i] << L"'." << endl; p_arrInt[i] = i; } wcout << endl; for (int i = 0; i < arrIntSize; i++) { wcout << L"i: '" << i << L"'. p_arrInt[i] = '" << p_arrInt[i] << L"'." << endl; } delete p_dsc; p_dsc = nullptr; delete[] p_arrInt; p_arrInt = nullptr; wcout << L"Ending program." << endl; return 0; }
#include "stdafx.h" #include "vkTextureUtils.h" namespace vkTextureUtils { struct TextureFormatPairs { D3DFORMAT m_dx9FMT; DXGI_FORMAT m_vkFMT; }; TextureFormatPairs TextureFormatList[] = { { D3DFMT_UNKNOWN, DXGI_FORMAT_UNKNOWN }, //D3DFMT_R8G8B8 Not available { D3DFMT_A8R8G8B8, DXGI_FORMAT_R8G8B8A8_UNORM }, // Not available //D3DFMT_X8R8G8B8 Not available // TODO: vk: Remove. Need only for nullrt //{ D3DFMT_R5G6B5, DXGI_FORMAT_B5G6R5_UNORM }, // Not available { D3DFMT_R5G6B5, DXGI_FORMAT_R8G8B8A8_UNORM }, // Not available //D3DFMT_X1R5G5B5 Not available //D3DFMT_A1R5G5B5 Not available //D3DFMT_A4R4G4B4 Not available //D3DFMT_R3G3B2 Not available //D3DFMT_A8 DXGI_FORMAT_A8_UNORM //D3DFMT_A8R3G3B2 Not available //D3DFMT_X4R4G4B4 Not available //D3DFMT_A2B10G10R10 DXGI_FORMAT_R10G10B10A2 { D3DFMT_A8B8G8R8, DXGI_FORMAT_R8G8B8A8_UNORM},// & DXGI_FORMAT_R8G8B8A8_UNORM_SRGB //D3DFMT_X8B8G8R8 Not available { D3DFMT_G16R16, DXGI_FORMAT_R16G16_UNORM}, //D3DFMT_A2R10G10B10 Not available { D3DFMT_A16B16G16R16, DXGI_FORMAT_R16G16B16A16_UNORM}, //D3DFMT_A8P8 Not available //D3DFMT_P8 Not available { D3DFMT_L8, DXGI_FORMAT_R8_UNORM}, // Note: Use .r swizzle in shader to duplicate red to other components to get D3D9 behavior. //D3DFMT_A8L8 Not available //D3DFMT_A4L4 Not available { D3DFMT_V8U8, DXGI_FORMAT_R8G8_SNORM}, //D3DFMT_L6V5U5 Not available //D3DFMT_X8L8V8U8 Not available { D3DFMT_Q8W8V8U8, DXGI_FORMAT_R8G8B8A8_SNORM}, { D3DFMT_V16U16, DXGI_FORMAT_R16G16_SNORM}, //D3DFMT_W11V11U10 Not available //D3DFMT_A2W10V10U10 Not available //D3DFMT_UYVY Not available //D3DFMT_R8G8_B8G8 DXGI_FORMAT_G8R8_G8B8_UNORM (in DX9 the data was scaled up by 255.0f, but this can be handled in shader code). //D3DFMT_YUY2 Not available //D3DFMT_G8R8_G8B8 DXGI_FORMAT_R8G8_B8G8_UNORM (in DX9 the data was scaled up by 255.0f, but this can be handled in shader code). //D3DFMT_DXT1 DXGI_FORMAT_BC1_UNORM & DXGI_FORMAT_BC1_UNORM_SRGB //D3DFMT_DXT2 DXGI_FORMAT_BC1_UNORM & DXGI_FORMAT_BC1_UNORM_SRGB Note: DXT1 and DXT2 are the same from an API/hardware perspective... only difference was 'premultiplied alpha', which can be tracked by an application and doesn't need a separate format. //D3DFMT_DXT3 DXGI_FORMAT_BC2_UNORM & DXGI_FORMAT_BC2_UNORM_SRGB //D3DFMT_DXT4 DXGI_FORMAT_BC2_UNORM & DXGI_FORMAT_BC2_UNORM_SRGB Note: DXT3 and DXT4 are the same from an API/hardware perspective... only difference was 'premultiplied alpha', which can be tracked by an application and doesn't need a separate format. //D3DFMT_DXT5 DXGI_FORMAT_BC3_UNORM & DXGI_FORMAT_BC3_UNORM_SRGB //D3DFMT_D16 & D3DFMT_D16_LOCKABLE DXGI_FORMAT_D16_UNORM //D3DFMT_D32 Not available //D3DFMT_D15S1 Not available //D3DFMT_D24S8 Not available { D3DFMT_D24X8, DXGI_FORMAT_R24G8_TYPELESS}, //DXGI_FORMAT_D24_UNORM_S8_UINT}, // Not available //D3DFMT_D24X4S4 Not available //D3DFMT_D16 DXGI_FORMAT_D16_UNORM //{ D3DFMT_D32F_LOCKABLE, DXGI_FORMAT_D32_FLOAT}, { D3DFMT_D32F_LOCKABLE, DXGI_FORMAT_R32_TYPELESS}, //D3DFMT_D24FS8 Not available //D3DFMT_S1D15 Not available //D3DFMT_S8D24 DXGI_FORMAT_D24_UNORM_S8_UINT //D3DFMT_X8D24 Not available //D3DFMT_X4S4D24 Not available //D3DFMT_L16 DXGI_FORMAT_R16_UNORM Note: Use .r swizzle in shader to duplicate red to other components to get D3D9 behavior. //D3DFMT_INDEX16 DXGI_FORMAT_R16_UINT //D3DFMT_INDEX32 DXGI_FORMAT_R32_UINT //D3DFMT_Q16W16V16U16 DXGI_FORMAT_R16G16B16A16_SNORM //D3DFMT_MULTI2_ARGB8 Not available //D3DFMT_R16F DXGI_FORMAT_R16_FLOAT { D3DFMT_G16R16F, DXGI_FORMAT_R16G16_FLOAT}, { D3DFMT_A16B16G16R16F, DXGI_FORMAT_R16G16B16A16_FLOAT}, { D3DFMT_R32F, DXGI_FORMAT_R32_FLOAT}, { D3DFMT_R16F, DXGI_FORMAT_R16_FLOAT}, //{ D3DFMT_G32R32F, DXGI_FORMAT_R32G32_FLOAT}, { D3DFMT_A32B32G32R32F, DXGI_FORMAT_R32G32B32A32_FLOAT }, //D3DFMT_CxV8U8 Not available //D3DDECLTYPE_FLOAT1 DXGI_FORMAT_R32_FLOAT //D3DDECLTYPE_FLOAT2 DXGI_FORMAT_R32G32_FLOAT //D3DDECLTYPE_FLOAT3 DXGI_FORMAT_R32G32B32_FLOAT //D3DDECLTYPE_FLOAT4 DXGI_FORMAT_R32G32B32A32_FLOAT //D3DDECLTYPED3DCOLOR Not available //D3DDECLTYPE_UBYTE4 DXGI_FORMAT_R8G8B8A8_UINT Note: Shader gets UINT values, but if Direct3D 9 style integral floats are needed (0.0f, 1.0f... 255.f), UINT can just be converted to float32 in shader. //D3DDECLTYPE_SHORT2 DXGI_FORMAT_R16G16_SINT Note: Shader gets SINT values, but if Direct3D 9 style integral floats are needed, SINT can just be converted to float32 in shader. //D3DDECLTYPE_SHORT4 DXGI_FORMAT_R16G16B16A16_SINT Note: Shader gets SINT values, but if Direct3D 9 style integral floats are needed, SINT can just be converted to float32 in shader. //D3DDECLTYPE_UBYTE4N DXGI_FORMAT_R8G8B8A8_UNORM //D3DDECLTYPE_SHORT2N DXGI_FORMAT_R16G16_SNORM //D3DDECLTYPE_SHORT4N DXGI_FORMAT_R16G16B16A16_SNORM //D3DDECLTYPE_USHORT2N DXGI_FORMAT_R16G16_UNORM //D3DDECLTYPE_USHORT4N DXGI_FORMAT_R16G16B16A16_UNORM //D3DDECLTYPE_UDEC3 Not available //D3DDECLTYPE_DEC3N Not available //D3DDECLTYPE_FLOAT16_2 DXGI_FORMAT_R16G16_FLOAT //D3DDECLTYPE_FLOAT16_4 DXGI_FORMAT_R16G16B16A16_FLOAT }; DXGI_FORMAT ConvertTextureFormat(D3DFORMAT dx9FMT) { int arrayLength = sizeof(TextureFormatList) / sizeof(TextureFormatList[0]); for (int i = 0; i < arrayLength; ++i) { if (TextureFormatList[i].m_dx9FMT == dx9FMT) return TextureFormatList[i].m_vkFMT; } VERIFY(!"ConvertTextureFormat didn't find appropriate vk texture format!"); return DXGI_FORMAT_UNKNOWN; } }
#include "CCRiftInstance.h" #include "CCRiftCommons.h" #include "CCRiftScene.h" #include "CCRiftGLFWPreviewDevice.h" using namespace CCRift; CCRiftInstance::CCRiftInstance(const tmInstance* inInstance, const SDKDevicePtr& inDevice, const SDKSettings& inSettings, const SDKSuites& inSuites, GLFWPreviewDevice* previewDevice) //: mDevice(inDevice) //, mSettings(inSettings) : mSuites(inSuites) , mSelfActive(false) , mPreviewDevice(previewDevice) { mPlaying = kPrFalse; mSuites.TimeSuite->GetTicksPerSecond(&mTicksPerSecond); } CCRiftInstance::~CCRiftInstance() { } tmResult CCRiftInstance::QueryVideoMode(const tmStdParms* inStdParms, const tmInstance* inInstance, csSDK_int32 inQueryIterationIndex, tmVideoMode* outVideoMode) { tmResult returnVal = tmResult_Success; outVideoMode->outWidth = mPreviewDevice->preferredFrameWidth(); outVideoMode->outHeight = mPreviewDevice->preferredFrameHeight(); outVideoMode->outPARNum = 1; outVideoMode->outPARDen = 1; outVideoMode->outFieldType = prFieldsNone; outVideoMode->outPixelFormat = PrPixelFormat_BGRA_4444_8u; //outVideoMode->outLatency = inInstance->inVideoFrameRate * 5; // Ask for 5 frames preroll mVideoFrameRate = inInstance->inVideoFrameRate; return returnVal; } tmResult CCRiftInstance::ActivateDeactivate(const tmStdParms* inStdParms, const tmInstance* inInstance, PrActivationEvent inActivationEvent, prBool inAudioActive, prBool inVideoActive) { #ifdef PRWIN_ENV char outputString[255]; sprintf_s( outputString, 255, "<%i> ActivateDeactivate called ", clock()); OutputDebugStringA(outputString); #elif defined PRMAC_ENV NSLog(@"ActivateDeactivate called."); #endif if (inVideoActive) { // mDevice->StartTransmit(); if (mPreviewDevice && !mPreviewDevice->isRunning()) { mPreviewDevice->start(); } mPreviewDevice->setActive(true); mSelfActive = true; } else { // mDevice->StopTransmit(); mPreviewDevice->setActive(false); mSelfActive = false; } return tmResult_Success; } tmResult CCRiftInstance::PushVideo(const tmStdParms* inStdParms, const tmInstance* inInstance, const tmPushVideo* inPushVideo) { // Send the video frames to the hardware. We also log frame info to the debug console. float frameTimeInSeconds = 0; prRect frameBounds; csSDK_uint32 parNum = 0, parDen = 0; PrPixelFormat pixelFormat = PrPixelFormat_Invalid; //int audioSampleCount = 0; PrTime zeroPointTime = 0; prBool dropFrame = kPrFalse; //prSuiteError returnValue = 0; frameTimeInSeconds = (float) inPushVideo->inTime / mTicksPerSecond; mSuites.PPixSuite->GetBounds(inPushVideo->inFrames[0].inFrame, &frameBounds); mSuites.PPixSuite->GetPixelAspectRatio(inPushVideo->inFrames[0].inFrame, &parNum, &parDen); mSuites.PPixSuite->GetPixelFormat(inPushVideo->inFrames[0].inFrame, &pixelFormat); mSuites.SequenceInfoSuite->GetZeroPoint(inInstance->inTimelineID, &zeroPointTime); mSuites.SequenceInfoSuite->GetTimecodeDropFrame(inInstance->inTimelineID, &dropFrame); #ifdef PRWIN_ENV char outputString[255]; sprintf_s( outputString, 255, "<%i> PushVideo called for time %7.2f, frame size: %d x %d, PAR: %4.3f, pixel format: %#x. %d", clock(), frameTimeInSeconds, abs(frameBounds.right - frameBounds.left), abs(frameBounds.top - frameBounds.bottom), (float) parNum / parDen, pixelFormat, inPushVideo->inFrameCount); OutputDebugStringA(outputString); if (inPushVideo->inPlayMode == playmode_Scrubbing) { sprintf_s( outputString, 255, " Scrubbing.\n"); } else if (inPushVideo->inPlayMode == playmode_Playing) { sprintf_s( outputString, 255, " Playing.\n"); } else if (inPushVideo->inPlayMode == playmode_Stopped) { sprintf_s( outputString, 255, " Stopped.\n"); } OutputDebugStringA(outputString); #elif defined PRMAC_ENV NSLog(@"PushVideo called for time %7.2f, frame size: %d x %d, PAR: %4.3f, pixel format: %#x.", frameTimeInSeconds, abs(frameBounds.right - frameBounds.left), abs(frameBounds.top - frameBounds.bottom), (float) parNum / parDen, pixelFormat); #endif // // This is where a transmit plug-in could queue up the frame to an actual hardware device. // short w = abs(frameBounds.right - frameBounds.left); short h = abs(frameBounds.top - frameBounds.bottom); if (mSelfActive && mPreviewDevice && !mPreviewDevice->isRunning()) { mPreviewDevice->start(); } if (mSelfActive && mPreviewDevice && mPreviewDevice->isRunning()) { if (pixelFormat == PrPixelFormat_BGRA_4444_8u && w == mPreviewDevice->preferredFrameWidth() && h == mPreviewDevice->preferredFrameHeight()) { char *data = 0; for (int i = 0; i < inPushVideo->inFrameCount; i++) { mSuites.PPixSuite->GetPixels(inPushVideo->inFrames[i].inFrame, PrPPixBufferAccess_ReadOnly, &data); break; } mPreviewDevice->pushFrame((unsigned char*)data); } } // Dispose of the PPix(es) when done! for (int i=0; i< inPushVideo->inFrameCount; i++) { mSuites.PPixSuite->Dispose(inPushVideo->inFrames[i].inFrame); } return tmResult_Success; }
#include<iostream> using namespace std; int main(){ float c[1001] = {0}; int m, n, t; float num; scanf("%d",&m); while(m--){ scanf("%d%f",&t,&num); c[t] += num; } scanf("%d",&n); while(n--){ scanf("%d%f",&t,&num); c[t] += num; } int count = 0; for(int i = 0; i < 1001; i++){ if(c[i]!=0){ count++; } } printf("%d",count); for(int i = 1000; i >= 0; i--){ if(c[i] != 0.0) printf(" %d %.1f",i,c[i]); } return 0; }
// Copyright 2016 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 "content/browser/media/media_devices_permission_checker.h" #include <utility> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "build/build_config.h" #include "content/browser/renderer_host/render_frame_host_delegate.h" #include "content/browser/renderer_host/render_frame_host_impl.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/permission_controller.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "third_party/blink/public/common/mediastream/media_devices.h" #include "url/gurl.h" #include "url/origin.h" namespace content { namespace { MediaDevicesManager::BoolDeviceTypes DoCheckPermissionsOnUIThread( MediaDevicesManager::BoolDeviceTypes requested_device_types, int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* frame_host = RenderFrameHostImpl::FromID(render_process_id, render_frame_id); // If there is no |frame_host|, return false for all permissions. if (!frame_host) return MediaDevicesManager::BoolDeviceTypes(); RenderFrameHostDelegate* delegate = frame_host->delegate(); url::Origin origin = frame_host->GetLastCommittedOrigin(); bool audio_permission = delegate->CheckMediaAccessPermission( frame_host, origin, blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE); bool mic_permissions_policy = true; bool camera_permissions_policy = true; mic_permissions_policy = frame_host->IsFeatureEnabled( blink::mojom::PermissionsPolicyFeature::kMicrophone); camera_permissions_policy = frame_host->IsFeatureEnabled( blink::mojom::PermissionsPolicyFeature::kCamera); MediaDevicesManager::BoolDeviceTypes result; // Speakers. // TODO(guidou): use specific permission for audio output when it becomes // available. See http://crbug.com/556542. result[static_cast<size_t>(MediaDeviceType::MEDIA_AUDIO_OUTPUT)] = requested_device_types[static_cast<size_t>( MediaDeviceType::MEDIA_AUDIO_OUTPUT)] && audio_permission; // Mic. result[static_cast<size_t>(MediaDeviceType::MEDIA_AUDIO_INPUT)] = requested_device_types[static_cast<size_t>( MediaDeviceType::MEDIA_AUDIO_INPUT)] && audio_permission && mic_permissions_policy; // Camera. result[static_cast<size_t>(MediaDeviceType::MEDIA_VIDEO_INPUT)] = requested_device_types[static_cast<size_t>( MediaDeviceType::MEDIA_VIDEO_INPUT)] && delegate->CheckMediaAccessPermission( frame_host, origin, blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE) && camera_permissions_policy; return result; } bool CheckSinglePermissionOnUIThread(MediaDeviceType device_type, int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); MediaDevicesManager::BoolDeviceTypes requested; requested[static_cast<size_t>(device_type)] = true; MediaDevicesManager::BoolDeviceTypes result = DoCheckPermissionsOnUIThread( requested, render_process_id, render_frame_id); return result[static_cast<size_t>(device_type)]; } } // namespace MediaDevicesPermissionChecker::MediaDevicesPermissionChecker() : use_override_(base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseFakeUIForMediaStream)), override_value_( base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kUseFakeUIForMediaStream) != "deny") {} MediaDevicesPermissionChecker::MediaDevicesPermissionChecker( bool override_value) : use_override_(true), override_value_(override_value) {} bool MediaDevicesPermissionChecker::CheckPermissionOnUIThread( MediaDeviceType device_type, int render_process_id, int render_frame_id) const { if (use_override_) return override_value_; return CheckSinglePermissionOnUIThread(device_type, render_process_id, render_frame_id); } void MediaDevicesPermissionChecker::CheckPermission( MediaDeviceType device_type, int render_process_id, int render_frame_id, base::OnceCallback<void(bool)> callback) const { if (use_override_) { std::move(callback).Run(override_value_); return; } GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&CheckSinglePermissionOnUIThread, device_type, render_process_id, render_frame_id), std::move(callback)); } void MediaDevicesPermissionChecker::CheckPermissions( MediaDevicesManager::BoolDeviceTypes requested, int render_process_id, int render_frame_id, base::OnceCallback<void(const MediaDevicesManager::BoolDeviceTypes&)> callback) const { if (use_override_) { MediaDevicesManager::BoolDeviceTypes result; result.fill(override_value_); std::move(callback).Run(result); return; } GetUIThreadTaskRunner({})->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&DoCheckPermissionsOnUIThread, requested, render_process_id, render_frame_id), std::move(callback)); } // static bool MediaDevicesPermissionChecker::HasPanTiltZoomPermissionGrantedOnUIThread( int render_process_id, int render_frame_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); #if defined(OS_ANDROID) // The PTZ permission is automatically granted on Android. This way, zoom is // not initially empty in ImageCapture. It is safe to do so because pan and // tilt are not supported on Android. return true; #else RenderFrameHostImpl* frame_host = RenderFrameHostImpl::FromID(render_process_id, render_frame_id); if (!frame_host) return false; auto* web_contents = WebContents::FromRenderFrameHost(frame_host); if (!web_contents) return false; auto* permission_controller = BrowserContext::GetPermissionController( web_contents->GetBrowserContext()); DCHECK(permission_controller); const GURL& origin = web_contents->GetLastCommittedURL(); blink::mojom::PermissionStatus status = permission_controller->GetPermissionStatusForFrame( PermissionType::CAMERA_PAN_TILT_ZOOM, frame_host, origin); return status == blink::mojom::PermissionStatus::GRANTED; #endif } } // namespace content
// 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. #ifndef __OPENCV_TEST_PRECOMP_HPP__ #define __OPENCV_TEST_PRECOMP_HPP__ #include "opencv2/ts.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/core/private.hpp" #include "opencv2/core/softfloat.hpp" // softfloat, uint32_t #endif
#ifdef _DEBUG #include "imgui/imgui.h" #include "imgui/imgui_impl_dx11.h" #include "imgui/imgui_impl_win32.h" #include "imgui/imgui_stdlib.h" #include "imgui//IconsFontAwesome5_c.h" #include "My_imgui.h" #include "imgui/ImGuizmo.h" #include "imgui/imgui_internal.h" ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); } ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); } #include "Scene.h" #include "manager.h" #include "ShadowMap.h" #include "texture.h" #include "Texture_Manager.h" #include "Model_Manager.h" #include "camera.h" #include "Debug_Camera.h" #include "Component.h" #include "Component_Manager.h" #include "Light.h" #include "Enemy.h" #include "Bullet.h" #include "Bounding.h" #include "Bounding_Aabb.h" #include "Bounding_Obb.h" #include "Bounding_Sphere.h" #include "Bounding_Capsule.h" #include "Player.h" using namespace Aegis; static const ImWchar glyphRangesJapanese[] = { 0x0020, 0x007E, 0x00A2, 0x00A3, 0x00A7, 0x00A8, 0x00AC, 0x00AC, 0x00B0, 0x00B1, 0x00B4, 0x00B4, 0x00B6, 0x00B6, 0x00D7, 0x00D7, 0x00F7, 0x00F7, 0x0391, 0x03A1, 0x03A3, 0x03A9, 0x03B1, 0x03C1, 0x03C3, 0x03C9, 0x0401, 0x0401, 0x0410, 0x044F, 0x0451, 0x0451, 0x2010, 0x2010, 0x2015, 0x2016, 0x2018, 0x2019, 0x201C, 0x201D, 0x2020, 0x2021, 0x2025, 0x2026, 0x2030, 0x2030, 0x2032, 0x2033, 0x203B, 0x203B, 0x2103, 0x2103, 0x212B, 0x212B, 0x2190, 0x2193, 0x21D2, 0x21D2, 0x21D4, 0x21D4, 0x2200, 0x2200, 0x2202, 0x2203, 0x2207, 0x2208, 0x220B, 0x220B, 0x2212, 0x2212, 0x221A, 0x221A, 0x221D, 0x221E, 0x2220, 0x2220, 0x2227, 0x222C, 0x2234, 0x2235, 0x223D, 0x223D, 0x2252, 0x2252, 0x2260, 0x2261, 0x2266, 0x2267, 0x226A, 0x226B, 0x2282, 0x2283, 0x2286, 0x2287, 0x22A5, 0x22A5, 0x2312, 0x2312, 0x2500, 0x2503, 0x250C, 0x250C, 0x250F, 0x2510, 0x2513, 0x2514, 0x2517, 0x2518, 0x251B, 0x251D, 0x2520, 0x2520, 0x2523, 0x2525, 0x2528, 0x2528, 0x252B, 0x252C, 0x252F, 0x2530, 0x2533, 0x2534, 0x2537, 0x2538, 0x253B, 0x253C, 0x253F, 0x253F, 0x2542, 0x2542, 0x254B, 0x254B, 0x25A0, 0x25A1, 0x25B2, 0x25B3, 0x25BC, 0x25BD, 0x25C6, 0x25C7, 0x25CB, 0x25CB, 0x25CE, 0x25CF, 0x25EF, 0x25EF, 0x2605, 0x2606, 0x2640, 0x2640, 0x2642, 0x2642, 0x266A, 0x266A, 0x266D, 0x266D, 0x266F, 0x266F, 0x3000, 0x3003, 0x3005, 0x3015, 0x301C, 0x301C, 0x3041, 0x3093, 0x309B, 0x309E, 0x30A1, 0x30F6, 0x30FB, 0x30FE, 0x4E00, 0x4E01, 0x4E03, 0x4E03, 0x4E07, 0x4E0B, 0x4E0D, 0x4E0E, 0x4E10, 0x4E11, 0x4E14, 0x4E19, 0x4E1E, 0x4E1E, 0x4E21, 0x4E21, 0x4E26, 0x4E26, 0x4E2A, 0x4E2A, 0x4E2D, 0x4E2D, 0x4E31, 0x4E32, 0x4E36, 0x4E36, 0x4E38, 0x4E39, 0x4E3B, 0x4E3C, 0x4E3F, 0x4E3F, 0x4E42, 0x4E43, 0x4E45, 0x4E45, 0x4E4B, 0x4E4B, 0x4E4D, 0x4E4F, 0x4E55, 0x4E59, 0x4E5D, 0x4E5F, 0x4E62, 0x4E62, 0x4E71, 0x4E71, 0x4E73, 0x4E73, 0x4E7E, 0x4E7E, 0x4E80, 0x4E80, 0x4E82, 0x4E82, 0x4E85, 0x4E86, 0x4E88, 0x4E8C, 0x4E8E, 0x4E8E, 0x4E91, 0x4E92, 0x4E94, 0x4E95, 0x4E98, 0x4E99, 0x4E9B, 0x4E9C, 0x4E9E, 0x4EA2, 0x4EA4, 0x4EA6, 0x4EA8, 0x4EA8, 0x4EAB, 0x4EAE, 0x4EB0, 0x4EB0, 0x4EB3, 0x4EB3, 0x4EB6, 0x4EB6, 0x4EBA, 0x4EBA, 0x4EC0, 0x4EC2, 0x4EC4, 0x4EC4, 0x4EC6, 0x4EC7, 0x4ECA, 0x4ECB, 0x4ECD, 0x4ECF, 0x4ED4, 0x4ED9, 0x4EDD, 0x4EDF, 0x4EE3, 0x4EE5, 0x4EED, 0x4EEE, 0x4EF0, 0x4EF0, 0x4EF2, 0x4EF2, 0x4EF6, 0x4EF7, 0x4EFB, 0x4EFB, 0x4F01, 0x4F01, 0x4F09, 0x4F0A, 0x4F0D, 0x4F11, 0x4F1A, 0x4F1A, 0x4F1C, 0x4F1D, 0x4F2F, 0x4F30, 0x4F34, 0x4F34, 0x4F36, 0x4F36, 0x4F38, 0x4F38, 0x4F3A, 0x4F3A, 0x4F3C, 0x4F3D, 0x4F43, 0x4F43, 0x4F46, 0x4F47, 0x4F4D, 0x4F51, 0x4F53, 0x4F53, 0x4F55, 0x4F55, 0x4F57, 0x4F57, 0x4F59, 0x4F5E, 0x4F69, 0x4F69, 0x4F6F, 0x4F70, 0x4F73, 0x4F73, 0x4F75, 0x4F76, 0x4F7B, 0x4F7C, 0x4F7F, 0x4F7F, 0x4F83, 0x4F83, 0x4F86, 0x4F86, 0x4F88, 0x4F88, 0x4F8B, 0x4F8B, 0x4F8D, 0x4F8D, 0x4F8F, 0x4F8F, 0x4F91, 0x4F91, 0x4F96, 0x4F96, 0x4F98, 0x4F98, 0x4F9B, 0x4F9B, 0x4F9D, 0x4F9D, 0x4FA0, 0x4FA1, 0x4FAB, 0x4FAB, 0x4FAD, 0x4FAF, 0x4FB5, 0x4FB6, 0x4FBF, 0x4FBF, 0x4FC2, 0x4FC4, 0x4FCA, 0x4FCA, 0x4FCE, 0x4FCE, 0x4FD0, 0x4FD1, 0x4FD4, 0x4FD4, 0x4FD7, 0x4FD8, 0x4FDA, 0x4FDB, 0x4FDD, 0x4FDD, 0x4FDF, 0x4FDF, 0x4FE1, 0x4FE1, 0x4FE3, 0x4FE5, 0x4FEE, 0x4FEF, 0x4FF3, 0x4FF3, 0x4FF5, 0x4FF6, 0x4FF8, 0x4FF8, 0x4FFA, 0x4FFA, 0x4FFE, 0x4FFE, 0x5005, 0x5006, 0x5009, 0x5009, 0x500B, 0x500B, 0x500D, 0x500D, 0x500F, 0x500F, 0x5011, 0x5012, 0x5014, 0x5014, 0x5016, 0x5016, 0x5019, 0x501A, 0x501F, 0x501F, 0x5021, 0x5021, 0x5023, 0x5026, 0x5028, 0x502D, 0x5036, 0x5036, 0x5039, 0x5039, 0x5043, 0x5043, 0x5047, 0x5049, 0x504F, 0x5050, 0x5055, 0x5056, 0x505A, 0x505A, 0x505C, 0x505C, 0x5065, 0x5065, 0x506C, 0x506C, 0x5072, 0x5072, 0x5074, 0x5076, 0x5078, 0x5078, 0x507D, 0x507D, 0x5080, 0x5080, 0x5085, 0x5085, 0x508D, 0x508D, 0x5091, 0x5091, 0x5098, 0x509A, 0x50AC, 0x50AD, 0x50B2, 0x50B5, 0x50B7, 0x50B7, 0x50BE, 0x50BE, 0x50C2, 0x50C2, 0x50C5, 0x50C5, 0x50C9, 0x50CA, 0x50CD, 0x50CD, 0x50CF, 0x50CF, 0x50D1, 0x50D1, 0x50D5, 0x50D6, 0x50DA, 0x50DA, 0x50DE, 0x50DE, 0x50E3, 0x50E3, 0x50E5, 0x50E5, 0x50E7, 0x50E7, 0x50ED, 0x50EE, 0x50F5, 0x50F5, 0x50F9, 0x50F9, 0x50FB, 0x50FB, 0x5100, 0x5102, 0x5104, 0x5104, 0x5109, 0x5109, 0x5112, 0x5112, 0x5114, 0x5116, 0x5118, 0x5118, 0x511A, 0x511A, 0x511F, 0x511F, 0x5121, 0x5121, 0x512A, 0x512A, 0x5132, 0x5132, 0x5137, 0x5137, 0x513A, 0x513C, 0x513F, 0x5141, 0x5143, 0x5149, 0x514B, 0x514E, 0x5150, 0x5150, 0x5152, 0x5152, 0x5154, 0x5154, 0x515A, 0x515A, 0x515C, 0x515C, 0x5162, 0x5162, 0x5165, 0x5165, 0x5168, 0x516E, 0x5171, 0x5171, 0x5175, 0x5178, 0x517C, 0x517C, 0x5180, 0x5180, 0x5182, 0x5182, 0x5185, 0x5186, 0x5189, 0x518A, 0x518C, 0x518D, 0x518F, 0x5193, 0x5195, 0x5197, 0x5199, 0x5199, 0x51A0, 0x51A0, 0x51A2, 0x51A2, 0x51A4, 0x51A6, 0x51A8, 0x51AC, 0x51B0, 0x51B7, 0x51BD, 0x51BD, 0x51C4, 0x51C6, 0x51C9, 0x51C9, 0x51CB, 0x51CD, 0x51D6, 0x51D6, 0x51DB, 0x51DD, 0x51E0, 0x51E1, 0x51E6, 0x51E7, 0x51E9, 0x51EA, 0x51ED, 0x51ED, 0x51F0, 0x51F1, 0x51F5, 0x51F6, 0x51F8, 0x51FA, 0x51FD, 0x51FE, 0x5200, 0x5200, 0x5203, 0x5204, 0x5206, 0x5208, 0x520A, 0x520B, 0x520E, 0x520E, 0x5211, 0x5211, 0x5214, 0x5214, 0x5217, 0x5217, 0x521D, 0x521D, 0x5224, 0x5225, 0x5227, 0x5227, 0x5229, 0x522A, 0x522E, 0x522E, 0x5230, 0x5230, 0x5233, 0x5233, 0x5236, 0x523B, 0x5243, 0x5244, 0x5247, 0x5247, 0x524A, 0x524D, 0x524F, 0x524F, 0x5254, 0x5254, 0x5256, 0x5256, 0x525B, 0x525B, 0x525E, 0x525E, 0x5263, 0x5265, 0x5269, 0x526A, 0x526F, 0x5275, 0x527D, 0x527D, 0x527F, 0x527F, 0x5283, 0x5283, 0x5287, 0x5289, 0x528D, 0x528D, 0x5291, 0x5292, 0x5294, 0x5294, 0x529B, 0x529B, 0x529F, 0x52A0, 0x52A3, 0x52A3, 0x52A9, 0x52AD, 0x52B1, 0x52B1, 0x52B4, 0x52B5, 0x52B9, 0x52B9, 0x52BC, 0x52BC, 0x52BE, 0x52BE, 0x52C1, 0x52C1, 0x52C3, 0x52C3, 0x52C5, 0x52C5, 0x52C7, 0x52C7, 0x52C9, 0x52C9, 0x52CD, 0x52CD, 0x52D2, 0x52D2, 0x52D5, 0x52D5, 0x52D7, 0x52D9, 0x52DD, 0x52E0, 0x52E2, 0x52E4, 0x52E6, 0x52E7, 0x52F2, 0x52F3, 0x52F5, 0x52F5, 0x52F8, 0x52FA, 0x52FE, 0x52FF, 0x5301, 0x5302, 0x5305, 0x5306, 0x5308, 0x5308, 0x530D, 0x530D, 0x530F, 0x5310, 0x5315, 0x5317, 0x5319, 0x531A, 0x531D, 0x531D, 0x5320, 0x5321, 0x5323, 0x5323, 0x532A, 0x532A, 0x532F, 0x532F, 0x5331, 0x5331, 0x5333, 0x5333, 0x5338, 0x533B, 0x533F, 0x5341, 0x5343, 0x5343, 0x5345, 0x534A, 0x534D, 0x534D, 0x5351, 0x5354, 0x5357, 0x5358, 0x535A, 0x535A, 0x535C, 0x535C, 0x535E, 0x535E, 0x5360, 0x5360, 0x5366, 0x5366, 0x5369, 0x5369, 0x536E, 0x5371, 0x5373, 0x5375, 0x5377, 0x5378, 0x537B, 0x537B, 0x537F, 0x537F, 0x5382, 0x5382, 0x5384, 0x5384, 0x5396, 0x5396, 0x5398, 0x5398, 0x539A, 0x539A, 0x539F, 0x53A0, 0x53A5, 0x53A6, 0x53A8, 0x53A9, 0x53AD, 0x53AE, 0x53B0, 0x53B0, 0x53B3, 0x53B3, 0x53B6, 0x53B6, 0x53BB, 0x53BB, 0x53C2, 0x53C3, 0x53C8, 0x53CE, 0x53D4, 0x53D4, 0x53D6, 0x53D7, 0x53D9, 0x53D9, 0x53DB, 0x53DB, 0x53DF, 0x53DF, 0x53E1, 0x53E5, 0x53E8, 0x53F3, 0x53F6, 0x53F8, 0x53FA, 0x53FA, 0x5401, 0x5401, 0x5403, 0x5404, 0x5408, 0x5411, 0x541B, 0x541B, 0x541D, 0x541D, 0x541F, 0x5420, 0x5426, 0x5426, 0x5429, 0x5429, 0x542B, 0x542E, 0x5436, 0x5436, 0x5438, 0x5439, 0x543B, 0x543E, 0x5440, 0x5440, 0x5442, 0x5442, 0x5446, 0x5446, 0x5448, 0x544A, 0x544E, 0x544E, 0x5451, 0x5451, 0x545F, 0x545F, 0x5468, 0x5468, 0x546A, 0x546A, 0x5470, 0x5471, 0x5473, 0x5473, 0x5475, 0x5477, 0x547B, 0x547D, 0x5480, 0x5480, 0x5484, 0x5484, 0x5486, 0x5486, 0x548B, 0x548C, 0x548E, 0x5490, 0x5492, 0x5492, 0x54A2, 0x54A2, 0x54A4, 0x54A5, 0x54A8, 0x54A8, 0x54AB, 0x54AC, 0x54AF, 0x54AF, 0x54B2, 0x54B3, 0x54B8, 0x54B8, 0x54BC, 0x54BE, 0x54C0, 0x54C2, 0x54C4, 0x54C4, 0x54C7, 0x54C9, 0x54D8, 0x54D8, 0x54E1, 0x54E2, 0x54E5, 0x54E6, 0x54E8, 0x54E9, 0x54ED, 0x54EE, 0x54F2, 0x54F2, 0x54FA, 0x54FA, 0x54FD, 0x54FD, 0x5504, 0x5504, 0x5506, 0x5507, 0x550F, 0x5510, 0x5514, 0x5514, 0x5516, 0x5516, 0x552E, 0x552F, 0x5531, 0x5531, 0x5533, 0x5533, 0x5538, 0x5539, 0x553E, 0x553E, 0x5540, 0x5540, 0x5544, 0x5546, 0x554C, 0x554C, 0x554F, 0x554F, 0x5553, 0x5553, 0x5556, 0x5557, 0x555C, 0x555D, 0x5563, 0x5563, 0x557B, 0x557C, 0x557E, 0x557E, 0x5580, 0x5580, 0x5583, 0x5584, 0x5587, 0x5587, 0x5589, 0x558B, 0x5598, 0x559A, 0x559C, 0x559F, 0x55A7, 0x55AC, 0x55AE, 0x55AE, 0x55B0, 0x55B0, 0x55B6, 0x55B6, 0x55C4, 0x55C5, 0x55C7, 0x55C7, 0x55D4, 0x55D4, 0x55DA, 0x55DA, 0x55DC, 0x55DC, 0x55DF, 0x55DF, 0x55E3, 0x55E4, 0x55F7, 0x55F7, 0x55F9, 0x55F9, 0x55FD, 0x55FE, 0x5606, 0x5606, 0x5609, 0x5609, 0x5614, 0x5614, 0x5616, 0x5618, 0x561B, 0x561B, 0x5629, 0x5629, 0x562F, 0x562F, 0x5631, 0x5632, 0x5634, 0x5634, 0x5636, 0x5636, 0x5638, 0x5638, 0x5642, 0x5642, 0x564C, 0x564C, 0x564E, 0x564E, 0x5650, 0x5650, 0x565B, 0x565B, 0x5664, 0x5664, 0x5668, 0x5668, 0x566A, 0x566C, 0x5674, 0x5674, 0x5678, 0x5678, 0x567A, 0x567A, 0x5680, 0x5680, 0x5686, 0x5687, 0x568A, 0x568A, 0x568F, 0x568F, 0x5694, 0x5694, 0x56A0, 0x56A0, 0x56A2, 0x56A2, 0x56A5, 0x56A5, 0x56AE, 0x56AE, 0x56B4, 0x56B4, 0x56B6, 0x56B6, 0x56BC, 0x56BC, 0x56C0, 0x56C3, 0x56C8, 0x56C8, 0x56CE, 0x56CE, 0x56D1, 0x56D1, 0x56D3, 0x56D3, 0x56D7, 0x56D8, 0x56DA, 0x56DB, 0x56DE, 0x56DE, 0x56E0, 0x56E0, 0x56E3, 0x56E3, 0x56EE, 0x56EE, 0x56F0, 0x56F0, 0x56F2, 0x56F3, 0x56F9, 0x56FA, 0x56FD, 0x56FD, 0x56FF, 0x5700, 0x5703, 0x5704, 0x5708, 0x5709, 0x570B, 0x570B, 0x570D, 0x570D, 0x570F, 0x570F, 0x5712, 0x5713, 0x5716, 0x5716, 0x5718, 0x5718, 0x571C, 0x571C, 0x571F, 0x571F, 0x5726, 0x5728, 0x572D, 0x572D, 0x5730, 0x5730, 0x5737, 0x5738, 0x573B, 0x573B, 0x5740, 0x5740, 0x5742, 0x5742, 0x5747, 0x5747, 0x574A, 0x574A, 0x574E, 0x5751, 0x5761, 0x5761, 0x5764, 0x5764, 0x5766, 0x5766, 0x5769, 0x576A, 0x577F, 0x577F, 0x5782, 0x5782, 0x5788, 0x5789, 0x578B, 0x578B, 0x5793, 0x5793, 0x57A0, 0x57A0, 0x57A2, 0x57A4, 0x57AA, 0x57AA, 0x57B0, 0x57B0, 0x57B3, 0x57B3, 0x57C0, 0x57C0, 0x57C3, 0x57C3, 0x57C6, 0x57C6, 0x57CB, 0x57CB, 0x57CE, 0x57CE, 0x57D2, 0x57D4, 0x57D6, 0x57D6, 0x57DC, 0x57DC, 0x57DF, 0x57E0, 0x57E3, 0x57E3, 0x57F4, 0x57F4, 0x57F7, 0x57F7, 0x57F9, 0x57FA, 0x57FC, 0x57FC, 0x5800, 0x5800, 0x5802, 0x5802, 0x5805, 0x5806, 0x580A, 0x580B, 0x5815, 0x5815, 0x5819, 0x5819, 0x581D, 0x581D, 0x5821, 0x5821, 0x5824, 0x5824, 0x582A, 0x582A, 0x582F, 0x5831, 0x5834, 0x5835, 0x583A, 0x583A, 0x583D, 0x583D, 0x5840, 0x5841, 0x584A, 0x584B, 0x5851, 0x5852, 0x5854, 0x5854, 0x5857, 0x585A, 0x585E, 0x585E, 0x5862, 0x5862, 0x5869, 0x5869, 0x586B, 0x586B, 0x5870, 0x5870, 0x5872, 0x5872, 0x5875, 0x5875, 0x5879, 0x5879, 0x587E, 0x587E, 0x5883, 0x5883, 0x5885, 0x5885, 0x5893, 0x5893, 0x5897, 0x5897, 0x589C, 0x589C, 0x589F, 0x589F, 0x58A8, 0x58A8, 0x58AB, 0x58AB, 0x58AE, 0x58AE, 0x58B3, 0x58B3, 0x58B8, 0x58BB, 0x58BE, 0x58BE, 0x58C1, 0x58C1, 0x58C5, 0x58C5, 0x58C7, 0x58C7, 0x58CA, 0x58CA, 0x58CC, 0x58CC, 0x58D1, 0x58D1, 0x58D3, 0x58D3, 0x58D5, 0x58D5, 0x58D7, 0x58D9, 0x58DC, 0x58DC, 0x58DE, 0x58DF, 0x58E4, 0x58E5, 0x58EB, 0x58EC, 0x58EE, 0x58F2, 0x58F7, 0x58F7, 0x58F9, 0x58FD, 0x5902, 0x5902, 0x5909, 0x590A, 0x590F, 0x5910, 0x5915, 0x5916, 0x5918, 0x591C, 0x5922, 0x5922, 0x5925, 0x5925, 0x5927, 0x5927, 0x5929, 0x592E, 0x5931, 0x5932, 0x5937, 0x5938, 0x593E, 0x593E, 0x5944, 0x5944, 0x5947, 0x5949, 0x594E, 0x5951, 0x5954, 0x5955, 0x5957, 0x5958, 0x595A, 0x595A, 0x5960, 0x5960, 0x5962, 0x5962, 0x5965, 0x5965, 0x5967, 0x596A, 0x596C, 0x596C, 0x596E, 0x596E, 0x5973, 0x5974, 0x5978, 0x5978, 0x597D, 0x597D, 0x5981, 0x5984, 0x598A, 0x598A, 0x598D, 0x598D, 0x5993, 0x5993, 0x5996, 0x5996, 0x5999, 0x5999, 0x599B, 0x599B, 0x599D, 0x599D, 0x59A3, 0x59A3, 0x59A5, 0x59A5, 0x59A8, 0x59A8, 0x59AC, 0x59AC, 0x59B2, 0x59B2, 0x59B9, 0x59B9, 0x59BB, 0x59BB, 0x59BE, 0x59BE, 0x59C6, 0x59C6, 0x59C9, 0x59C9, 0x59CB, 0x59CB, 0x59D0, 0x59D1, 0x59D3, 0x59D4, 0x59D9, 0x59DA, 0x59DC, 0x59DC, 0x59E5, 0x59E6, 0x59E8, 0x59E8, 0x59EA, 0x59EB, 0x59F6, 0x59F6, 0x59FB, 0x59FB, 0x59FF, 0x59FF, 0x5A01, 0x5A01, 0x5A03, 0x5A03, 0x5A09, 0x5A09, 0x5A11, 0x5A11, 0x5A18, 0x5A18, 0x5A1A, 0x5A1A, 0x5A1C, 0x5A1C, 0x5A1F, 0x5A20, 0x5A25, 0x5A25, 0x5A29, 0x5A29, 0x5A2F, 0x5A2F, 0x5A35, 0x5A36, 0x5A3C, 0x5A3C, 0x5A40, 0x5A41, 0x5A46, 0x5A46, 0x5A49, 0x5A49, 0x5A5A, 0x5A5A, 0x5A62, 0x5A62, 0x5A66, 0x5A66, 0x5A6A, 0x5A6A, 0x5A6C, 0x5A6C, 0x5A7F, 0x5A7F, 0x5A92, 0x5A92, 0x5A9A, 0x5A9B, 0x5ABC, 0x5ABE, 0x5AC1, 0x5AC2, 0x5AC9, 0x5AC9, 0x5ACB, 0x5ACC, 0x5AD0, 0x5AD0, 0x5AD6, 0x5AD7, 0x5AE1, 0x5AE1, 0x5AE3, 0x5AE3, 0x5AE6, 0x5AE6, 0x5AE9, 0x5AE9, 0x5AFA, 0x5AFB, 0x5B09, 0x5B09, 0x5B0B, 0x5B0C, 0x5B16, 0x5B16, 0x5B22, 0x5B22, 0x5B2A, 0x5B2A, 0x5B2C, 0x5B2C, 0x5B30, 0x5B30, 0x5B32, 0x5B32, 0x5B36, 0x5B36, 0x5B3E, 0x5B3E, 0x5B40, 0x5B40, 0x5B43, 0x5B43, 0x5B45, 0x5B45, 0x5B50, 0x5B51, 0x5B54, 0x5B55, 0x5B57, 0x5B58, 0x5B5A, 0x5B5D, 0x5B5F, 0x5B5F, 0x5B63, 0x5B66, 0x5B69, 0x5B69, 0x5B6B, 0x5B6B, 0x5B70, 0x5B71, 0x5B73, 0x5B73, 0x5B75, 0x5B75, 0x5B78, 0x5B78, 0x5B7A, 0x5B7A, 0x5B80, 0x5B80, 0x5B83, 0x5B83, 0x5B85, 0x5B85, 0x5B87, 0x5B89, 0x5B8B, 0x5B8D, 0x5B8F, 0x5B8F, 0x5B95, 0x5B95, 0x5B97, 0x5B9D, 0x5B9F, 0x5B9F, 0x5BA2, 0x5BA6, 0x5BAE, 0x5BAE, 0x5BB0, 0x5BB0, 0x5BB3, 0x5BB6, 0x5BB8, 0x5BB9, 0x5BBF, 0x5BBF, 0x5BC2, 0x5BC7, 0x5BC9, 0x5BC9, 0x5BCC, 0x5BCC, 0x5BD0, 0x5BD0, 0x5BD2, 0x5BD4, 0x5BDB, 0x5BDB, 0x5BDD, 0x5BDF, 0x5BE1, 0x5BE2, 0x5BE4, 0x5BE9, 0x5BEB, 0x5BEB, 0x5BEE, 0x5BEE, 0x5BF0, 0x5BF0, 0x5BF3, 0x5BF3, 0x5BF5, 0x5BF6, 0x5BF8, 0x5BF8, 0x5BFA, 0x5BFA, 0x5BFE, 0x5BFF, 0x5C01, 0x5C02, 0x5C04, 0x5C0B, 0x5C0D, 0x5C0F, 0x5C11, 0x5C11, 0x5C13, 0x5C13, 0x5C16, 0x5C16, 0x5C1A, 0x5C1A, 0x5C20, 0x5C20, 0x5C22, 0x5C22, 0x5C24, 0x5C24, 0x5C28, 0x5C28, 0x5C2D, 0x5C2D, 0x5C31, 0x5C31, 0x5C38, 0x5C41, 0x5C45, 0x5C46, 0x5C48, 0x5C48, 0x5C4A, 0x5C4B, 0x5C4D, 0x5C51, 0x5C53, 0x5C53, 0x5C55, 0x5C55, 0x5C5E, 0x5C5E, 0x5C60, 0x5C61, 0x5C64, 0x5C65, 0x5C6C, 0x5C6C, 0x5C6E, 0x5C6F, 0x5C71, 0x5C71, 0x5C76, 0x5C76, 0x5C79, 0x5C79, 0x5C8C, 0x5C8C, 0x5C90, 0x5C91, 0x5C94, 0x5C94, 0x5CA1, 0x5CA1, 0x5CA8, 0x5CA9, 0x5CAB, 0x5CAC, 0x5CB1, 0x5CB1, 0x5CB3, 0x5CB3, 0x5CB6, 0x5CB8, 0x5CBB, 0x5CBC, 0x5CBE, 0x5CBE, 0x5CC5, 0x5CC5, 0x5CC7, 0x5CC7, 0x5CD9, 0x5CD9, 0x5CE0, 0x5CE1, 0x5CE8, 0x5CEA, 0x5CED, 0x5CED, 0x5CEF, 0x5CF0, 0x5CF6, 0x5CF6, 0x5CFA, 0x5CFB, 0x5CFD, 0x5CFD, 0x5D07, 0x5D07, 0x5D0B, 0x5D0B, 0x5D0E, 0x5D0E, 0x5D11, 0x5D11, 0x5D14, 0x5D1B, 0x5D1F, 0x5D1F, 0x5D22, 0x5D22, 0x5D29, 0x5D29, 0x5D4B, 0x5D4C, 0x5D4E, 0x5D4E, 0x5D50, 0x5D50, 0x5D52, 0x5D52, 0x5D5C, 0x5D5C, 0x5D69, 0x5D69, 0x5D6C, 0x5D6C, 0x5D6F, 0x5D6F, 0x5D73, 0x5D73, 0x5D76, 0x5D76, 0x5D82, 0x5D82, 0x5D84, 0x5D84, 0x5D87, 0x5D87, 0x5D8B, 0x5D8C, 0x5D90, 0x5D90, 0x5D9D, 0x5D9D, 0x5DA2, 0x5DA2, 0x5DAC, 0x5DAC, 0x5DAE, 0x5DAE, 0x5DB7, 0x5DB7, 0x5DBA, 0x5DBA, 0x5DBC, 0x5DBD, 0x5DC9, 0x5DC9, 0x5DCC, 0x5DCD, 0x5DD2, 0x5DD3, 0x5DD6, 0x5DD6, 0x5DDB, 0x5DDB, 0x5DDD, 0x5DDE, 0x5DE1, 0x5DE1, 0x5DE3, 0x5DE3, 0x5DE5, 0x5DE8, 0x5DEB, 0x5DEB, 0x5DEE, 0x5DEE, 0x5DF1, 0x5DF5, 0x5DF7, 0x5DF7, 0x5DFB, 0x5DFB, 0x5DFD, 0x5DFE, 0x5E02, 0x5E03, 0x5E06, 0x5E06, 0x5E0B, 0x5E0C, 0x5E11, 0x5E11, 0x5E16, 0x5E16, 0x5E19, 0x5E1B, 0x5E1D, 0x5E1D, 0x5E25, 0x5E25, 0x5E2B, 0x5E2B, 0x5E2D, 0x5E2D, 0x5E2F, 0x5E30, 0x5E33, 0x5E33, 0x5E36, 0x5E38, 0x5E3D, 0x5E3D, 0x5E40, 0x5E40, 0x5E43, 0x5E45, 0x5E47, 0x5E47, 0x5E4C, 0x5E4C, 0x5E4E, 0x5E4E, 0x5E54, 0x5E55, 0x5E57, 0x5E57, 0x5E5F, 0x5E5F, 0x5E61, 0x5E64, 0x5E72, 0x5E76, 0x5E78, 0x5E7F, 0x5E81, 0x5E81, 0x5E83, 0x5E84, 0x5E87, 0x5E87, 0x5E8A, 0x5E8A, 0x5E8F, 0x5E8F, 0x5E95, 0x5E97, 0x5E9A, 0x5E9A, 0x5E9C, 0x5E9C, 0x5EA0, 0x5EA0, 0x5EA6, 0x5EA7, 0x5EAB, 0x5EAB, 0x5EAD, 0x5EAD, 0x5EB5, 0x5EB8, 0x5EC1, 0x5EC3, 0x5EC8, 0x5ECA, 0x5ECF, 0x5ED0, 0x5ED3, 0x5ED3, 0x5ED6, 0x5ED6, 0x5EDA, 0x5EDB, 0x5EDD, 0x5EDD, 0x5EDF, 0x5EE3, 0x5EE8, 0x5EE9, 0x5EEC, 0x5EEC, 0x5EF0, 0x5EF1, 0x5EF3, 0x5EF4, 0x5EF6, 0x5EF8, 0x5EFA, 0x5EFC, 0x5EFE, 0x5EFF, 0x5F01, 0x5F01, 0x5F03, 0x5F04, 0x5F09, 0x5F0D, 0x5F0F, 0x5F11, 0x5F13, 0x5F18, 0x5F1B, 0x5F1B, 0x5F1F, 0x5F1F, 0x5F25, 0x5F27, 0x5F29, 0x5F29, 0x5F2D, 0x5F2D, 0x5F2F, 0x5F2F, 0x5F31, 0x5F31, 0x5F35, 0x5F35, 0x5F37, 0x5F38, 0x5F3C, 0x5F3C, 0x5F3E, 0x5F3E, 0x5F41, 0x5F41, 0x5F48, 0x5F48, 0x5F4A, 0x5F4A, 0x5F4C, 0x5F4C, 0x5F4E, 0x5F4E, 0x5F51, 0x5F51, 0x5F53, 0x5F53, 0x5F56, 0x5F57, 0x5F59, 0x5F59, 0x5F5C, 0x5F5D, 0x5F61, 0x5F62, 0x5F66, 0x5F66, 0x5F69, 0x5F6D, 0x5F70, 0x5F71, 0x5F73, 0x5F73, 0x5F77, 0x5F77, 0x5F79, 0x5F79, 0x5F7C, 0x5F7C, 0x5F7F, 0x5F85, 0x5F87, 0x5F88, 0x5F8A, 0x5F8C, 0x5F90, 0x5F93, 0x5F97, 0x5F99, 0x5F9E, 0x5F9E, 0x5FA0, 0x5FA1, 0x5FA8, 0x5FAA, 0x5FAD, 0x5FAE, 0x5FB3, 0x5FB4, 0x5FB9, 0x5FB9, 0x5FBC, 0x5FBD, 0x5FC3, 0x5FC3, 0x5FC5, 0x5FC5, 0x5FCC, 0x5FCD, 0x5FD6, 0x5FD9, 0x5FDC, 0x5FDD, 0x5FE0, 0x5FE0, 0x5FE4, 0x5FE4, 0x5FEB, 0x5FEB, 0x5FF0, 0x5FF1, 0x5FF5, 0x5FF5, 0x5FF8, 0x5FF8, 0x5FFB, 0x5FFB, 0x5FFD, 0x5FFD, 0x5FFF, 0x5FFF, 0x600E, 0x6010, 0x6012, 0x6012, 0x6015, 0x6016, 0x6019, 0x6019, 0x601B, 0x601D, 0x6020, 0x6021, 0x6025, 0x602B, 0x602F, 0x602F, 0x6031, 0x6031, 0x603A, 0x603A, 0x6041, 0x6043, 0x6046, 0x6046, 0x604A, 0x604B, 0x604D, 0x604D, 0x6050, 0x6050, 0x6052, 0x6052, 0x6055, 0x6055, 0x6059, 0x605A, 0x605F, 0x6060, 0x6062, 0x6065, 0x6068, 0x606D, 0x606F, 0x6070, 0x6075, 0x6075, 0x6077, 0x6077, 0x6081, 0x6081, 0x6083, 0x6084, 0x6089, 0x6089, 0x608B, 0x608D, 0x6092, 0x6092, 0x6094, 0x6094, 0x6096, 0x6097, 0x609A, 0x609B, 0x609F, 0x60A0, 0x60A3, 0x60A3, 0x60A6, 0x60A7, 0x60A9, 0x60AA, 0x60B2, 0x60B6, 0x60B8, 0x60B8, 0x60BC, 0x60BD, 0x60C5, 0x60C7, 0x60D1, 0x60D1, 0x60D3, 0x60D3, 0x60D8, 0x60D8, 0x60DA, 0x60DA, 0x60DC, 0x60DC, 0x60DF, 0x60E1, 0x60E3, 0x60E3, 0x60E7, 0x60E8, 0x60F0, 0x60F1, 0x60F3, 0x60F4, 0x60F6, 0x60F7, 0x60F9, 0x60FB, 0x6100, 0x6101, 0x6103, 0x6103, 0x6106, 0x6106, 0x6108, 0x6109, 0x610D, 0x610F, 0x6115, 0x6115, 0x611A, 0x611B, 0x611F, 0x611F, 0x6121, 0x6121, 0x6127, 0x6128, 0x612C, 0x612C, 0x6134, 0x6134, 0x613C, 0x613F, 0x6142, 0x6142, 0x6144, 0x6144, 0x6147, 0x6148, 0x614A, 0x614E, 0x6153, 0x6153, 0x6155, 0x6155, 0x6158, 0x615A, 0x615D, 0x615D, 0x615F, 0x615F, 0x6162, 0x6163, 0x6165, 0x6165, 0x6167, 0x6168, 0x616B, 0x616B, 0x616E, 0x6171, 0x6173, 0x6177, 0x617E, 0x617E, 0x6182, 0x6182, 0x6187, 0x6187, 0x618A, 0x618A, 0x618E, 0x618E, 0x6190, 0x6191, 0x6194, 0x6194, 0x6196, 0x6196, 0x6199, 0x619A, 0x61A4, 0x61A4, 0x61A7, 0x61A7, 0x61A9, 0x61A9, 0x61AB, 0x61AC, 0x61AE, 0x61AE, 0x61B2, 0x61B2, 0x61B6, 0x61B6, 0x61BA, 0x61BA, 0x61BE, 0x61BE, 0x61C3, 0x61C3, 0x61C6, 0x61CD, 0x61D0, 0x61D0, 0x61E3, 0x61E3, 0x61E6, 0x61E6, 0x61F2, 0x61F2, 0x61F4, 0x61F4, 0x61F6, 0x61F8, 0x61FA, 0x61FA, 0x61FC, 0x6200, 0x6208, 0x620A, 0x620C, 0x620E, 0x6210, 0x6212, 0x6214, 0x6214, 0x6216, 0x6216, 0x621A, 0x621B, 0x621D, 0x621F, 0x6221, 0x6221, 0x6226, 0x6226, 0x622A, 0x622A, 0x622E, 0x6230, 0x6232, 0x6234, 0x6238, 0x6238, 0x623B, 0x623B, 0x623F, 0x6241, 0x6247, 0x6249, 0x624B, 0x624B, 0x624D, 0x624E, 0x6253, 0x6253, 0x6255, 0x6255, 0x6258, 0x6258, 0x625B, 0x625B, 0x625E, 0x625E, 0x6260, 0x6260, 0x6263, 0x6263, 0x6268, 0x6268, 0x626E, 0x626E, 0x6271, 0x6271, 0x6276, 0x6276, 0x6279, 0x6279, 0x627C, 0x627C, 0x627E, 0x6280, 0x6282, 0x6284, 0x6289, 0x628A, 0x6291, 0x6298, 0x629B, 0x629C, 0x629E, 0x629E, 0x62AB, 0x62AC, 0x62B1, 0x62B1, 0x62B5, 0x62B5, 0x62B9, 0x62B9, 0x62BB, 0x62BD, 0x62C2, 0x62C2, 0x62C5, 0x62CA, 0x62CC, 0x62CD, 0x62CF, 0x62D4, 0x62D7, 0x62D9, 0x62DB, 0x62DD, 0x62E0, 0x62E1, 0x62EC, 0x62EF, 0x62F1, 0x62F1, 0x62F3, 0x62F3, 0x62F5, 0x62F7, 0x62FE, 0x62FF, 0x6301, 0x6302, 0x6307, 0x6309, 0x630C, 0x630C, 0x6311, 0x6311, 0x6319, 0x6319, 0x631F, 0x631F, 0x6327, 0x6328, 0x632B, 0x632B, 0x632F, 0x632F, 0x633A, 0x633A, 0x633D, 0x633F, 0x6349, 0x6349, 0x634C, 0x634D, 0x634F, 0x6350, 0x6355, 0x6355, 0x6357, 0x6357, 0x635C, 0x635C, 0x6367, 0x6369, 0x636B, 0x636B, 0x636E, 0x636E, 0x6372, 0x6372, 0x6376, 0x6377, 0x637A, 0x637B, 0x6380, 0x6380, 0x6383, 0x6383, 0x6388, 0x6389, 0x638C, 0x638C, 0x638E, 0x638F, 0x6392, 0x6392, 0x6396, 0x6396, 0x6398, 0x6398, 0x639B, 0x639B, 0x639F, 0x63A3, 0x63A5, 0x63A5, 0x63A7, 0x63AC, 0x63B2, 0x63B2, 0x63B4, 0x63B5, 0x63BB, 0x63BB, 0x63BE, 0x63BE, 0x63C0, 0x63C0, 0x63C3, 0x63C4, 0x63C6, 0x63C6, 0x63C9, 0x63C9, 0x63CF, 0x63D0, 0x63D2, 0x63D2, 0x63D6, 0x63D6, 0x63DA, 0x63DB, 0x63E1, 0x63E1, 0x63E3, 0x63E3, 0x63E9, 0x63E9, 0x63EE, 0x63EE, 0x63F4, 0x63F4, 0x63F6, 0x63F6, 0x63FA, 0x63FA, 0x6406, 0x6406, 0x640D, 0x640D, 0x640F, 0x640F, 0x6413, 0x6413, 0x6416, 0x6417, 0x641C, 0x641C, 0x6426, 0x6426, 0x6428, 0x6428, 0x642C, 0x642D, 0x6434, 0x6434, 0x6436, 0x6436, 0x643A, 0x643A, 0x643E, 0x643E, 0x6442, 0x6442, 0x644E, 0x644E, 0x6458, 0x6458, 0x6467, 0x6467, 0x6469, 0x6469, 0x646F, 0x646F, 0x6476, 0x6476, 0x6478, 0x6478, 0x647A, 0x647A, 0x6483, 0x6483, 0x6488, 0x6488, 0x6492, 0x6493, 0x6495, 0x6495, 0x649A, 0x649A, 0x649E, 0x649E, 0x64A4, 0x64A5, 0x64A9, 0x64A9, 0x64AB, 0x64AB, 0x64AD, 0x64AE, 0x64B0, 0x64B0, 0x64B2, 0x64B2, 0x64B9, 0x64B9, 0x64BB, 0x64BC, 0x64C1, 0x64C2, 0x64C5, 0x64C5, 0x64C7, 0x64C7, 0x64CD, 0x64CD, 0x64D2, 0x64D2, 0x64D4, 0x64D4, 0x64D8, 0x64D8, 0x64DA, 0x64DA, 0x64E0, 0x64E3, 0x64E6, 0x64E7, 0x64EC, 0x64EC, 0x64EF, 0x64EF, 0x64F1, 0x64F2, 0x64F4, 0x64F4, 0x64F6, 0x64F6, 0x64FA, 0x64FA, 0x64FD, 0x64FE, 0x6500, 0x6500, 0x6505, 0x6505, 0x6518, 0x6518, 0x651C, 0x651D, 0x6523, 0x6524, 0x652A, 0x652C, 0x652F, 0x652F, 0x6534, 0x6539, 0x653B, 0x653B, 0x653E, 0x653F, 0x6545, 0x6545, 0x6548, 0x6548, 0x654D, 0x654D, 0x654F, 0x654F, 0x6551, 0x6551, 0x6555, 0x6559, 0x655D, 0x655E, 0x6562, 0x6563, 0x6566, 0x6566, 0x656C, 0x656C, 0x6570, 0x6570, 0x6572, 0x6572, 0x6574, 0x6575, 0x6577, 0x6578, 0x6582, 0x6583, 0x6587, 0x6589, 0x658C, 0x658C, 0x658E, 0x658E, 0x6590, 0x6591, 0x6597, 0x6597, 0x6599, 0x6599, 0x659B, 0x659C, 0x659F, 0x659F, 0x65A1, 0x65A1, 0x65A4, 0x65A5, 0x65A7, 0x65A7, 0x65AB, 0x65AD, 0x65AF, 0x65B0, 0x65B7, 0x65B7, 0x65B9, 0x65B9, 0x65BC, 0x65BD, 0x65C1, 0x65C1, 0x65C3, 0x65C6, 0x65CB, 0x65CC, 0x65CF, 0x65CF, 0x65D2, 0x65D2, 0x65D7, 0x65D7, 0x65D9, 0x65D9, 0x65DB, 0x65DB, 0x65E0, 0x65E2, 0x65E5, 0x65E9, 0x65EC, 0x65ED, 0x65F1, 0x65F1, 0x65FA, 0x65FB, 0x6602, 0x6603, 0x6606, 0x6607, 0x660A, 0x660A, 0x660C, 0x660C, 0x660E, 0x660F, 0x6613, 0x6614, 0x661C, 0x661C, 0x661F, 0x6620, 0x6625, 0x6625, 0x6627, 0x6628, 0x662D, 0x662D, 0x662F, 0x662F, 0x6634, 0x6636, 0x663C, 0x663C, 0x663F, 0x663F, 0x6641, 0x6644, 0x6649, 0x6649, 0x664B, 0x664B, 0x664F, 0x664F, 0x6652, 0x6652, 0x665D, 0x665F, 0x6662, 0x6662, 0x6664, 0x6664, 0x6666, 0x6669, 0x666E, 0x6670, 0x6674, 0x6674, 0x6676, 0x6676, 0x667A, 0x667A, 0x6681, 0x6681, 0x6683, 0x6684, 0x6687, 0x6689, 0x668E, 0x668E, 0x6691, 0x6691, 0x6696, 0x6698, 0x669D, 0x669D, 0x66A2, 0x66A2, 0x66A6, 0x66A6, 0x66AB, 0x66AB, 0x66AE, 0x66AE, 0x66B4, 0x66B4, 0x66B8, 0x66B9, 0x66BC, 0x66BC, 0x66BE, 0x66BE, 0x66C1, 0x66C1, 0x66C4, 0x66C4, 0x66C7, 0x66C7, 0x66C9, 0x66C9, 0x66D6, 0x66D6, 0x66D9, 0x66DA, 0x66DC, 0x66DD, 0x66E0, 0x66E0, 0x66E6, 0x66E6, 0x66E9, 0x66E9, 0x66F0, 0x66F0, 0x66F2, 0x66F5, 0x66F7, 0x66F9, 0x66FC, 0x6700, 0x6703, 0x6703, 0x6708, 0x6709, 0x670B, 0x670B, 0x670D, 0x670D, 0x670F, 0x670F, 0x6714, 0x6717, 0x671B, 0x671B, 0x671D, 0x671F, 0x6726, 0x6728, 0x672A, 0x672E, 0x6731, 0x6731, 0x6734, 0x6734, 0x6736, 0x6738, 0x673A, 0x673A, 0x673D, 0x673D, 0x673F, 0x673F, 0x6741, 0x6741, 0x6746, 0x6746, 0x6749, 0x6749, 0x674E, 0x6751, 0x6753, 0x6753, 0x6756, 0x6756, 0x6759, 0x6759, 0x675C, 0x675C, 0x675E, 0x6765, 0x676A, 0x676A, 0x676D, 0x676D, 0x676F, 0x6773, 0x6775, 0x6775, 0x6777, 0x6777, 0x677C, 0x677C, 0x677E, 0x677F, 0x6785, 0x6785, 0x6787, 0x6787, 0x6789, 0x6789, 0x678B, 0x678C, 0x6790, 0x6790, 0x6795, 0x6795, 0x6797, 0x6797, 0x679A, 0x679A, 0x679C, 0x679D, 0x67A0, 0x67A2, 0x67A6, 0x67A6, 0x67A9, 0x67A9, 0x67AF, 0x67AF, 0x67B3, 0x67B4, 0x67B6, 0x67B9, 0x67C1, 0x67C1, 0x67C4, 0x67C4, 0x67C6, 0x67C6, 0x67CA, 0x67CA, 0x67CE, 0x67D1, 0x67D3, 0x67D4, 0x67D8, 0x67D8, 0x67DA, 0x67DA, 0x67DD, 0x67DE, 0x67E2, 0x67E2, 0x67E4, 0x67E4, 0x67E7, 0x67E7, 0x67E9, 0x67E9, 0x67EC, 0x67EC, 0x67EE, 0x67EF, 0x67F1, 0x67F1, 0x67F3, 0x67F5, 0x67FB, 0x67FB, 0x67FE, 0x67FF, 0x6802, 0x6804, 0x6813, 0x6813, 0x6816, 0x6817, 0x681E, 0x681E, 0x6821, 0x6822, 0x6829, 0x682B, 0x6832, 0x6832, 0x6834, 0x6834, 0x6838, 0x6839, 0x683C, 0x683D, 0x6840, 0x6843, 0x6846, 0x6846, 0x6848, 0x6848, 0x684D, 0x684E, 0x6850, 0x6851, 0x6853, 0x6854, 0x6859, 0x6859, 0x685C, 0x685D, 0x685F, 0x685F, 0x6863, 0x6863, 0x6867, 0x6867, 0x6874, 0x6874, 0x6876, 0x6877, 0x687E, 0x687F, 0x6881, 0x6881, 0x6883, 0x6883, 0x6885, 0x6885, 0x688D, 0x688D, 0x688F, 0x688F, 0x6893, 0x6894, 0x6897, 0x6897, 0x689B, 0x689B, 0x689D, 0x689D, 0x689F, 0x68A0, 0x68A2, 0x68A2, 0x68A6, 0x68A8, 0x68AD, 0x68AD, 0x68AF, 0x68B1, 0x68B3, 0x68B3, 0x68B5, 0x68B6, 0x68B9, 0x68BA, 0x68BC, 0x68BC, 0x68C4, 0x68C4, 0x68C6, 0x68C6, 0x68C9, 0x68CB, 0x68CD, 0x68CD, 0x68D2, 0x68D2, 0x68D4, 0x68D5, 0x68D7, 0x68D8, 0x68DA, 0x68DA, 0x68DF, 0x68E1, 0x68E3, 0x68E3, 0x68E7, 0x68E7, 0x68EE, 0x68EF, 0x68F2, 0x68F2, 0x68F9, 0x68FA, 0x6900, 0x6901, 0x6904, 0x6905, 0x6908, 0x6908, 0x690B, 0x690F, 0x6912, 0x6912, 0x6919, 0x691C, 0x6921, 0x6923, 0x6925, 0x6926, 0x6928, 0x6928, 0x692A, 0x692A, 0x6930, 0x6930, 0x6934, 0x6934, 0x6936, 0x6936, 0x6939, 0x6939, 0x693D, 0x693D, 0x693F, 0x693F, 0x694A, 0x694A, 0x6953, 0x6955, 0x6959, 0x695A, 0x695C, 0x695E, 0x6960, 0x6962, 0x696A, 0x696B, 0x696D, 0x696F, 0x6973, 0x6975, 0x6977, 0x6979, 0x697C, 0x697E, 0x6981, 0x6982, 0x698A, 0x698A, 0x698E, 0x698E, 0x6991, 0x6991, 0x6994, 0x6995, 0x699B, 0x699C, 0x69A0, 0x69A0, 0x69A7, 0x69A7, 0x69AE, 0x69AE, 0x69B1, 0x69B2, 0x69B4, 0x69B4, 0x69BB, 0x69BB, 0x69BE, 0x69BF, 0x69C1, 0x69C1, 0x69C3, 0x69C3, 0x69C7, 0x69C7, 0x69CA, 0x69CE, 0x69D0, 0x69D0, 0x69D3, 0x69D3, 0x69D8, 0x69D9, 0x69DD, 0x69DE, 0x69E7, 0x69E8, 0x69EB, 0x69EB, 0x69ED, 0x69ED, 0x69F2, 0x69F2, 0x69F9, 0x69F9, 0x69FB, 0x69FB, 0x69FD, 0x69FD, 0x69FF, 0x69FF, 0x6A02, 0x6A02, 0x6A05, 0x6A05, 0x6A0A, 0x6A0C, 0x6A12, 0x6A14, 0x6A17, 0x6A17, 0x6A19, 0x6A19, 0x6A1B, 0x6A1B, 0x6A1E, 0x6A1F, 0x6A21, 0x6A23, 0x6A29, 0x6A2B, 0x6A2E, 0x6A2E, 0x6A35, 0x6A36, 0x6A38, 0x6A3A, 0x6A3D, 0x6A3D, 0x6A44, 0x6A44, 0x6A47, 0x6A48, 0x6A4B, 0x6A4B, 0x6A58, 0x6A59, 0x6A5F, 0x6A5F, 0x6A61, 0x6A62, 0x6A66, 0x6A66, 0x6A72, 0x6A72, 0x6A78, 0x6A78, 0x6A7F, 0x6A80, 0x6A84, 0x6A84, 0x6A8D, 0x6A8E, 0x6A90, 0x6A90, 0x6A97, 0x6A97, 0x6A9C, 0x6A9C, 0x6AA0, 0x6AA0, 0x6AA2, 0x6AA3, 0x6AAA, 0x6AAA, 0x6AAC, 0x6AAC, 0x6AAE, 0x6AAE, 0x6AB3, 0x6AB3, 0x6AB8, 0x6AB8, 0x6ABB, 0x6ABB, 0x6AC1, 0x6AC3, 0x6AD1, 0x6AD1, 0x6AD3, 0x6AD3, 0x6ADA, 0x6ADB, 0x6ADE, 0x6ADF, 0x6AE8, 0x6AE8, 0x6AEA, 0x6AEA, 0x6AFA, 0x6AFB, 0x6B04, 0x6B05, 0x6B0A, 0x6B0A, 0x6B12, 0x6B12, 0x6B16, 0x6B16, 0x6B1D, 0x6B1D, 0x6B1F, 0x6B21, 0x6B23, 0x6B23, 0x6B27, 0x6B27, 0x6B32, 0x6B32, 0x6B37, 0x6B3A, 0x6B3D, 0x6B3E, 0x6B43, 0x6B43, 0x6B47, 0x6B47, 0x6B49, 0x6B49, 0x6B4C, 0x6B4C, 0x6B4E, 0x6B4E, 0x6B50, 0x6B50, 0x6B53, 0x6B54, 0x6B59, 0x6B59, 0x6B5B, 0x6B5B, 0x6B5F, 0x6B5F, 0x6B61, 0x6B64, 0x6B66, 0x6B66, 0x6B69, 0x6B6A, 0x6B6F, 0x6B6F, 0x6B73, 0x6B74, 0x6B78, 0x6B79, 0x6B7B, 0x6B7B, 0x6B7F, 0x6B80, 0x6B83, 0x6B84, 0x6B86, 0x6B86, 0x6B89, 0x6B8B, 0x6B8D, 0x6B8D, 0x6B95, 0x6B96, 0x6B98, 0x6B98, 0x6B9E, 0x6B9E, 0x6BA4, 0x6BA4, 0x6BAA, 0x6BAB, 0x6BAF, 0x6BAF, 0x6BB1, 0x6BB5, 0x6BB7, 0x6BB7, 0x6BBA, 0x6BBC, 0x6BBF, 0x6BC0, 0x6BC5, 0x6BC6, 0x6BCB, 0x6BCB, 0x6BCD, 0x6BCE, 0x6BD2, 0x6BD4, 0x6BD8, 0x6BD8, 0x6BDB, 0x6BDB, 0x6BDF, 0x6BDF, 0x6BEB, 0x6BEC, 0x6BEF, 0x6BEF, 0x6BF3, 0x6BF3, 0x6C08, 0x6C08, 0x6C0F, 0x6C0F, 0x6C11, 0x6C11, 0x6C13, 0x6C14, 0x6C17, 0x6C17, 0x6C1B, 0x6C1B, 0x6C23, 0x6C24, 0x6C34, 0x6C34, 0x6C37, 0x6C38, 0x6C3E, 0x6C3E, 0x6C40, 0x6C42, 0x6C4E, 0x6C4E, 0x6C50, 0x6C50, 0x6C55, 0x6C55, 0x6C57, 0x6C57, 0x6C5A, 0x6C5A, 0x6C5D, 0x6C60, 0x6C62, 0x6C62, 0x6C68, 0x6C68, 0x6C6A, 0x6C6A, 0x6C70, 0x6C70, 0x6C72, 0x6C73, 0x6C7A, 0x6C7A, 0x6C7D, 0x6C7E, 0x6C81, 0x6C83, 0x6C88, 0x6C88, 0x6C8C, 0x6C8D, 0x6C90, 0x6C90, 0x6C92, 0x6C93, 0x6C96, 0x6C96, 0x6C99, 0x6C9B, 0x6CA1, 0x6CA2, 0x6CAB, 0x6CAB, 0x6CAE, 0x6CAE, 0x6CB1, 0x6CB1, 0x6CB3, 0x6CB3, 0x6CB8, 0x6CBF, 0x6CC1, 0x6CC1, 0x6CC4, 0x6CC5, 0x6CC9, 0x6CCA, 0x6CCC, 0x6CCC, 0x6CD3, 0x6CD3, 0x6CD5, 0x6CD5, 0x6CD7, 0x6CD7, 0x6CD9, 0x6CD9, 0x6CDB, 0x6CDB, 0x6CDD, 0x6CDD, 0x6CE1, 0x6CE3, 0x6CE5, 0x6CE5, 0x6CE8, 0x6CE8, 0x6CEA, 0x6CEA, 0x6CEF, 0x6CF1, 0x6CF3, 0x6CF3, 0x6D0B, 0x6D0C, 0x6D12, 0x6D12, 0x6D17, 0x6D17, 0x6D19, 0x6D19, 0x6D1B, 0x6D1B, 0x6D1E, 0x6D1F, 0x6D25, 0x6D25, 0x6D29, 0x6D2B, 0x6D32, 0x6D33, 0x6D35, 0x6D36, 0x6D38, 0x6D38, 0x6D3B, 0x6D3B, 0x6D3D, 0x6D3E, 0x6D41, 0x6D41, 0x6D44, 0x6D45, 0x6D59, 0x6D5A, 0x6D5C, 0x6D5C, 0x6D63, 0x6D64, 0x6D66, 0x6D66, 0x6D69, 0x6D6A, 0x6D6C, 0x6D6C, 0x6D6E, 0x6D6E, 0x6D74, 0x6D74, 0x6D77, 0x6D79, 0x6D85, 0x6D85, 0x6D88, 0x6D88, 0x6D8C, 0x6D8C, 0x6D8E, 0x6D8E, 0x6D93, 0x6D93, 0x6D95, 0x6D95, 0x6D99, 0x6D99, 0x6D9B, 0x6D9C, 0x6DAF, 0x6DAF, 0x6DB2, 0x6DB2, 0x6DB5, 0x6DB5, 0x6DB8, 0x6DB8, 0x6DBC, 0x6DBC, 0x6DC0, 0x6DC0, 0x6DC5, 0x6DC7, 0x6DCB, 0x6DCC, 0x6DD1, 0x6DD2, 0x6DD5, 0x6DD5, 0x6DD8, 0x6DD9, 0x6DDE, 0x6DDE, 0x6DE1, 0x6DE1, 0x6DE4, 0x6DE4, 0x6DE6, 0x6DE6, 0x6DE8, 0x6DE8, 0x6DEA, 0x6DEC, 0x6DEE, 0x6DEE, 0x6DF1, 0x6DF1, 0x6DF3, 0x6DF3, 0x6DF5, 0x6DF5, 0x6DF7, 0x6DF7, 0x6DF9, 0x6DFB, 0x6E05, 0x6E05, 0x6E07, 0x6E0B, 0x6E13, 0x6E13, 0x6E15, 0x6E15, 0x6E19, 0x6E1B, 0x6E1D, 0x6E1D, 0x6E1F, 0x6E21, 0x6E23, 0x6E26, 0x6E29, 0x6E29, 0x6E2B, 0x6E2F, 0x6E38, 0x6E38, 0x6E3A, 0x6E3A, 0x6E3E, 0x6E3E, 0x6E43, 0x6E43, 0x6E4A, 0x6E4A, 0x6E4D, 0x6E4E, 0x6E56, 0x6E56, 0x6E58, 0x6E58, 0x6E5B, 0x6E5B, 0x6E5F, 0x6E5F, 0x6E67, 0x6E67, 0x6E6B, 0x6E6B, 0x6E6E, 0x6E6F, 0x6E72, 0x6E72, 0x6E76, 0x6E76, 0x6E7E, 0x6E80, 0x6E82, 0x6E82, 0x6E8C, 0x6E8C, 0x6E8F, 0x6E90, 0x6E96, 0x6E96, 0x6E98, 0x6E98, 0x6E9C, 0x6E9D, 0x6E9F, 0x6E9F, 0x6EA2, 0x6EA2, 0x6EA5, 0x6EA5, 0x6EAA, 0x6EAA, 0x6EAF, 0x6EAF, 0x6EB2, 0x6EB2, 0x6EB6, 0x6EB7, 0x6EBA, 0x6EBA, 0x6EBD, 0x6EBD, 0x6EC2, 0x6EC2, 0x6EC4, 0x6EC5, 0x6EC9, 0x6EC9, 0x6ECB, 0x6ECC, 0x6ED1, 0x6ED1, 0x6ED3, 0x6ED5, 0x6EDD, 0x6EDE, 0x6EEC, 0x6EEC, 0x6EEF, 0x6EEF, 0x6EF2, 0x6EF2, 0x6EF4, 0x6EF4, 0x6EF7, 0x6EF8, 0x6EFE, 0x6EFF, 0x6F01, 0x6F02, 0x6F06, 0x6F06, 0x6F09, 0x6F09, 0x6F0F, 0x6F0F, 0x6F11, 0x6F11, 0x6F13, 0x6F15, 0x6F20, 0x6F20, 0x6F22, 0x6F23, 0x6F2B, 0x6F2C, 0x6F31, 0x6F32, 0x6F38, 0x6F38, 0x6F3E, 0x6F3F, 0x6F41, 0x6F41, 0x6F45, 0x6F45, 0x6F54, 0x6F54, 0x6F58, 0x6F58, 0x6F5B, 0x6F5C, 0x6F5F, 0x6F5F, 0x6F64, 0x6F64, 0x6F66, 0x6F66, 0x6F6D, 0x6F70, 0x6F74, 0x6F74, 0x6F78, 0x6F78, 0x6F7A, 0x6F7A, 0x6F7C, 0x6F7C, 0x6F80, 0x6F82, 0x6F84, 0x6F84, 0x6F86, 0x6F86, 0x6F8E, 0x6F8E, 0x6F91, 0x6F91, 0x6F97, 0x6F97, 0x6FA1, 0x6FA1, 0x6FA3, 0x6FA4, 0x6FAA, 0x6FAA, 0x6FB1, 0x6FB1, 0x6FB3, 0x6FB3, 0x6FB9, 0x6FB9, 0x6FC0, 0x6FC3, 0x6FC6, 0x6FC6, 0x6FD4, 0x6FD5, 0x6FD8, 0x6FD8, 0x6FDB, 0x6FDB, 0x6FDF, 0x6FE1, 0x6FE4, 0x6FE4, 0x6FEB, 0x6FEC, 0x6FEE, 0x6FEF, 0x6FF1, 0x6FF1, 0x6FF3, 0x6FF3, 0x6FF6, 0x6FF6, 0x6FFA, 0x6FFA, 0x6FFE, 0x6FFE, 0x7001, 0x7001, 0x7009, 0x7009, 0x700B, 0x700B, 0x700F, 0x700F, 0x7011, 0x7011, 0x7015, 0x7015, 0x7018, 0x7018, 0x701A, 0x701B, 0x701D, 0x701F, 0x7026, 0x7027, 0x702C, 0x702C, 0x7030, 0x7030, 0x7032, 0x7032, 0x703E, 0x703E, 0x704C, 0x704C, 0x7051, 0x7051, 0x7058, 0x7058, 0x7063, 0x7063, 0x706B, 0x706B, 0x706F, 0x7070, 0x7078, 0x7078, 0x707C, 0x707D, 0x7089, 0x708A, 0x708E, 0x708E, 0x7092, 0x7092, 0x7099, 0x7099, 0x70AC, 0x70AF, 0x70B3, 0x70B3, 0x70B8, 0x70BA, 0x70C8, 0x70C8, 0x70CB, 0x70CB, 0x70CF, 0x70CF, 0x70D9, 0x70D9, 0x70DD, 0x70DD, 0x70DF, 0x70DF, 0x70F1, 0x70F1, 0x70F9, 0x70F9, 0x70FD, 0x70FD, 0x7109, 0x7109, 0x7114, 0x7114, 0x7119, 0x711A, 0x711C, 0x711C, 0x7121, 0x7121, 0x7126, 0x7126, 0x7136, 0x7136, 0x713C, 0x713C, 0x7149, 0x7149, 0x714C, 0x714C, 0x714E, 0x714E, 0x7155, 0x7156, 0x7159, 0x7159, 0x7162, 0x7162, 0x7164, 0x7167, 0x7169, 0x7169, 0x716C, 0x716C, 0x716E, 0x716E, 0x717D, 0x717D, 0x7184, 0x7184, 0x7188, 0x7188, 0x718A, 0x718A, 0x718F, 0x718F, 0x7194, 0x7195, 0x7199, 0x7199, 0x719F, 0x719F, 0x71A8, 0x71A8, 0x71AC, 0x71AC, 0x71B1, 0x71B1, 0x71B9, 0x71B9, 0x71BE, 0x71BE, 0x71C3, 0x71C3, 0x71C8, 0x71C9, 0x71CE, 0x71CE, 0x71D0, 0x71D0, 0x71D2, 0x71D2, 0x71D4, 0x71D5, 0x71D7, 0x71D7, 0x71DF, 0x71E0, 0x71E5, 0x71E7, 0x71EC, 0x71EE, 0x71F5, 0x71F5, 0x71F9, 0x71F9, 0x71FB, 0x71FC, 0x71FF, 0x71FF, 0x7206, 0x7206, 0x720D, 0x720D, 0x7210, 0x7210, 0x721B, 0x721B, 0x7228, 0x7228, 0x722A, 0x722A, 0x722C, 0x722D, 0x7230, 0x7230, 0x7232, 0x7232, 0x7235, 0x7236, 0x723A, 0x7240, 0x7246, 0x7248, 0x724B, 0x724C, 0x7252, 0x7252, 0x7258, 0x7259, 0x725B, 0x725B, 0x725D, 0x725D, 0x725F, 0x725F, 0x7261, 0x7262, 0x7267, 0x7267, 0x7269, 0x7269, 0x7272, 0x7272, 0x7274, 0x7274, 0x7279, 0x7279, 0x727D, 0x727E, 0x7280, 0x7282, 0x7287, 0x7287, 0x7292, 0x7292, 0x7296, 0x7296, 0x72A0, 0x72A0, 0x72A2, 0x72A2, 0x72A7, 0x72A7, 0x72AC, 0x72AC, 0x72AF, 0x72AF, 0x72B2, 0x72B2, 0x72B6, 0x72B6, 0x72B9, 0x72B9, 0x72C2, 0x72C4, 0x72C6, 0x72C6, 0x72CE, 0x72CE, 0x72D0, 0x72D0, 0x72D2, 0x72D2, 0x72D7, 0x72D7, 0x72D9, 0x72D9, 0x72DB, 0x72DB, 0x72E0, 0x72E2, 0x72E9, 0x72E9, 0x72EC, 0x72ED, 0x72F7, 0x72F9, 0x72FC, 0x72FD, 0x730A, 0x730A, 0x7316, 0x7317, 0x731B, 0x731D, 0x731F, 0x731F, 0x7325, 0x7325, 0x7329, 0x732B, 0x732E, 0x732F, 0x7334, 0x7334, 0x7336, 0x7337, 0x733E, 0x733F, 0x7344, 0x7345, 0x734E, 0x734F, 0x7357, 0x7357, 0x7363, 0x7363, 0x7368, 0x7368, 0x736A, 0x736A, 0x7370, 0x7370, 0x7372, 0x7372, 0x7375, 0x7375, 0x7378, 0x7378, 0x737A, 0x737B, 0x7384, 0x7384, 0x7387, 0x7387, 0x7389, 0x7389, 0x738B, 0x738B, 0x7396, 0x7396, 0x73A9, 0x73A9, 0x73B2, 0x73B3, 0x73BB, 0x73BB, 0x73C0, 0x73C0, 0x73C2, 0x73C2, 0x73C8, 0x73C8, 0x73CA, 0x73CA, 0x73CD, 0x73CE, 0x73DE, 0x73DE, 0x73E0, 0x73E0, 0x73E5, 0x73E5, 0x73EA, 0x73EA, 0x73ED, 0x73EE, 0x73F1, 0x73F1, 0x73F8, 0x73F8, 0x73FE, 0x73FE, 0x7403, 0x7403, 0x7405, 0x7406, 0x7409, 0x7409, 0x7422, 0x7422, 0x7425, 0x7425, 0x7432, 0x7436, 0x743A, 0x743A, 0x743F, 0x743F, 0x7441, 0x7441, 0x7455, 0x7455, 0x7459, 0x745C, 0x745E, 0x7460, 0x7463, 0x7464, 0x7469, 0x746A, 0x746F, 0x7470, 0x7473, 0x7473, 0x7476, 0x7476, 0x747E, 0x747E, 0x7483, 0x7483, 0x748B, 0x748B, 0x749E, 0x749E, 0x74A2, 0x74A2, 0x74A7, 0x74A7, 0x74B0, 0x74B0, 0x74BD, 0x74BD, 0x74CA, 0x74CA, 0x74CF, 0x74CF, 0x74D4, 0x74D4, 0x74DC, 0x74DC, 0x74E0, 0x74E0, 0x74E2, 0x74E3, 0x74E6, 0x74E7, 0x74E9, 0x74E9, 0x74EE, 0x74EE, 0x74F0, 0x74F2, 0x74F6, 0x74F8, 0x7503, 0x7505, 0x750C, 0x750E, 0x7511, 0x7511, 0x7513, 0x7513, 0x7515, 0x7515, 0x7518, 0x7518, 0x751A, 0x751A, 0x751C, 0x751C, 0x751E, 0x751F, 0x7523, 0x7523, 0x7525, 0x7526, 0x7528, 0x7528, 0x752B, 0x752C, 0x7530, 0x7533, 0x7537, 0x7538, 0x753A, 0x753C, 0x7544, 0x7544, 0x7546, 0x7546, 0x7549, 0x754D, 0x754F, 0x754F, 0x7551, 0x7551, 0x7554, 0x7554, 0x7559, 0x755D, 0x7560, 0x7560, 0x7562, 0x7562, 0x7564, 0x7567, 0x7569, 0x756B, 0x756D, 0x756D, 0x7570, 0x7570, 0x7573, 0x7574, 0x7576, 0x7578, 0x757F, 0x757F, 0x7582, 0x7582, 0x7586, 0x7587, 0x7589, 0x758B, 0x758E, 0x758F, 0x7591, 0x7591, 0x7594, 0x7594, 0x759A, 0x759A, 0x759D, 0x759D, 0x75A3, 0x75A3, 0x75A5, 0x75A5, 0x75AB, 0x75AB, 0x75B1, 0x75B3, 0x75B5, 0x75B5, 0x75B8, 0x75B9, 0x75BC, 0x75BE, 0x75C2, 0x75C3, 0x75C5, 0x75C5, 0x75C7, 0x75C7, 0x75CA, 0x75CA, 0x75CD, 0x75CD, 0x75D2, 0x75D2, 0x75D4, 0x75D5, 0x75D8, 0x75D9, 0x75DB, 0x75DB, 0x75DE, 0x75DE, 0x75E2, 0x75E3, 0x75E9, 0x75E9, 0x75F0, 0x75F0, 0x75F2, 0x75F4, 0x75FA, 0x75FA, 0x75FC, 0x75FC, 0x75FE, 0x75FF, 0x7601, 0x7601, 0x7609, 0x7609, 0x760B, 0x760B, 0x760D, 0x760D, 0x761F, 0x7622, 0x7624, 0x7624, 0x7627, 0x7627, 0x7630, 0x7630, 0x7634, 0x7634, 0x763B, 0x763B, 0x7642, 0x7642, 0x7646, 0x7648, 0x764C, 0x764C, 0x7652, 0x7652, 0x7656, 0x7656, 0x7658, 0x7658, 0x765C, 0x765C, 0x7661, 0x7662, 0x7667, 0x766A, 0x766C, 0x766C, 0x7670, 0x7670, 0x7672, 0x7672, 0x7676, 0x7676, 0x7678, 0x7678, 0x767A, 0x767E, 0x7680, 0x7680, 0x7683, 0x7684, 0x7686, 0x7688, 0x768B, 0x768B, 0x768E, 0x768E, 0x7690, 0x7690, 0x7693, 0x7693, 0x7696, 0x7696, 0x7699, 0x769A, 0x76AE, 0x76AE, 0x76B0, 0x76B0, 0x76B4, 0x76B4, 0x76B7, 0x76BA, 0x76BF, 0x76BF, 0x76C2, 0x76C3, 0x76C6, 0x76C6, 0x76C8, 0x76C8, 0x76CA, 0x76CA, 0x76CD, 0x76CD, 0x76D2, 0x76D2, 0x76D6, 0x76D7, 0x76DB, 0x76DC, 0x76DE, 0x76DF, 0x76E1, 0x76E1, 0x76E3, 0x76E5, 0x76E7, 0x76E7, 0x76EA, 0x76EA, 0x76EE, 0x76EE, 0x76F2, 0x76F2, 0x76F4, 0x76F4, 0x76F8, 0x76F8, 0x76FB, 0x76FB, 0x76FE, 0x76FE, 0x7701, 0x7701, 0x7704, 0x7704, 0x7707, 0x7709, 0x770B, 0x770C, 0x771B, 0x771B, 0x771E, 0x7720, 0x7724, 0x7726, 0x7729, 0x7729, 0x7737, 0x7738, 0x773A, 0x773A, 0x773C, 0x773C, 0x7740, 0x7740, 0x7747, 0x7747, 0x775A, 0x775B, 0x7761, 0x7761, 0x7763, 0x7763, 0x7765, 0x7766, 0x7768, 0x7768, 0x776B, 0x776B, 0x7779, 0x7779, 0x777E, 0x777F, 0x778B, 0x778B, 0x778E, 0x778E, 0x7791, 0x7791, 0x779E, 0x779E, 0x77A0, 0x77A0, 0x77A5, 0x77A5, 0x77AC, 0x77AD, 0x77B0, 0x77B0, 0x77B3, 0x77B3, 0x77B6, 0x77B6, 0x77B9, 0x77B9, 0x77BB, 0x77BD, 0x77BF, 0x77BF, 0x77C7, 0x77C7, 0x77CD, 0x77CD, 0x77D7, 0x77D7, 0x77DA, 0x77DC, 0x77E2, 0x77E3, 0x77E5, 0x77E5, 0x77E7, 0x77E7, 0x77E9, 0x77E9, 0x77ED, 0x77EF, 0x77F3, 0x77F3, 0x77FC, 0x77FC, 0x7802, 0x7802, 0x780C, 0x780C, 0x7812, 0x7812, 0x7814, 0x7815, 0x7820, 0x7820, 0x7825, 0x7827, 0x7832, 0x7832, 0x7834, 0x7834, 0x783A, 0x783A, 0x783F, 0x783F, 0x7845, 0x7845, 0x785D, 0x785D, 0x786B, 0x786C, 0x786F, 0x786F, 0x7872, 0x7872, 0x7874, 0x7874, 0x787C, 0x787C, 0x7881, 0x7881, 0x7886, 0x7887, 0x788C, 0x788E, 0x7891, 0x7891, 0x7893, 0x7893, 0x7895, 0x7895, 0x7897, 0x7897, 0x789A, 0x789A, 0x78A3, 0x78A3, 0x78A7, 0x78A7, 0x78A9, 0x78AA, 0x78AF, 0x78AF, 0x78B5, 0x78B5, 0x78BA, 0x78BA, 0x78BC, 0x78BC, 0x78BE, 0x78BE, 0x78C1, 0x78C1, 0x78C5, 0x78C6, 0x78CA, 0x78CB, 0x78D0, 0x78D1, 0x78D4, 0x78D4, 0x78DA, 0x78DA, 0x78E7, 0x78E8, 0x78EC, 0x78EC, 0x78EF, 0x78EF, 0x78F4, 0x78F4, 0x78FD, 0x78FD, 0x7901, 0x7901, 0x7907, 0x7907, 0x790E, 0x790E, 0x7911, 0x7912, 0x7919, 0x7919, 0x7926, 0x7926, 0x792A, 0x792C, 0x793A, 0x793A, 0x793C, 0x793C, 0x793E, 0x793E, 0x7940, 0x7941, 0x7947, 0x7949, 0x7950, 0x7950, 0x7953, 0x7953, 0x7955, 0x7957, 0x795A, 0x795A, 0x795D, 0x7960, 0x7962, 0x7962, 0x7965, 0x7965, 0x7968, 0x7968, 0x796D, 0x796D, 0x7977, 0x7977, 0x797A, 0x797A, 0x797F, 0x7981, 0x7984, 0x7985, 0x798A, 0x798A, 0x798D, 0x798F, 0x799D, 0x799D, 0x79A6, 0x79A7, 0x79AA, 0x79AA, 0x79AE, 0x79AE, 0x79B0, 0x79B0, 0x79B3, 0x79B3, 0x79B9, 0x79BA, 0x79BD, 0x79C1, 0x79C9, 0x79C9, 0x79CB, 0x79CB, 0x79D1, 0x79D2, 0x79D5, 0x79D5, 0x79D8, 0x79D8, 0x79DF, 0x79DF, 0x79E1, 0x79E1, 0x79E3, 0x79E4, 0x79E6, 0x79E7, 0x79E9, 0x79E9, 0x79EC, 0x79EC, 0x79F0, 0x79F0, 0x79FB, 0x79FB, 0x7A00, 0x7A00, 0x7A08, 0x7A08, 0x7A0B, 0x7A0B, 0x7A0D, 0x7A0E, 0x7A14, 0x7A14, 0x7A17, 0x7A1A, 0x7A1C, 0x7A1C, 0x7A1F, 0x7A20, 0x7A2E, 0x7A2E, 0x7A31, 0x7A32, 0x7A37, 0x7A37, 0x7A3B, 0x7A40, 0x7A42, 0x7A43, 0x7A46, 0x7A46, 0x7A49, 0x7A49, 0x7A4D, 0x7A50, 0x7A57, 0x7A57, 0x7A61, 0x7A63, 0x7A69, 0x7A69, 0x7A6B, 0x7A6B, 0x7A70, 0x7A70, 0x7A74, 0x7A74, 0x7A76, 0x7A76, 0x7A79, 0x7A7A, 0x7A7D, 0x7A7D, 0x7A7F, 0x7A7F, 0x7A81, 0x7A81, 0x7A83, 0x7A84, 0x7A88, 0x7A88, 0x7A92, 0x7A93, 0x7A95, 0x7A98, 0x7A9F, 0x7A9F, 0x7AA9, 0x7AAA, 0x7AAE, 0x7AB0, 0x7AB6, 0x7AB6, 0x7ABA, 0x7ABA, 0x7ABF, 0x7ABF, 0x7AC3, 0x7AC5, 0x7AC7, 0x7AC8, 0x7ACA, 0x7ACB, 0x7ACD, 0x7ACD, 0x7ACF, 0x7ACF, 0x7AD2, 0x7AD3, 0x7AD5, 0x7AD5, 0x7AD9, 0x7ADA, 0x7ADC, 0x7ADD, 0x7ADF, 0x7AE3, 0x7AE5, 0x7AE6, 0x7AEA, 0x7AEA, 0x7AED, 0x7AED, 0x7AEF, 0x7AF0, 0x7AF6, 0x7AF6, 0x7AF8, 0x7AFA, 0x7AFF, 0x7AFF, 0x7B02, 0x7B02, 0x7B04, 0x7B04, 0x7B06, 0x7B06, 0x7B08, 0x7B08, 0x7B0A, 0x7B0B, 0x7B0F, 0x7B0F, 0x7B11, 0x7B11, 0x7B18, 0x7B19, 0x7B1B, 0x7B1B, 0x7B1E, 0x7B1E, 0x7B20, 0x7B20, 0x7B25, 0x7B26, 0x7B28, 0x7B28, 0x7B2C, 0x7B2C, 0x7B33, 0x7B33, 0x7B35, 0x7B36, 0x7B39, 0x7B39, 0x7B45, 0x7B46, 0x7B48, 0x7B49, 0x7B4B, 0x7B4D, 0x7B4F, 0x7B52, 0x7B54, 0x7B54, 0x7B56, 0x7B56, 0x7B5D, 0x7B5D, 0x7B65, 0x7B65, 0x7B67, 0x7B67, 0x7B6C, 0x7B6C, 0x7B6E, 0x7B6E, 0x7B70, 0x7B71, 0x7B74, 0x7B75, 0x7B7A, 0x7B7A, 0x7B86, 0x7B87, 0x7B8B, 0x7B8B, 0x7B8D, 0x7B8D, 0x7B8F, 0x7B8F, 0x7B92, 0x7B92, 0x7B94, 0x7B95, 0x7B97, 0x7B9A, 0x7B9C, 0x7B9D, 0x7B9F, 0x7B9F, 0x7BA1, 0x7BA1, 0x7BAA, 0x7BAA, 0x7BAD, 0x7BAD, 0x7BB1, 0x7BB1, 0x7BB4, 0x7BB4, 0x7BB8, 0x7BB8, 0x7BC0, 0x7BC1, 0x7BC4, 0x7BC4, 0x7BC6, 0x7BC7, 0x7BC9, 0x7BC9, 0x7BCB, 0x7BCC, 0x7BCF, 0x7BCF, 0x7BDD, 0x7BDD, 0x7BE0, 0x7BE0, 0x7BE4, 0x7BE6, 0x7BE9, 0x7BE9, 0x7BED, 0x7BED, 0x7BF3, 0x7BF3, 0x7BF6, 0x7BF7, 0x7C00, 0x7C00, 0x7C07, 0x7C07, 0x7C0D, 0x7C0D, 0x7C11, 0x7C14, 0x7C17, 0x7C17, 0x7C1F, 0x7C1F, 0x7C21, 0x7C21, 0x7C23, 0x7C23, 0x7C27, 0x7C27, 0x7C2A, 0x7C2B, 0x7C37, 0x7C38, 0x7C3D, 0x7C40, 0x7C43, 0x7C43, 0x7C4C, 0x7C4D, 0x7C4F, 0x7C50, 0x7C54, 0x7C54, 0x7C56, 0x7C56, 0x7C58, 0x7C58, 0x7C5F, 0x7C60, 0x7C64, 0x7C65, 0x7C6C, 0x7C6C, 0x7C73, 0x7C73, 0x7C75, 0x7C75, 0x7C7E, 0x7C7E, 0x7C81, 0x7C83, 0x7C89, 0x7C89, 0x7C8B, 0x7C8B, 0x7C8D, 0x7C8D, 0x7C90, 0x7C90, 0x7C92, 0x7C92, 0x7C95, 0x7C95, 0x7C97, 0x7C98, 0x7C9B, 0x7C9B, 0x7C9F, 0x7C9F, 0x7CA1, 0x7CA2, 0x7CA4, 0x7CA5, 0x7CA7, 0x7CA8, 0x7CAB, 0x7CAB, 0x7CAD, 0x7CAE, 0x7CB1, 0x7CB3, 0x7CB9, 0x7CB9, 0x7CBD, 0x7CBE, 0x7CC0, 0x7CC0, 0x7CC2, 0x7CC2, 0x7CC5, 0x7CC5, 0x7CCA, 0x7CCA, 0x7CCE, 0x7CCE, 0x7CD2, 0x7CD2, 0x7CD6, 0x7CD6, 0x7CD8, 0x7CD8, 0x7CDC, 0x7CDC, 0x7CDE, 0x7CE0, 0x7CE2, 0x7CE2, 0x7CE7, 0x7CE7, 0x7CEF, 0x7CEF, 0x7CF2, 0x7CF2, 0x7CF4, 0x7CF4, 0x7CF6, 0x7CF6, 0x7CF8, 0x7CF8, 0x7CFA, 0x7CFB, 0x7CFE, 0x7CFE, 0x7D00, 0x7D00, 0x7D02, 0x7D02, 0x7D04, 0x7D06, 0x7D0A, 0x7D0B, 0x7D0D, 0x7D0D, 0x7D10, 0x7D10, 0x7D14, 0x7D15, 0x7D17, 0x7D1C, 0x7D20, 0x7D22, 0x7D2B, 0x7D2C, 0x7D2E, 0x7D30, 0x7D32, 0x7D33, 0x7D35, 0x7D35, 0x7D39, 0x7D3A, 0x7D3F, 0x7D3F, 0x7D42, 0x7D46, 0x7D4B, 0x7D4C, 0x7D4E, 0x7D50, 0x7D56, 0x7D56, 0x7D5B, 0x7D5B, 0x7D5E, 0x7D5E, 0x7D61, 0x7D63, 0x7D66, 0x7D66, 0x7D68, 0x7D68, 0x7D6E, 0x7D6E, 0x7D71, 0x7D73, 0x7D75, 0x7D76, 0x7D79, 0x7D79, 0x7D7D, 0x7D7D, 0x7D89, 0x7D89, 0x7D8F, 0x7D8F, 0x7D93, 0x7D93, 0x7D99, 0x7D9C, 0x7D9F, 0x7D9F, 0x7DA2, 0x7DA3, 0x7DAB, 0x7DB2, 0x7DB4, 0x7DB5, 0x7DB8, 0x7DB8, 0x7DBA, 0x7DBB, 0x7DBD, 0x7DBF, 0x7DC7, 0x7DC7, 0x7DCA, 0x7DCB, 0x7DCF, 0x7DCF, 0x7DD1, 0x7DD2, 0x7DD5, 0x7DD5, 0x7DD8, 0x7DD8, 0x7DDA, 0x7DDA, 0x7DDC, 0x7DDE, 0x7DE0, 0x7DE1, 0x7DE4, 0x7DE4, 0x7DE8, 0x7DE9, 0x7DEC, 0x7DEC, 0x7DEF, 0x7DEF, 0x7DF2, 0x7DF2, 0x7DF4, 0x7DF4, 0x7DFB, 0x7DFB, 0x7E01, 0x7E01, 0x7E04, 0x7E05, 0x7E09, 0x7E0B, 0x7E12, 0x7E12, 0x7E1B, 0x7E1B, 0x7E1E, 0x7E1F, 0x7E21, 0x7E23, 0x7E26, 0x7E26, 0x7E2B, 0x7E2B, 0x7E2E, 0x7E2E, 0x7E31, 0x7E32, 0x7E35, 0x7E35, 0x7E37, 0x7E37, 0x7E39, 0x7E3B, 0x7E3D, 0x7E3E, 0x7E41, 0x7E41, 0x7E43, 0x7E43, 0x7E46, 0x7E46, 0x7E4A, 0x7E4B, 0x7E4D, 0x7E4D, 0x7E54, 0x7E56, 0x7E59, 0x7E5A, 0x7E5D, 0x7E5E, 0x7E66, 0x7E67, 0x7E69, 0x7E6A, 0x7E6D, 0x7E6D, 0x7E70, 0x7E70, 0x7E79, 0x7E79, 0x7E7B, 0x7E7D, 0x7E7F, 0x7E7F, 0x7E82, 0x7E83, 0x7E88, 0x7E89, 0x7E8C, 0x7E8C, 0x7E8E, 0x7E90, 0x7E92, 0x7E94, 0x7E96, 0x7E96, 0x7E9B, 0x7E9C, 0x7F36, 0x7F36, 0x7F38, 0x7F38, 0x7F3A, 0x7F3A, 0x7F45, 0x7F45, 0x7F4C, 0x7F4E, 0x7F50, 0x7F51, 0x7F54, 0x7F55, 0x7F58, 0x7F58, 0x7F5F, 0x7F60, 0x7F67, 0x7F6B, 0x7F6E, 0x7F6E, 0x7F70, 0x7F70, 0x7F72, 0x7F72, 0x7F75, 0x7F75, 0x7F77, 0x7F79, 0x7F82, 0x7F83, 0x7F85, 0x7F88, 0x7F8A, 0x7F8A, 0x7F8C, 0x7F8C, 0x7F8E, 0x7F8E, 0x7F94, 0x7F94, 0x7F9A, 0x7F9A, 0x7F9D, 0x7F9E, 0x7FA3, 0x7FA4, 0x7FA8, 0x7FA9, 0x7FAE, 0x7FAF, 0x7FB2, 0x7FB2, 0x7FB6, 0x7FB6, 0x7FB8, 0x7FB9, 0x7FBD, 0x7FBD, 0x7FC1, 0x7FC1, 0x7FC5, 0x7FC6, 0x7FCA, 0x7FCA, 0x7FCC, 0x7FCC, 0x7FD2, 0x7FD2, 0x7FD4, 0x7FD5, 0x7FE0, 0x7FE1, 0x7FE6, 0x7FE6, 0x7FE9, 0x7FE9, 0x7FEB, 0x7FEB, 0x7FF0, 0x7FF0, 0x7FF3, 0x7FF3, 0x7FF9, 0x7FF9, 0x7FFB, 0x7FFC, 0x8000, 0x8001, 0x8003, 0x8006, 0x800B, 0x800C, 0x8010, 0x8010, 0x8012, 0x8012, 0x8015, 0x8015, 0x8017, 0x8019, 0x801C, 0x801C, 0x8021, 0x8021, 0x8028, 0x8028, 0x8033, 0x8033, 0x8036, 0x8036, 0x803B, 0x803B, 0x803D, 0x803D, 0x803F, 0x803F, 0x8046, 0x8046, 0x804A, 0x804A, 0x8052, 0x8052, 0x8056, 0x8056, 0x8058, 0x8058, 0x805A, 0x805A, 0x805E, 0x805F, 0x8061, 0x8062, 0x8068, 0x8068, 0x806F, 0x8070, 0x8072, 0x8074, 0x8076, 0x8077, 0x8079, 0x8079, 0x807D, 0x807F, 0x8084, 0x8087, 0x8089, 0x8089, 0x808B, 0x808C, 0x8093, 0x8093, 0x8096, 0x8096, 0x8098, 0x8098, 0x809A, 0x809B, 0x809D, 0x809D, 0x80A1, 0x80A2, 0x80A5, 0x80A5, 0x80A9, 0x80AA, 0x80AC, 0x80AD, 0x80AF, 0x80AF, 0x80B1, 0x80B2, 0x80B4, 0x80B4, 0x80BA, 0x80BA, 0x80C3, 0x80C4, 0x80C6, 0x80C6, 0x80CC, 0x80CC, 0x80CE, 0x80CE, 0x80D6, 0x80D6, 0x80D9, 0x80DB, 0x80DD, 0x80DE, 0x80E1, 0x80E1, 0x80E4, 0x80E5, 0x80EF, 0x80EF, 0x80F1, 0x80F1, 0x80F4, 0x80F4, 0x80F8, 0x80F8, 0x80FC, 0x80FD, 0x8102, 0x8102, 0x8105, 0x810A, 0x811A, 0x811B, 0x8123, 0x8123, 0x8129, 0x8129, 0x812F, 0x812F, 0x8131, 0x8131, 0x8133, 0x8133, 0x8139, 0x8139, 0x813E, 0x813E, 0x8146, 0x8146, 0x814B, 0x814B, 0x814E, 0x814E, 0x8150, 0x8151, 0x8153, 0x8155, 0x815F, 0x815F, 0x8165, 0x8166, 0x816B, 0x816B, 0x816E, 0x816E, 0x8170, 0x8171, 0x8174, 0x8174, 0x8178, 0x817A, 0x817F, 0x8180, 0x8182, 0x8183, 0x8188, 0x8188, 0x818A, 0x818A, 0x818F, 0x818F, 0x8193, 0x8193, 0x8195, 0x8195, 0x819A, 0x819A, 0x819C, 0x819D, 0x81A0, 0x81A0, 0x81A3, 0x81A4, 0x81A8, 0x81A9, 0x81B0, 0x81B0, 0x81B3, 0x81B3, 0x81B5, 0x81B5, 0x81B8, 0x81B8, 0x81BA, 0x81BA, 0x81BD, 0x81C0, 0x81C2, 0x81C2, 0x81C6, 0x81C6, 0x81C8, 0x81C9, 0x81CD, 0x81CD, 0x81D1, 0x81D1, 0x81D3, 0x81D3, 0x81D8, 0x81DA, 0x81DF, 0x81E0, 0x81E3, 0x81E3, 0x81E5, 0x81E5, 0x81E7, 0x81E8, 0x81EA, 0x81EA, 0x81ED, 0x81ED, 0x81F3, 0x81F4, 0x81FA, 0x81FC, 0x81FE, 0x81FE, 0x8201, 0x8202, 0x8205, 0x8205, 0x8207, 0x820A, 0x820C, 0x820E, 0x8210, 0x8210, 0x8212, 0x8212, 0x8216, 0x8218, 0x821B, 0x821C, 0x821E, 0x821F, 0x8229, 0x822C, 0x822E, 0x822E, 0x8233, 0x8233, 0x8235, 0x8239, 0x8240, 0x8240, 0x8247, 0x8247, 0x8258, 0x825A, 0x825D, 0x825D, 0x825F, 0x825F, 0x8262, 0x8262, 0x8264, 0x8264, 0x8266, 0x8266, 0x8268, 0x8268, 0x826A, 0x826B, 0x826E, 0x826F, 0x8271, 0x8272, 0x8276, 0x8278, 0x827E, 0x827E, 0x828B, 0x828B, 0x828D, 0x828D, 0x8292, 0x8292, 0x8299, 0x8299, 0x829D, 0x829D, 0x829F, 0x829F, 0x82A5, 0x82A6, 0x82AB, 0x82AD, 0x82AF, 0x82AF, 0x82B1, 0x82B1, 0x82B3, 0x82B3, 0x82B8, 0x82B9, 0x82BB, 0x82BB, 0x82BD, 0x82BD, 0x82C5, 0x82C5, 0x82D1, 0x82D4, 0x82D7, 0x82D7, 0x82D9, 0x82D9, 0x82DB, 0x82DC, 0x82DE, 0x82DF, 0x82E1, 0x82E1, 0x82E3, 0x82E3, 0x82E5, 0x82E7, 0x82EB, 0x82EB, 0x82F1, 0x82F1, 0x82F3, 0x82F4, 0x82F9, 0x82FB, 0x8302, 0x8306, 0x8309, 0x8309, 0x830E, 0x830E, 0x8316, 0x8318, 0x831C, 0x831C, 0x8323, 0x8323, 0x8328, 0x8328, 0x832B, 0x832B, 0x832F, 0x832F, 0x8331, 0x8332, 0x8334, 0x8336, 0x8338, 0x8339, 0x8340, 0x8340, 0x8345, 0x8345, 0x8349, 0x834A, 0x834F, 0x8350, 0x8352, 0x8352, 0x8358, 0x8358, 0x8373, 0x8373, 0x8375, 0x8375, 0x8377, 0x8377, 0x837B, 0x837C, 0x8385, 0x8385, 0x8387, 0x8387, 0x8389, 0x838A, 0x838E, 0x838E, 0x8393, 0x8393, 0x8396, 0x8396, 0x839A, 0x839A, 0x839E, 0x83A0, 0x83A2, 0x83A2, 0x83A8, 0x83A8, 0x83AA, 0x83AB, 0x83B1, 0x83B1, 0x83B5, 0x83B5, 0x83BD, 0x83BD, 0x83C1, 0x83C1, 0x83C5, 0x83C5, 0x83CA, 0x83CA, 0x83CC, 0x83CC, 0x83CE, 0x83CE, 0x83D3, 0x83D3, 0x83D6, 0x83D6, 0x83D8, 0x83D8, 0x83DC, 0x83DC, 0x83DF, 0x83E0, 0x83E9, 0x83E9, 0x83EB, 0x83EB, 0x83EF, 0x83F2, 0x83F4, 0x83F4, 0x83F7, 0x83F7, 0x83FB, 0x83FB, 0x83FD, 0x83FD, 0x8403, 0x8404, 0x8407, 0x8407, 0x840B, 0x840E, 0x8413, 0x8413, 0x8420, 0x8420, 0x8422, 0x8422, 0x8429, 0x842A, 0x842C, 0x842C, 0x8431, 0x8431, 0x8435, 0x8435, 0x8438, 0x8438, 0x843C, 0x843D, 0x8446, 0x8446, 0x8449, 0x8449, 0x844E, 0x844E, 0x8457, 0x8457, 0x845B, 0x845B, 0x8461, 0x8463, 0x8466, 0x8466, 0x8469, 0x8469, 0x846B, 0x846F, 0x8471, 0x8471, 0x8475, 0x8475, 0x8477, 0x8477, 0x8479, 0x847A, 0x8482, 0x8482, 0x8484, 0x8484, 0x848B, 0x848B, 0x8490, 0x8490, 0x8494, 0x8494, 0x8499, 0x8499, 0x849C, 0x849C, 0x849F, 0x849F, 0x84A1, 0x84A1, 0x84AD, 0x84AD, 0x84B2, 0x84B2, 0x84B8, 0x84B9, 0x84BB, 0x84BC, 0x84BF, 0x84BF, 0x84C1, 0x84C1, 0x84C4, 0x84C4, 0x84C6, 0x84C6, 0x84C9, 0x84CB, 0x84CD, 0x84CD, 0x84D0, 0x84D1, 0x84D6, 0x84D6, 0x84D9, 0x84DA, 0x84EC, 0x84EC, 0x84EE, 0x84EE, 0x84F4, 0x84F4, 0x84FC, 0x84FC, 0x84FF, 0x8500, 0x8506, 0x8506, 0x8511, 0x8511, 0x8513, 0x8515, 0x8517, 0x8518, 0x851A, 0x851A, 0x851F, 0x851F, 0x8521, 0x8521, 0x8526, 0x8526, 0x852C, 0x852D, 0x8535, 0x8535, 0x853D, 0x853D, 0x8540, 0x8541, 0x8543, 0x8543, 0x8548, 0x854B, 0x854E, 0x854E, 0x8555, 0x8555, 0x8557, 0x8558, 0x855A, 0x855A, 0x8563, 0x8563, 0x8568, 0x856A, 0x856D, 0x856D, 0x8577, 0x8577, 0x857E, 0x857E, 0x8580, 0x8580, 0x8584, 0x8584, 0x8587, 0x8588, 0x858A, 0x858A, 0x8590, 0x8591, 0x8594, 0x8594, 0x8597, 0x8597, 0x8599, 0x8599, 0x859B, 0x859C, 0x85A4, 0x85A4, 0x85A6, 0x85A6, 0x85A8, 0x85AC, 0x85AE, 0x85AF, 0x85B9, 0x85BA, 0x85C1, 0x85C1, 0x85C9, 0x85C9, 0x85CD, 0x85CD, 0x85CF, 0x85D0, 0x85D5, 0x85D5, 0x85DC, 0x85DD, 0x85E4, 0x85E5, 0x85E9, 0x85EA, 0x85F7, 0x85F7, 0x85F9, 0x85FB, 0x85FE, 0x85FE, 0x8602, 0x8602, 0x8606, 0x8607, 0x860A, 0x860B, 0x8613, 0x8613, 0x8616, 0x8617, 0x861A, 0x861A, 0x8622, 0x8622, 0x862D, 0x862D, 0x862F, 0x8630, 0x863F, 0x863F, 0x864D, 0x864E, 0x8650, 0x8650, 0x8654, 0x8655, 0x865A, 0x865A, 0x865C, 0x865C, 0x865E, 0x865F, 0x8667, 0x8667, 0x866B, 0x866B, 0x8671, 0x8671, 0x8679, 0x8679, 0x867B, 0x867B, 0x868A, 0x868C, 0x8693, 0x8693, 0x8695, 0x8695, 0x86A3, 0x86A4, 0x86A9, 0x86AB, 0x86AF, 0x86B0, 0x86B6, 0x86B6, 0x86C4, 0x86C4, 0x86C6, 0x86C7, 0x86C9, 0x86C9, 0x86CB, 0x86CB, 0x86CD, 0x86CE, 0x86D4, 0x86D4, 0x86D9, 0x86D9, 0x86DB, 0x86DB, 0x86DE, 0x86DF, 0x86E4, 0x86E4, 0x86E9, 0x86E9, 0x86EC, 0x86EF, 0x86F8, 0x86F9, 0x86FB, 0x86FB, 0x86FE, 0x86FE, 0x8700, 0x8700, 0x8702, 0x8703, 0x8706, 0x8706, 0x8708, 0x870A, 0x870D, 0x870D, 0x8711, 0x8712, 0x8718, 0x8718, 0x871A, 0x871A, 0x871C, 0x871C, 0x8725, 0x8725, 0x8729, 0x8729, 0x8734, 0x8734, 0x8737, 0x8737, 0x873B, 0x873B, 0x873F, 0x873F, 0x8749, 0x8749, 0x874B, 0x874C, 0x874E, 0x874E, 0x8753, 0x8753, 0x8755, 0x8755, 0x8757, 0x8757, 0x8759, 0x8759, 0x875F, 0x8760, 0x8763, 0x8763, 0x8766, 0x8766, 0x8768, 0x8768, 0x876A, 0x876A, 0x876E, 0x876E, 0x8774, 0x8774, 0x8776, 0x8776, 0x8778, 0x8778, 0x877F, 0x877F, 0x8782, 0x8782, 0x878D, 0x878D, 0x879F, 0x879F, 0x87A2, 0x87A2, 0x87AB, 0x87AB, 0x87AF, 0x87AF, 0x87B3, 0x87B3, 0x87BA, 0x87BB, 0x87BD, 0x87BD, 0x87C0, 0x87C0, 0x87C4, 0x87C4, 0x87C6, 0x87C7, 0x87CB, 0x87CB, 0x87D0, 0x87D0, 0x87D2, 0x87D2, 0x87E0, 0x87E0, 0x87EF, 0x87EF, 0x87F2, 0x87F2, 0x87F6, 0x87F7, 0x87F9, 0x87F9, 0x87FB, 0x87FB, 0x87FE, 0x87FE, 0x8805, 0x8805, 0x880D, 0x880F, 0x8811, 0x8811, 0x8815, 0x8816, 0x8821, 0x8823, 0x8827, 0x8827, 0x8831, 0x8831, 0x8836, 0x8836, 0x8839, 0x8839, 0x883B, 0x883B, 0x8840, 0x8840, 0x8842, 0x8842, 0x8844, 0x8844, 0x8846, 0x8846, 0x884C, 0x884D, 0x8852, 0x8853, 0x8857, 0x8857, 0x8859, 0x8859, 0x885B, 0x885B, 0x885D, 0x885E, 0x8861, 0x8863, 0x8868, 0x8868, 0x886B, 0x886B, 0x8870, 0x8870, 0x8872, 0x8872, 0x8875, 0x8875, 0x8877, 0x8877, 0x887D, 0x887F, 0x8881, 0x8882, 0x8888, 0x8888, 0x888B, 0x888B, 0x888D, 0x888D, 0x8892, 0x8892, 0x8896, 0x8897, 0x8899, 0x8899, 0x889E, 0x889E, 0x88A2, 0x88A2, 0x88A4, 0x88A4, 0x88AB, 0x88AB, 0x88AE, 0x88AE, 0x88B0, 0x88B1, 0x88B4, 0x88B5, 0x88B7, 0x88B7, 0x88BF, 0x88BF, 0x88C1, 0x88C5, 0x88CF, 0x88CF, 0x88D4, 0x88D5, 0x88D8, 0x88D9, 0x88DC, 0x88DD, 0x88DF, 0x88DF, 0x88E1, 0x88E1, 0x88E8, 0x88E8, 0x88F2, 0x88F4, 0x88F8, 0x88F9, 0x88FC, 0x88FE, 0x8902, 0x8902, 0x8904, 0x8904, 0x8907, 0x8907, 0x890A, 0x890A, 0x890C, 0x890C, 0x8910, 0x8910, 0x8912, 0x8913, 0x891D, 0x891E, 0x8925, 0x8925, 0x892A, 0x892B, 0x8936, 0x8936, 0x8938, 0x8938, 0x893B, 0x893B, 0x8941, 0x8941, 0x8943, 0x8944, 0x894C, 0x894D, 0x8956, 0x8956, 0x895E, 0x8960, 0x8964, 0x8964, 0x8966, 0x8966, 0x896A, 0x896A, 0x896D, 0x896D, 0x896F, 0x896F, 0x8972, 0x8972, 0x8974, 0x8974, 0x8977, 0x8977, 0x897E, 0x897F, 0x8981, 0x8981, 0x8983, 0x8983, 0x8986, 0x8988, 0x898A, 0x898B, 0x898F, 0x898F, 0x8993, 0x8993, 0x8996, 0x8998, 0x899A, 0x899A, 0x89A1, 0x89A1, 0x89A6, 0x89A7, 0x89A9, 0x89AA, 0x89AC, 0x89AC, 0x89AF, 0x89AF, 0x89B2, 0x89B3, 0x89BA, 0x89BA, 0x89BD, 0x89BD, 0x89BF, 0x89C0, 0x89D2, 0x89D2, 0x89DA, 0x89DA, 0x89DC, 0x89DD, 0x89E3, 0x89E3, 0x89E6, 0x89E7, 0x89F4, 0x89F4, 0x89F8, 0x89F8, 0x8A00, 0x8A00, 0x8A02, 0x8A03, 0x8A08, 0x8A08, 0x8A0A, 0x8A0A, 0x8A0C, 0x8A0C, 0x8A0E, 0x8A0E, 0x8A10, 0x8A10, 0x8A13, 0x8A13, 0x8A16, 0x8A18, 0x8A1B, 0x8A1B, 0x8A1D, 0x8A1D, 0x8A1F, 0x8A1F, 0x8A23, 0x8A23, 0x8A25, 0x8A25, 0x8A2A, 0x8A2A, 0x8A2D, 0x8A2D, 0x8A31, 0x8A31, 0x8A33, 0x8A34, 0x8A36, 0x8A36, 0x8A3A, 0x8A3C, 0x8A41, 0x8A41, 0x8A46, 0x8A46, 0x8A48, 0x8A48, 0x8A50, 0x8A52, 0x8A54, 0x8A55, 0x8A5B, 0x8A5B, 0x8A5E, 0x8A5E, 0x8A60, 0x8A60, 0x8A62, 0x8A63, 0x8A66, 0x8A66, 0x8A69, 0x8A69, 0x8A6B, 0x8A6E, 0x8A70, 0x8A73, 0x8A7C, 0x8A7C, 0x8A82, 0x8A82, 0x8A84, 0x8A85, 0x8A87, 0x8A87, 0x8A89, 0x8A89, 0x8A8C, 0x8A8D, 0x8A91, 0x8A91, 0x8A93, 0x8A93, 0x8A95, 0x8A95, 0x8A98, 0x8A98, 0x8A9A, 0x8A9A, 0x8A9E, 0x8A9E, 0x8AA0, 0x8AA1, 0x8AA3, 0x8AA6, 0x8AA8, 0x8AA8, 0x8AAC, 0x8AAD, 0x8AB0, 0x8AB0, 0x8AB2, 0x8AB2, 0x8AB9, 0x8AB9, 0x8ABC, 0x8ABC, 0x8ABF, 0x8ABF, 0x8AC2, 0x8AC2, 0x8AC4, 0x8AC4, 0x8AC7, 0x8AC7, 0x8ACB, 0x8ACD, 0x8ACF, 0x8ACF, 0x8AD2, 0x8AD2, 0x8AD6, 0x8AD6, 0x8ADA, 0x8ADC, 0x8ADE, 0x8ADE, 0x8AE0, 0x8AE2, 0x8AE4, 0x8AE4, 0x8AE6, 0x8AE7, 0x8AEB, 0x8AEB, 0x8AED, 0x8AEE, 0x8AF1, 0x8AF1, 0x8AF3, 0x8AF3, 0x8AF7, 0x8AF8, 0x8AFA, 0x8AFA, 0x8AFE, 0x8AFE, 0x8B00, 0x8B02, 0x8B04, 0x8B04, 0x8B07, 0x8B07, 0x8B0C, 0x8B0C, 0x8B0E, 0x8B0E, 0x8B10, 0x8B10, 0x8B14, 0x8B14, 0x8B16, 0x8B17, 0x8B19, 0x8B1B, 0x8B1D, 0x8B1D, 0x8B20, 0x8B21, 0x8B26, 0x8B26, 0x8B28, 0x8B28, 0x8B2B, 0x8B2C, 0x8B33, 0x8B33, 0x8B39, 0x8B39, 0x8B3E, 0x8B3E, 0x8B41, 0x8B41, 0x8B49, 0x8B49, 0x8B4C, 0x8B4C, 0x8B4E, 0x8B4F, 0x8B56, 0x8B56, 0x8B58, 0x8B58, 0x8B5A, 0x8B5C, 0x8B5F, 0x8B5F, 0x8B66, 0x8B66, 0x8B6B, 0x8B6C, 0x8B6F, 0x8B72, 0x8B74, 0x8B74, 0x8B77, 0x8B77, 0x8B7D, 0x8B7D, 0x8B80, 0x8B80, 0x8B83, 0x8B83, 0x8B8A, 0x8B8A, 0x8B8C, 0x8B8C, 0x8B8E, 0x8B8E, 0x8B90, 0x8B90, 0x8B92, 0x8B93, 0x8B96, 0x8B96, 0x8B99, 0x8B9A, 0x8C37, 0x8C37, 0x8C3A, 0x8C3A, 0x8C3F, 0x8C3F, 0x8C41, 0x8C41, 0x8C46, 0x8C46, 0x8C48, 0x8C48, 0x8C4A, 0x8C4A, 0x8C4C, 0x8C4C, 0x8C4E, 0x8C4E, 0x8C50, 0x8C50, 0x8C55, 0x8C55, 0x8C5A, 0x8C5A, 0x8C61, 0x8C62, 0x8C6A, 0x8C6C, 0x8C78, 0x8C7A, 0x8C7C, 0x8C7C, 0x8C82, 0x8C82, 0x8C85, 0x8C85, 0x8C89, 0x8C8A, 0x8C8C, 0x8C8E, 0x8C94, 0x8C94, 0x8C98, 0x8C98, 0x8C9D, 0x8C9E, 0x8CA0, 0x8CA2, 0x8CA7, 0x8CB0, 0x8CB2, 0x8CB4, 0x8CB6, 0x8CB8, 0x8CBB, 0x8CBD, 0x8CBF, 0x8CC4, 0x8CC7, 0x8CC8, 0x8CCA, 0x8CCA, 0x8CCD, 0x8CCE, 0x8CD1, 0x8CD1, 0x8CD3, 0x8CD3, 0x8CDA, 0x8CDC, 0x8CDE, 0x8CDE, 0x8CE0, 0x8CE0, 0x8CE2, 0x8CE4, 0x8CE6, 0x8CE6, 0x8CEA, 0x8CEA, 0x8CED, 0x8CED, 0x8CFA, 0x8CFD, 0x8D04, 0x8D05, 0x8D07, 0x8D08, 0x8D0A, 0x8D0B, 0x8D0D, 0x8D0D, 0x8D0F, 0x8D10, 0x8D13, 0x8D14, 0x8D16, 0x8D16, 0x8D64, 0x8D64, 0x8D66, 0x8D67, 0x8D6B, 0x8D6B, 0x8D6D, 0x8D6D, 0x8D70, 0x8D71, 0x8D73, 0x8D74, 0x8D77, 0x8D77, 0x8D81, 0x8D81, 0x8D85, 0x8D85, 0x8D8A, 0x8D8A, 0x8D99, 0x8D99, 0x8DA3, 0x8DA3, 0x8DA8, 0x8DA8, 0x8DB3, 0x8DB3, 0x8DBA, 0x8DBA, 0x8DBE, 0x8DBE, 0x8DC2, 0x8DC2, 0x8DCB, 0x8DCC, 0x8DCF, 0x8DCF, 0x8DD6, 0x8DD6, 0x8DDA, 0x8DDB, 0x8DDD, 0x8DDD, 0x8DDF, 0x8DDF, 0x8DE1, 0x8DE1, 0x8DE3, 0x8DE3, 0x8DE8, 0x8DE8, 0x8DEA, 0x8DEB, 0x8DEF, 0x8DEF, 0x8DF3, 0x8DF3, 0x8DF5, 0x8DF5, 0x8DFC, 0x8DFC, 0x8DFF, 0x8DFF, 0x8E08, 0x8E0A, 0x8E0F, 0x8E10, 0x8E1D, 0x8E1F, 0x8E2A, 0x8E2A, 0x8E30, 0x8E30, 0x8E34, 0x8E35, 0x8E42, 0x8E42, 0x8E44, 0x8E44, 0x8E47, 0x8E4A, 0x8E4C, 0x8E4C, 0x8E50, 0x8E50, 0x8E55, 0x8E55, 0x8E59, 0x8E59, 0x8E5F, 0x8E60, 0x8E63, 0x8E64, 0x8E72, 0x8E72, 0x8E74, 0x8E74, 0x8E76, 0x8E76, 0x8E7C, 0x8E7C, 0x8E81, 0x8E81, 0x8E84, 0x8E85, 0x8E87, 0x8E87, 0x8E8A, 0x8E8B, 0x8E8D, 0x8E8D, 0x8E91, 0x8E91, 0x8E93, 0x8E94, 0x8E99, 0x8E99, 0x8EA1, 0x8EA1, 0x8EAA, 0x8EAC, 0x8EAF, 0x8EB1, 0x8EBE, 0x8EBE, 0x8EC5, 0x8EC6, 0x8EC8, 0x8EC8, 0x8ECA, 0x8ECD, 0x8ED2, 0x8ED2, 0x8EDB, 0x8EDB, 0x8EDF, 0x8EDF, 0x8EE2, 0x8EE3, 0x8EEB, 0x8EEB, 0x8EF8, 0x8EF8, 0x8EFB, 0x8EFE, 0x8F03, 0x8F03, 0x8F05, 0x8F05, 0x8F09, 0x8F0A, 0x8F0C, 0x8F0C, 0x8F12, 0x8F15, 0x8F19, 0x8F19, 0x8F1B, 0x8F1D, 0x8F1F, 0x8F1F, 0x8F26, 0x8F26, 0x8F29, 0x8F2A, 0x8F2F, 0x8F2F, 0x8F33, 0x8F33, 0x8F38, 0x8F39, 0x8F3B, 0x8F3B, 0x8F3E, 0x8F3F, 0x8F42, 0x8F42, 0x8F44, 0x8F46, 0x8F49, 0x8F49, 0x8F4C, 0x8F4E, 0x8F57, 0x8F57, 0x8F5C, 0x8F5C, 0x8F5F, 0x8F5F, 0x8F61, 0x8F64, 0x8F9B, 0x8F9C, 0x8F9E, 0x8F9F, 0x8FA3, 0x8FA3, 0x8FA7, 0x8FA8, 0x8FAD, 0x8FB2, 0x8FB7, 0x8FB7, 0x8FBA, 0x8FBC, 0x8FBF, 0x8FBF, 0x8FC2, 0x8FC2, 0x8FC4, 0x8FC5, 0x8FCE, 0x8FCE, 0x8FD1, 0x8FD1, 0x8FD4, 0x8FD4, 0x8FDA, 0x8FDA, 0x8FE2, 0x8FE2, 0x8FE5, 0x8FE6, 0x8FE9, 0x8FEB, 0x8FED, 0x8FED, 0x8FEF, 0x8FF0, 0x8FF4, 0x8FF4, 0x8FF7, 0x8FFA, 0x8FFD, 0x8FFD, 0x9000, 0x9001, 0x9003, 0x9003, 0x9005, 0x9006, 0x900B, 0x900B, 0x900D, 0x9011, 0x9013, 0x9017, 0x9019, 0x901A, 0x901D, 0x9023, 0x9027, 0x9027, 0x902E, 0x902E, 0x9031, 0x9032, 0x9035, 0x9036, 0x9038, 0x9039, 0x903C, 0x903C, 0x903E, 0x903E, 0x9041, 0x9042, 0x9045, 0x9045, 0x9047, 0x9047, 0x9049, 0x904B, 0x904D, 0x9056, 0x9058, 0x9059, 0x905C, 0x905C, 0x905E, 0x905E, 0x9060, 0x9061, 0x9063, 0x9063, 0x9065, 0x9065, 0x9068, 0x9069, 0x906D, 0x906F, 0x9072, 0x9072, 0x9075, 0x9078, 0x907A, 0x907A, 0x907C, 0x907D, 0x907F, 0x9084, 0x9087, 0x9087, 0x9089, 0x908A, 0x908F, 0x908F, 0x9091, 0x9091, 0x90A3, 0x90A3, 0x90A6, 0x90A6, 0x90A8, 0x90A8, 0x90AA, 0x90AA, 0x90AF, 0x90AF, 0x90B1, 0x90B1, 0x90B5, 0x90B5, 0x90B8, 0x90B8, 0x90C1, 0x90C1, 0x90CA, 0x90CA, 0x90CE, 0x90CE, 0x90DB, 0x90DB, 0x90E1, 0x90E2, 0x90E4, 0x90E4, 0x90E8, 0x90E8, 0x90ED, 0x90ED, 0x90F5, 0x90F5, 0x90F7, 0x90F7, 0x90FD, 0x90FD, 0x9102, 0x9102, 0x9112, 0x9112, 0x9119, 0x9119, 0x912D, 0x912D, 0x9130, 0x9130, 0x9132, 0x9132, 0x9149, 0x914E, 0x9152, 0x9152, 0x9154, 0x9154, 0x9156, 0x9156, 0x9158, 0x9158, 0x9162, 0x9163, 0x9165, 0x9165, 0x9169, 0x916A, 0x916C, 0x916C, 0x9172, 0x9173, 0x9175, 0x9175, 0x9177, 0x9178, 0x9182, 0x9182, 0x9187, 0x9187, 0x9189, 0x9189, 0x918B, 0x918B, 0x918D, 0x918D, 0x9190, 0x9190, 0x9192, 0x9192, 0x9197, 0x9197, 0x919C, 0x919C, 0x91A2, 0x91A2, 0x91A4, 0x91A4, 0x91AA, 0x91AB, 0x91AF, 0x91AF, 0x91B4, 0x91B5, 0x91B8, 0x91B8, 0x91BA, 0x91BA, 0x91C0, 0x91C1, 0x91C6, 0x91C9, 0x91CB, 0x91D1, 0x91D6, 0x91D6, 0x91D8, 0x91D8, 0x91DB, 0x91DD, 0x91DF, 0x91DF, 0x91E1, 0x91E1, 0x91E3, 0x91E3, 0x91E6, 0x91E7, 0x91F5, 0x91F6, 0x91FC, 0x91FC, 0x91FF, 0x91FF, 0x920D, 0x920E, 0x9211, 0x9211, 0x9214, 0x9215, 0x921E, 0x921E, 0x9229, 0x9229, 0x922C, 0x922C, 0x9234, 0x9234, 0x9237, 0x9237, 0x923F, 0x923F, 0x9244, 0x9245, 0x9248, 0x9249, 0x924B, 0x924B, 0x9250, 0x9250, 0x9257, 0x9257, 0x925A, 0x925B, 0x925E, 0x925E, 0x9262, 0x9262, 0x9264, 0x9264, 0x9266, 0x9266, 0x9271, 0x9271, 0x927E, 0x927E, 0x9280, 0x9280, 0x9283, 0x9283, 0x9285, 0x9285, 0x9291, 0x9291, 0x9293, 0x9293, 0x9295, 0x9296, 0x9298, 0x9298, 0x929A, 0x929C, 0x92AD, 0x92AD, 0x92B7, 0x92B7, 0x92B9, 0x92B9, 0x92CF, 0x92CF, 0x92D2, 0x92D2, 0x92E4, 0x92E4, 0x92E9, 0x92EA, 0x92ED, 0x92ED, 0x92F2, 0x92F3, 0x92F8, 0x92F8, 0x92FA, 0x92FA, 0x92FC, 0x92FC, 0x9306, 0x9306, 0x930F, 0x9310, 0x9318, 0x931A, 0x9320, 0x9320, 0x9322, 0x9323, 0x9326, 0x9326, 0x9328, 0x9328, 0x932B, 0x932C, 0x932E, 0x932F, 0x9332, 0x9332, 0x9335, 0x9335, 0x933A, 0x933B, 0x9344, 0x9344, 0x934B, 0x934B, 0x934D, 0x934D, 0x9354, 0x9354, 0x9356, 0x9356, 0x935B, 0x935C, 0x9360, 0x9360, 0x936C, 0x936C, 0x936E, 0x936E, 0x9375, 0x9375, 0x937C, 0x937C, 0x937E, 0x937E, 0x938C, 0x938C, 0x9394, 0x9394, 0x9396, 0x9397, 0x939A, 0x939A, 0x93A7, 0x93A7, 0x93AC, 0x93AE, 0x93B0, 0x93B0, 0x93B9, 0x93B9, 0x93C3, 0x93C3, 0x93C8, 0x93C8, 0x93D0, 0x93D1, 0x93D6, 0x93D8, 0x93DD, 0x93DD, 0x93E1, 0x93E1, 0x93E4, 0x93E5, 0x93E8, 0x93E8, 0x9403, 0x9403, 0x9407, 0x9407, 0x9410, 0x9410, 0x9413, 0x9414, 0x9418, 0x941A, 0x9421, 0x9421, 0x942B, 0x942B, 0x9435, 0x9436, 0x9438, 0x9438, 0x943A, 0x943A, 0x9441, 0x9441, 0x9444, 0x9444, 0x9451, 0x9453, 0x945A, 0x945B, 0x945E, 0x945E, 0x9460, 0x9460, 0x9462, 0x9462, 0x946A, 0x946A, 0x9470, 0x9470, 0x9475, 0x9475, 0x9477, 0x9477, 0x947C, 0x947F, 0x9481, 0x9481, 0x9577, 0x9577, 0x9580, 0x9580, 0x9582, 0x9583, 0x9587, 0x9587, 0x9589, 0x958B, 0x958F, 0x958F, 0x9591, 0x9591, 0x9593, 0x9594, 0x9596, 0x9596, 0x9598, 0x9599, 0x95A0, 0x95A0, 0x95A2, 0x95A5, 0x95A7, 0x95A8, 0x95AD, 0x95AD, 0x95B2, 0x95B2, 0x95B9, 0x95B9, 0x95BB, 0x95BC, 0x95BE, 0x95BE, 0x95C3, 0x95C3, 0x95C7, 0x95C7, 0x95CA, 0x95CA, 0x95CC, 0x95CD, 0x95D4, 0x95D6, 0x95D8, 0x95D8, 0x95DC, 0x95DC, 0x95E1, 0x95E2, 0x95E5, 0x95E5, 0x961C, 0x961C, 0x9621, 0x9621, 0x9628, 0x9628, 0x962A, 0x962A, 0x962E, 0x962F, 0x9632, 0x9632, 0x963B, 0x963B, 0x963F, 0x9640, 0x9642, 0x9642, 0x9644, 0x9644, 0x964B, 0x964D, 0x964F, 0x9650, 0x965B, 0x965F, 0x9662, 0x9666, 0x966A, 0x966A, 0x966C, 0x966C, 0x9670, 0x9670, 0x9672, 0x9673, 0x9675, 0x9678, 0x967A, 0x967A, 0x967D, 0x967D, 0x9685, 0x9686, 0x9688, 0x9688, 0x968A, 0x968B, 0x968D, 0x968F, 0x9694, 0x9695, 0x9697, 0x9699, 0x969B, 0x969C, 0x96A0, 0x96A0, 0x96A3, 0x96A3, 0x96A7, 0x96A8, 0x96AA, 0x96AA, 0x96B0, 0x96B2, 0x96B4, 0x96B4, 0x96B6, 0x96B9, 0x96BB, 0x96BC, 0x96C0, 0x96C1, 0x96C4, 0x96C7, 0x96C9, 0x96C9, 0x96CB, 0x96CE, 0x96D1, 0x96D1, 0x96D5, 0x96D6, 0x96D9, 0x96D9, 0x96DB, 0x96DC, 0x96E2, 0x96E3, 0x96E8, 0x96E8, 0x96EA, 0x96EB, 0x96F0, 0x96F0, 0x96F2, 0x96F2, 0x96F6, 0x96F7, 0x96F9, 0x96F9, 0x96FB, 0x96FB, 0x9700, 0x9700, 0x9704, 0x9704, 0x9706, 0x9708, 0x970A, 0x970A, 0x970D, 0x970F, 0x9711, 0x9711, 0x9713, 0x9713, 0x9716, 0x9716, 0x9719, 0x9719, 0x971C, 0x971C, 0x971E, 0x971E, 0x9724, 0x9724, 0x9727, 0x9727, 0x972A, 0x972A, 0x9730, 0x9730, 0x9732, 0x9732, 0x9738, 0x9739, 0x973D, 0x973E, 0x9742, 0x9742, 0x9744, 0x9744, 0x9746, 0x9746, 0x9748, 0x9749, 0x9752, 0x9752, 0x9756, 0x9756, 0x9759, 0x9759, 0x975C, 0x975C, 0x975E, 0x975E, 0x9760, 0x9762, 0x9764, 0x9764, 0x9766, 0x9766, 0x9768, 0x9769, 0x976B, 0x976B, 0x976D, 0x976D, 0x9771, 0x9771, 0x9774, 0x9774, 0x9779, 0x977A, 0x977C, 0x977C, 0x9781, 0x9781, 0x9784, 0x9786, 0x978B, 0x978B, 0x978D, 0x978D, 0x978F, 0x9790, 0x9798, 0x9798, 0x979C, 0x979C, 0x97A0, 0x97A0, 0x97A3, 0x97A3, 0x97A6, 0x97A6, 0x97A8, 0x97A8, 0x97AB, 0x97AB, 0x97AD, 0x97AD, 0x97B3, 0x97B4, 0x97C3, 0x97C3, 0x97C6, 0x97C6, 0x97C8, 0x97C8, 0x97CB, 0x97CB, 0x97D3, 0x97D3, 0x97DC, 0x97DC, 0x97ED, 0x97EE, 0x97F2, 0x97F3, 0x97F5, 0x97F6, 0x97FB, 0x97FB, 0x97FF, 0x97FF, 0x9801, 0x9803, 0x9805, 0x9806, 0x9808, 0x9808, 0x980C, 0x980C, 0x980F, 0x9813, 0x9817, 0x9818, 0x981A, 0x981A, 0x9821, 0x9821, 0x9824, 0x9824, 0x982C, 0x982D, 0x9834, 0x9834, 0x9837, 0x9838, 0x983B, 0x983D, 0x9846, 0x9846, 0x984B, 0x984F, 0x9854, 0x9855, 0x9858, 0x9858, 0x985B, 0x985B, 0x985E, 0x985E, 0x9867, 0x9867, 0x986B, 0x986B, 0x986F, 0x9871, 0x9873, 0x9874, 0x98A8, 0x98A8, 0x98AA, 0x98AA, 0x98AF, 0x98AF, 0x98B1, 0x98B1, 0x98B6, 0x98B6, 0x98C3, 0x98C4, 0x98C6, 0x98C6, 0x98DB, 0x98DC, 0x98DF, 0x98DF, 0x98E2, 0x98E2, 0x98E9, 0x98E9, 0x98EB, 0x98EB, 0x98ED, 0x98EF, 0x98F2, 0x98F2, 0x98F4, 0x98F4, 0x98FC, 0x98FE, 0x9903, 0x9903, 0x9905, 0x9905, 0x9909, 0x990A, 0x990C, 0x990C, 0x9910, 0x9910, 0x9912, 0x9914, 0x9918, 0x9918, 0x991D, 0x991E, 0x9920, 0x9921, 0x9924, 0x9924, 0x9928, 0x9928, 0x992C, 0x992C, 0x992E, 0x992E, 0x993D, 0x993E, 0x9942, 0x9942, 0x9945, 0x9945, 0x9949, 0x9949, 0x994B, 0x994C, 0x9950, 0x9952, 0x9955, 0x9955, 0x9957, 0x9957, 0x9996, 0x9999, 0x99A5, 0x99A5, 0x99A8, 0x99A8, 0x99AC, 0x99AE, 0x99B3, 0x99B4, 0x99BC, 0x99BC, 0x99C1, 0x99C1, 0x99C4, 0x99C6, 0x99C8, 0x99C8, 0x99D0, 0x99D2, 0x99D5, 0x99D5, 0x99D8, 0x99D8, 0x99DB, 0x99DB, 0x99DD, 0x99DD, 0x99DF, 0x99DF, 0x99E2, 0x99E2, 0x99ED, 0x99EE, 0x99F1, 0x99F2, 0x99F8, 0x99F8, 0x99FB, 0x99FB, 0x99FF, 0x99FF, 0x9A01, 0x9A01, 0x9A05, 0x9A05, 0x9A0E, 0x9A0F, 0x9A12, 0x9A13, 0x9A19, 0x9A19, 0x9A28, 0x9A28, 0x9A2B, 0x9A2B, 0x9A30, 0x9A30, 0x9A37, 0x9A37, 0x9A3E, 0x9A3E, 0x9A40, 0x9A40, 0x9A42, 0x9A43, 0x9A45, 0x9A45, 0x9A4D, 0x9A4D, 0x9A55, 0x9A55, 0x9A57, 0x9A57, 0x9A5A, 0x9A5B, 0x9A5F, 0x9A5F, 0x9A62, 0x9A62, 0x9A64, 0x9A65, 0x9A69, 0x9A6B, 0x9AA8, 0x9AA8, 0x9AAD, 0x9AAD, 0x9AB0, 0x9AB0, 0x9AB8, 0x9AB8, 0x9ABC, 0x9ABC, 0x9AC0, 0x9AC0, 0x9AC4, 0x9AC4, 0x9ACF, 0x9ACF, 0x9AD1, 0x9AD1, 0x9AD3, 0x9AD4, 0x9AD8, 0x9AD8, 0x9ADE, 0x9ADF, 0x9AE2, 0x9AE3, 0x9AE6, 0x9AE6, 0x9AEA, 0x9AEB, 0x9AED, 0x9AEF, 0x9AF1, 0x9AF1, 0x9AF4, 0x9AF4, 0x9AF7, 0x9AF7, 0x9AFB, 0x9AFB, 0x9B06, 0x9B06, 0x9B18, 0x9B18, 0x9B1A, 0x9B1A, 0x9B1F, 0x9B1F, 0x9B22, 0x9B23, 0x9B25, 0x9B25, 0x9B27, 0x9B2A, 0x9B2E, 0x9B2F, 0x9B31, 0x9B32, 0x9B3B, 0x9B3C, 0x9B41, 0x9B45, 0x9B4D, 0x9B4F, 0x9B51, 0x9B51, 0x9B54, 0x9B54, 0x9B58, 0x9B58, 0x9B5A, 0x9B5A, 0x9B6F, 0x9B6F, 0x9B74, 0x9B74, 0x9B83, 0x9B83, 0x9B8E, 0x9B8E, 0x9B91, 0x9B93, 0x9B96, 0x9B97, 0x9B9F, 0x9BA0, 0x9BA8, 0x9BA8, 0x9BAA, 0x9BAB, 0x9BAD, 0x9BAE, 0x9BB4, 0x9BB4, 0x9BB9, 0x9BB9, 0x9BC0, 0x9BC0, 0x9BC6, 0x9BC6, 0x9BC9, 0x9BCA, 0x9BCF, 0x9BCF, 0x9BD1, 0x9BD2, 0x9BD4, 0x9BD4, 0x9BD6, 0x9BD6, 0x9BDB, 0x9BDB, 0x9BE1, 0x9BE4, 0x9BE8, 0x9BE8, 0x9BF0, 0x9BF2, 0x9BF5, 0x9BF5, 0x9C04, 0x9C04, 0x9C06, 0x9C06, 0x9C08, 0x9C0A, 0x9C0C, 0x9C0D, 0x9C10, 0x9C10, 0x9C12, 0x9C15, 0x9C1B, 0x9C1B, 0x9C21, 0x9C21, 0x9C24, 0x9C25, 0x9C2D, 0x9C30, 0x9C32, 0x9C32, 0x9C39, 0x9C3B, 0x9C3E, 0x9C3E, 0x9C46, 0x9C48, 0x9C52, 0x9C52, 0x9C57, 0x9C57, 0x9C5A, 0x9C5A, 0x9C60, 0x9C60, 0x9C67, 0x9C67, 0x9C76, 0x9C76, 0x9C78, 0x9C78, 0x9CE5, 0x9CE5, 0x9CE7, 0x9CE7, 0x9CE9, 0x9CE9, 0x9CEB, 0x9CEC, 0x9CF0, 0x9CF0, 0x9CF3, 0x9CF4, 0x9CF6, 0x9CF6, 0x9D03, 0x9D03, 0x9D06, 0x9D09, 0x9D0E, 0x9D0E, 0x9D12, 0x9D12, 0x9D15, 0x9D15, 0x9D1B, 0x9D1B, 0x9D1F, 0x9D1F, 0x9D23, 0x9D23, 0x9D26, 0x9D26, 0x9D28, 0x9D28, 0x9D2A, 0x9D2C, 0x9D3B, 0x9D3B, 0x9D3E, 0x9D3F, 0x9D41, 0x9D41, 0x9D44, 0x9D44, 0x9D46, 0x9D46, 0x9D48, 0x9D48, 0x9D50, 0x9D51, 0x9D59, 0x9D59, 0x9D5C, 0x9D5E, 0x9D60, 0x9D61, 0x9D64, 0x9D64, 0x9D6C, 0x9D6C, 0x9D6F, 0x9D6F, 0x9D72, 0x9D72, 0x9D7A, 0x9D7A, 0x9D87, 0x9D87, 0x9D89, 0x9D89, 0x9D8F, 0x9D8F, 0x9D9A, 0x9D9A, 0x9DA4, 0x9DA4, 0x9DA9, 0x9DA9, 0x9DAB, 0x9DAB, 0x9DAF, 0x9DAF, 0x9DB2, 0x9DB2, 0x9DB4, 0x9DB4, 0x9DB8, 0x9DB8, 0x9DBA, 0x9DBB, 0x9DC1, 0x9DC2, 0x9DC4, 0x9DC4, 0x9DC6, 0x9DC6, 0x9DCF, 0x9DCF, 0x9DD3, 0x9DD3, 0x9DD9, 0x9DD9, 0x9DE6, 0x9DE6, 0x9DED, 0x9DED, 0x9DEF, 0x9DEF, 0x9DF2, 0x9DF2, 0x9DF8, 0x9DFA, 0x9DFD, 0x9DFD, 0x9E1A, 0x9E1B, 0x9E1E, 0x9E1E, 0x9E75, 0x9E75, 0x9E78, 0x9E79, 0x9E7D, 0x9E7D, 0x9E7F, 0x9E7F, 0x9E81, 0x9E81, 0x9E88, 0x9E88, 0x9E8B, 0x9E8C, 0x9E91, 0x9E93, 0x9E95, 0x9E95, 0x9E97, 0x9E97, 0x9E9D, 0x9E9D, 0x9E9F, 0x9E9F, 0x9EA5, 0x9EA6, 0x9EA9, 0x9EAA, 0x9EAD, 0x9EAD, 0x9EB8, 0x9EBC, 0x9EBE, 0x9EBF, 0x9EC4, 0x9EC4, 0x9ECC, 0x9ED0, 0x9ED2, 0x9ED2, 0x9ED4, 0x9ED4, 0x9ED8, 0x9ED9, 0x9EDB, 0x9EDE, 0x9EE0, 0x9EE0, 0x9EE5, 0x9EE5, 0x9EE8, 0x9EE8, 0x9EEF, 0x9EEF, 0x9EF4, 0x9EF4, 0x9EF6, 0x9EF7, 0x9EF9, 0x9EF9, 0x9EFB, 0x9EFD, 0x9F07, 0x9F08, 0x9F0E, 0x9F0E, 0x9F13, 0x9F13, 0x9F15, 0x9F15, 0x9F20, 0x9F21, 0x9F2C, 0x9F2C, 0x9F3B, 0x9F3B, 0x9F3E, 0x9F3E, 0x9F4A, 0x9F4B, 0x9F4E, 0x9F4F, 0x9F52, 0x9F52, 0x9F54, 0x9F54, 0x9F5F, 0x9F63, 0x9F66, 0x9F67, 0x9F6A, 0x9F6A, 0x9F6C, 0x9F6C, 0x9F72, 0x9F72, 0x9F76, 0x9F77, 0x9F8D, 0x9F8D, 0x9F95, 0x9F95, 0x9F9C, 0x9F9D, 0x9FA0, 0x9FA0, 0xFF01, 0xFF01, 0xFF03, 0xFF06, 0xFF08, 0xFF0C, 0xFF0E, 0xFF3B, 0xFF3D, 0xFF5D, 0xFF61, 0xFF9F, 0xFFE3, 0xFFE3, 0xFFE5, 0xFFE5, 0xFFFF, 0xFFFF, 0, }; extern float32 radius; static string old_name; extern double fps; void EditTransform(const float32* cameraView, float32* cameraProjection, float32* matrix, bool enable, GAME_OBJECT* object); #include <dxgi1_4.h> extern DXGI_QUERY_VIDEO_MEMORY_INFO info; #include <psapi.h> extern void ShowExampleAppDockSpace(bool* p_open); template <typename ... Args> std::string format(const std::string& fmt, Args ... args) { size_t len = std::snprintf(nullptr, 0, fmt.c_str(), args ...); std::vector<char> buf(len + 1); std::snprintf(&buf[0], len + 1, fmt.c_str(), args ...); return std::string(&buf[0]/*, &buf[0] + len*/); } void printFile(const std::string& path) { wstring wstr; string str; for (const std::filesystem::directory_entry& i : std::filesystem::directory_iterator(path)) { if (i.is_directory()) { //wstr = stringTowstring(i.path().filename().string()); str = format((char*)u8"%s %s", ICON_FA_FOLDER, i.path().filename().string().c_str()); if(ImGui::TreeNodeEx(str.c_str(), ImGuiTreeNodeFlags_Bullet)) { printFile(i.path().string()); ImGui::TreePop(); } } else { str = format((char*)u8"%s %s", ICON_FA_FILE, i.path().filename().string().c_str()); if (ImGui::TreeNodeEx(str.c_str(), ImGuiTreeNodeFlags_Leaf)) { ImGui::PushID(str.c_str()); { if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { ImGui::SetDragDropPayload("DND_DEMO_CELL", i.path().filename().string().c_str(), sizeof(char*) * i.path().filename().string().size()); // Set payload to carry the index of our item (could be anything) { ImGui::Text((char*)u8"%s", str.c_str()); } ImGui::EndDragDropSource(); } ImGui::TreePop(); } ImGui::PopID(); } } } } void My_imgui::Init(HWND hWnd) { // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard | ImGuiConfigFlags_DockingEnable; // Enable Keyboard Controls // u8を使えば日本語の表示はできる ImFontConfig config; // Load a first font ImFont* font = io.Fonts->AddFontDefault(); // Add character ranges and merge into the previous font // The ranges array is not copied by the AddFont* functions and is used lazily // so ensure it is available at the time of building or calling GetTexDataAsRGBA32(). config.MergeMode = true; io.Fonts->AddFontFromFileTTF("./asset/font/Gidole-Regular.ttf", 15.0f, &config, io.Fonts->GetGlyphRangesDefault()); io.Fonts->AddFontFromFileTTF("./asset/font/meiryo.ttc", 16.0f, &config, glyphRangesJapanese); /// config.PixelSnapH = true; ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 }; //io.Fonts->AddFontFromFileTTF("./asset/font/fa-regular-400.ttf", 13.0f, &config, icon_ranges); io.Fonts->AddFontFromFileTTF("./asset/font/Font Awesome 5 Free-Solid-900.otf", 13.0f, &config, icon_ranges); /// io.Fonts->Build(); { CRenderer* render = CRenderer::getInstance(); // Setup Platform/Renderer bindings ImGui_ImplWin32_Init(hWnd); ImGui_ImplDX11_Init(render->GetDevice(), render->GetDeviceContext()); } // Setup Style ImGui::StyleColorsDark(); ImVec4 color = ImVec4(0.06f, 0.06f, 0.06f, 1.0f); ImGuiStyle& style = ImGui::GetStyle(); style.Colors[ImGuiCol_WindowBg] = color; { Component_Items.first.emplace_back((char*)u8"コリジョン AABB"); Component_Items.second.emplace_back("コリジョン AABB"); Component_Items.first.emplace_back((char*)u8"コリジョン OBB"); Component_Items.second.emplace_back("コリジョン OBB"); Component_Items.first.emplace_back((char*)u8"コリジョン 球"); Component_Items.second.emplace_back("コリジョン 球"); Component_Items.first.emplace_back((char*)u8"コリジョン カプセル"); Component_Items.second.emplace_back("コリジョン カプセル"); Component_Items.first.emplace_back((char*)u8"EEEE"); Component_Items.second.emplace_back("EEEE"); Component_Items.first.emplace_back((char*)u8"FFFF"); Component_Items.second.emplace_back("FFFF"); } } void My_imgui::Draw(void) { if (show_demo_window) ImGui::ShowDemoWindow(&show_demo_window); if (show_default_window) { ImGui::Begin("Hello, world!"); ImGui::Text("This is some useful text."); ImGui::Checkbox("Demo Window", &show_demo_window); ImGui::Checkbox("Another Window", &show_another_window); ImGui::Text("Application average %.6f ms/frame (%.1f FPS)", (1000.0f / ImGui::GetIO().Framerate) /** 0.001f*/, ImGui::GetIO().Framerate); ImGui::Text("x = %f", ImGui::GetMousePos().x); ImGui::Text("y = %f", ImGui::GetMousePos().y); ImGui::End(); } if (show_another_window) { ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello from another window!"); if (ImGui::Button("Close Me")) show_another_window = false; ImGui::End(); } static bool show_app_style_editor = false; // メニューバー { if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("New")) {} if (ImGui::MenuItem("Open", "Ctrl+O")) {} if (ImGui::BeginMenu("Open Recent")) { ImGui::MenuItem("fish_hat.c"); ImGui::MenuItem("fish_hat.inl"); ImGui::MenuItem("fish_hat.h"); if (ImGui::BeginMenu("More..")) { ImGui::MenuItem("Hello"); ImGui::MenuItem("Sailor"); if (ImGui::BeginMenu("Recurse..")) { ImGui::EndMenu(); } ImGui::EndMenu(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Import")) { { if (ImGui::MenuItem("Texture")) { Texture_Import_Enable = true; } if (ImGui::MenuItem("Model")) { Model_Import_Enable = true; } } ImGui::EndMenu(); } if (ImGui::BeginMenu("Delete")) { { if (ImGui::MenuItem("Texture")) { Texture_Delete_Enable = true; } if (ImGui::MenuItem("model")) { Model_Delete_Enable = true; } } ImGui::EndMenu(); } if (ImGui::MenuItem("Close")) { CManager::Get_Instance()->GameEnd(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Edit")) { if (ImGui::MenuItem("Undo", "CTRL+Z")) {} if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item ImGui::Separator(); if (ImGui::MenuItem("Cut", "CTRL+X")) {} if (ImGui::MenuItem("Copy", "CTRL+C")) {} if (ImGui::MenuItem("Paste", "CTRL+V")) {} ImGui::EndMenu(); } if (ImGui::BeginMenu("Setting")) { ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor); ImGui::Checkbox("Default Window", &show_default_window); ImGui::Checkbox("Debug Draw Enable", &Debug_Draw_Enable); ImGui::SameLine(); HelpMarker((char*)u8"デバッグ表示 有効無効\n"); ImGui::MenuItem("Setting", NULL, &Setting_Enable); ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } } if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor, ImGuiWindowFlags_NoResize); ImGuiStyle style = ImGui::GetStyle(); ImGui::ShowStyleEditor(&style); ImGui::End(); } // ドッキングスペース ImGui::DockSpaceOverViewport(ImGui::GetMainViewport(), ImGuiDockNodeFlags_PassthruCentralNode); static string s = GAME_OBJECT::Get_Object_Name_Map().begin()->c_str(); old_name = s; { // ライトの設定 { CRenderer* render = CRenderer::getInstance(); ImGuiWindowFlags window_flag = ImGuiWindowFlags_NoResize; LIGHT* light = render->Get_Light(); float32 vec4_Direction[] = { light->Direction.x, light->Direction.y, light->Direction.z, light->Direction.w }; float32 vec4_Position[] = { light->Position.x, light->Position.y, light->Position.z, light->Position.w }; float32 vec4_Diffuse[] = { light->Diffuse.r, light->Diffuse.g, light->Diffuse.b, light->Diffuse.a }; float32 vec4_Ambient[] = { light->Ambient.r, light->Ambient.g, light->Ambient.b, light->Ambient.a }; float32 vec4_Specular[] = { light->Specular.r, light->Specular.g, light->Specular.b, light->Specular.a }; ImGui::Begin("Directional Light", nullptr/*, window_flag*/); ImGui::DragFloat4("Direction", vec4_Direction, 0.01f); ImGui::SameLine(); HelpMarker((char*)u8"\"平行光\" 向き\n"); ImGui::DragFloat4("Position", vec4_Position, 0.01f); ImGui::SameLine(); HelpMarker((char*)u8"\"平行光源の位置\""); ImGui::DragFloat4("Diffuse", vec4_Diffuse, 0.01f); ImGui::SameLine(); HelpMarker((char*)u8"\"平行光\" 拡散(直接)光\n"); ImGui::DragFloat4("Ambient", vec4_Ambient, 0.01f); ImGui::SameLine(); HelpMarker((char*)u8"\"平行光\" 環境光\n"); ImGui::DragFloat4("Specular", vec4_Specular, 0.01f); ImGui::SameLine(); HelpMarker((char*)u8"\"平行光\" 鏡面光\n"); ImGui::End(); // ライトの設定 light->Direction = Vector4(vec4_Direction[0], vec4_Direction[1], vec4_Direction[2], vec4_Direction[3]); light->Position = Vector4(vec4_Position[0], vec4_Position[1], vec4_Position[2], vec4_Position[3]); light->Diffuse = COLOR(vec4_Diffuse[0], vec4_Diffuse[1], vec4_Diffuse[2], vec4_Diffuse[3]); light->Ambient = COLOR(vec4_Ambient[0], vec4_Ambient[1], vec4_Ambient[2], vec4_Ambient[3]); light->Specular = COLOR(vec4_Specular[0], vec4_Specular[1], vec4_Specular[2], vec4_Specular[3]); render->SetLight(light); } // レンダリングテクスチャ { // タイトルバーありの場合、imageyよりWindowSizeがImVec2(17, 40)分大きければ丁度いい // タイトルバーなしの場合、imageyよりWindowSizeがImVec2(13, 16)分大きければ丁度いい ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize; { ImGui::SetNextWindowSize(ImVec2(512 + 17, 512 + 40), ImGuiCond_Once); ImGui::Begin("Shadow", nullptr, window_flags); ImTextureID image = CManager::Get_Instance()->Get_ShadowMap()->Get(); ImGui::Image(image, ImVec2(512, 512)); ImGui::End(); } } // オブジェクト一覧 { ImGuiWindowFlags window_flag = ImGuiWindowFlags_NoTitleBar; ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; auto map = GAME_OBJECT::Get_Object_Name_Map(); vector<string> Object_Name_List; Object_Name_List.reserve(map.size()); for (auto object : map) { Object_Name_List.emplace_back(object); } sort(Object_Name_List.begin(), Object_Name_List.end()); ImGui::Begin("World", nullptr, window_flag); ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); { int32 i = 0; for (auto object : Object_Name_List) { // マウスボタン : 0 = left, 1 = right, 2 = middle + extras string str = object.c_str(); node_flags |= /*ImGuiTreeNodeFlags_Leaf |*/ ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, str.c_str()); if (ImGui::IsMouseClicked(0)) { if (ImGui::IsItemClicked(0)) { s = str.c_str(); } } if (ImGui::IsMouseClicked(1)) { if (ImGui::IsItemClicked(1)) { s = str.c_str(); } } i++; } } ImGui::End(); } } { const weak_ptr<DEBUG_CAMERA> camera = CManager::Get_Instance()->Get_Scene()->Get_Game_Object<DEBUG_CAMERA>("camera"); ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize; ImGui::SetNextWindowSize(ImVec2(500, 500), ImGuiCond_Once); ImGui::Begin("Test", nullptr, window_flags); { ImGuiIO& io = ImGui::GetIO(); if (io.WantCaptureMouse) { ImGui::Text((char*)u8"true"); } else { ImGui::Text((char*)u8"false"); } ImGui::Text((char*)u8"%f", fps); auto p = CManager::Get_Instance()->Get_Scene()->Get_Game_Object<PLAYER>("player"); if (!p.expired()) { ("HP %f", p.lock()->Get_HP()); } } { ImGui::Text((char*)u8"GPUメモリ使用量 %d byte", info.CurrentUsage); ImGui::Text((char*)u8"1 %d キロバイト", info.CurrentUsage / 1000); ImGui::Text((char*)u8"1 %d メガバイト", info.CurrentUsage / 1000 / 1000); } { HANDLE hProc = GetCurrentProcess(); PROCESS_MEMORY_COUNTERS_EX pmc; BOOL isSuccess = GetProcessMemoryInfo(hProc, (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); if (isSuccess == FALSE) { CloseHandle(hProc); } else { ImGui::Text((char*)u8"メモリ使用量 %d byte", pmc.PrivateUsage); ImGui::Text((char*)u8"1 メモリ使用量 %.3f キロバイト", float32(pmc.PrivateUsage / 1024.0f)); ImGui::Text((char*)u8"2 メモリ使用量 %.3f メガバイト", float32(pmc.PrivateUsage / 1024.0f / 1024.0f)); CloseHandle(hProc); } } { ImDrawList* draw_list = ImGui::GetWindowDrawList(); ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos; { ImGui::DrawRect(ImVec2(100, 100), ImVec4(1.0f, 0.f, 0.f, 1.0f), "test", ImVec4(0.f, 0.f, 0.f, 1.0f), 3.0f); } ImGui::SameLine(); { ImGui::DrawRect(ImVec2(100, 100), ImVec4(0.f, 0.f, 1.0f, 1.0f), "test", ImVec4(0.f, 0.f, 0.f, 1.0f), 3.0f); } ImGui::SameLine(); { ImGui::DrawRect(ImVec2(100, 100), ImVec4(1.0f, 1.0f, 0.f, 1.0f), "test", ImVec4(0.f, 0.f, 0.f, 1.0f), 3.0f); } } ImGui::End(); } // Drag Test { static std::vector<std::string> names = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }; static int32 cnt = 0; if (ImGui::Begin("Drag Test")) { enum Mode { Mode_Copy, Mode_Move, Mode_Swap }; auto tex_file = TEXTURE_MANEGER::Get_Instance()->Get_TextureFile().begin(); TEXTURE tex; for (cnt = 0; cnt < 9; cnt++) { ImGui::PushID(cnt); { if ((cnt % 3) != 0) ImGui::SameLine(); size_t pos = tex_file->second.Path.find_last_of("/"); string tex_name = tex_file->second.Path.substr(pos + 1); ImGui::BeginGroup(); { { auto hash = std::hash<string>()(tex_name); ImTextureID image = TEXTURE_MANEGER::Get_Instance()->GetShaderResourceView(hash); auto wh = TEXTURE_MANEGER::Get_Instance()->Get_WH(hash); //ImVec2 size =ImVec2(wh->x / 5.0f, wh->y / 5.0f); const ImVec2 size = ImVec2(64.0f, 64.0f); //ImGui::ImageButton(image, size); if ((tex_name.size() * 4.0f) < (size.x * 0.6f)) { ImGui::ImageButton(image, size); ImGui::Indent(size.x * 0.6f - tex_name.size() * 4.0f); } else { //ImGui::Indent((tex_name.size() * 4.0f - size.x) * 0.5f); ImGui::ImageButton(image, size); //ImGui::Indent(tex_name.size() * 4.0f - size.x ); //ImGui::Indent(size.x * 0.6f - tex_name.size() * 4.0f); } } // Our buttons are both drag sources and drag targets here! if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) { ImGui::SetDragDropPayload("DND_DEMO_CELL", &cnt, sizeof(int32)); // Set payload to carry the index of our item (could be anything) //{ ImGui::Text("%s", names[cnt].c_str()); } { ImGui::Text("%s", tex_name.c_str()); } ImGui::EndDragDropSource(); } ImGui::Text("%s", tex_name.c_str()); ImGui::Spacing(); } ImGui::EndGroup(); tex_file++; } ImGui::PopID(); } ImGui::End(); } if (ImGui::Begin("Drop Test")) { static std::vector<std::string> names_temp = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }; enum Mode { Mode_Copy, Mode_Move, Mode_Swap }; static int32 mode = 0; if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine(); if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine(); if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; } auto start = TEXTURE_MANEGER::Get_Instance()->Get_TextureFile().begin(); for (cnt = 0; cnt < names_temp.size(); cnt++) { ImGui::PushID(cnt); if ((cnt % 3) != 0) ImGui::SameLine(); ImGui::Button(names_temp[cnt].c_str(), ImVec2(names_temp[cnt].size() * 8.0f, 60)); if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_DEMO_CELL")) { //IM_ASSERT(payload->DataSize == sizeof(int32)); //IM_ASSERT(payload->DataSize == sizeof(char*)); //int32 payload_n = *(const int32*)payload->Data; string str = reinterpret_cast<char*>(payload->Data); if (mode == Mode_Copy) { size_t pos = start->second.Path.find_last_of("/"); string tex_name = start->second.Path.substr(pos + 1); //names_temp[cnt] = tex_name; names_temp[cnt] = str.c_str(); } /*if (mode == Mode_Move) { names_temp[cnt] = names[payload_n]; names[payload_n] = ""; }*/ /*if (mode == Mode_Swap) { const auto tmp = names[cnt]; names[cnt] = names[payload_n]; names[payload_n] = tmp; }*/ } ImGui::EndDragDropTarget(); } ImGui::PopID(); start++; } ImGui::End(); } } { ImGuiWindowFlags flag = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize; ImVec2 size(150.0f, 50.f); ImVec2 pos(SCREEN_WIDTH * 0.5f - size.x * 0.5f, 20.0f); ImGui::SetNextWindowSize(size); ImGui::SetNextWindowPos(pos); ImGui::Begin("PLAY", nullptr, flag); static int32 radio = 1; ImGui::RadioButton("PLAT", &radio, 1); ImGui::SameLine(); ImGui::RadioButton("STOP", &radio, 0); radio ? CManager::Get_Instance()->Set_Play_Enable(true) : CManager::Get_Instance()->Set_Play_Enable(false); ImGui::End(); } { // タイトルバーありの場合、imageyよりWindowSizeがImVec2(17, 40)分大きければ丁度いい // タイトルバーなしの場合、imageyよりWindowSizeがImVec2(13, 16)分大きければ丁度いい ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar; { ImGui::Begin("folder_tree"); printFile("asset"); ImGui::Text((char*)u8"メモリ使用量"); ImGui::Text((char*)u8"%s %s %s %s", ICON_FA_COG, ICON_FA_COGS, ICON_FA_COINS, ICON_FA_COLUMNS); ImGui::End(); } // ライトの設定(ディレクショナルライトではない) { Light_Setting(); } // インスペクター { Draw_Inspector(s); } // テクスチャにインポート Texture_Import(); // テクスチャの削除 Texture_Delete(); // モデルにインポート Model_Import(); // モデルの削除 Model_Delete(); Setting(); File(); } } void My_imgui::Update(void) { { if (ImGui::GetIO().WantCaptureMouse) { Mouse_Over_Enable = true; } else { Mouse_Over_Enable = false; } COMPONENT_MANEGER::Set_Draw_Enable_All(Debug_Draw_Enable); } } void My_imgui::Uninit(void) { ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); { pair< vector<string>, vector<string> > temp; temp.swap(Component_Items); } } void My_imgui::Begin() { ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); ImGuizmo::BeginFrame(); } void My_imgui::End() { // Rendering ImGui::Render(); ImGui::EndFrame(); } void My_imgui::Render(void) { ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); } const bool My_imgui::Get_Mouse_Over_Enable() { return Mouse_Over_Enable; } void My_imgui::Draw_Inspector(const string& name) { //static const char* item_current = nullptr; //static const char* temp_current = nullptr; static unique_ptr<const char> item_current; static unique_ptr<const char> temp_current; bool flag = false; if (old_name != name) { flag = true; item_current = nullptr; temp_current = nullptr; } auto object = SCENE::Get_Game_Object(name); if (nullptr != object) { ImGui::Begin("Inspector"); ImGui::Text(object->Get_Object_Name().c_str()); static bool enable = true; ImGui::Checkbox("Enable", &enable); // 3Dギズモ { XMMATRIX mtr; const auto camera1 = SCENE::Get_Game_Object<CCamera>("camera"); const auto camera2 = SCENE::Get_Game_Object<DEBUG_CAMERA>("camera"); { if (!camera1.expired() && Empty_weak_ptr<CCamera>(camera1)) { mtr = camera1.lock()->Get_Camera_View(); } else { mtr = camera2.lock()->Get_Camera_View(); } } XMFLOAT4X4 mat44; XMStoreFloat4x4(&mat44, mtr); float32 view[16] = { mat44._11, mat44._12, mat44._13,mat44._14, mat44._21, mat44._22, mat44._23,mat44._24, mat44._31, mat44._32, mat44._33,mat44._34, mat44._41, mat44._42, mat44._43,mat44._44 }; { if (!camera1.expired() && Empty_weak_ptr<CCamera>(camera1)) { mtr = camera1.lock()->Get_Camera_Projection(); } else { mtr = camera2.lock()->Get_Camera_Projection(); } } XMStoreFloat4x4(&mat44, mtr); float32 pro[16] = { mat44._11, mat44._12, mat44._13,mat44._14, mat44._21, mat44._22, mat44._23,mat44._24, mat44._31, mat44._32, mat44._33,mat44._34, mat44._41, mat44._42, mat44._43,mat44._44 }; mtr = XMMatrixTranslation(object->Get_Transform().Get_Position()->x, object->Get_Transform().Get_Position()->y, object->Get_Transform().Get_Position()->z); XMStoreFloat4x4(&mat44, mtr); static float32 pos[16] = { mat44._11, mat44._12, mat44._13,mat44._14, mat44._21, mat44._22, mat44._23,mat44._24, mat44._31, mat44._32, mat44._33,mat44._34, mat44._41, mat44._42, mat44._43,mat44._44 }; if (flag) { mtr = XMMatrixScaling(object->Get_Transform().Get_Scaling()->x, object->Get_Transform().Get_Scaling()->y, object->Get_Transform().Get_Scaling()->z); mtr *= XMMatrixTranslation(object->Get_Transform().Get_Position()->x, object->Get_Transform().Get_Position()->y, object->Get_Transform().Get_Position()->z); XMStoreFloat4x4(&mat44, mtr); pos[0] = mat44._11, pos[1] = mat44._12, pos[2] = mat44._13, pos[3] = mat44._14; pos[4] = mat44._21, pos[5] = mat44._22, pos[6] = mat44._23, pos[7] = mat44._24; pos[8] = mat44._31, pos[9] = mat44._32, pos[10] = mat44._33, pos[11] = mat44._34; pos[12] = mat44._41, pos[13] = mat44._42, pos[14] = mat44._43, pos[15] = mat44._44; } EditTransform(view, pro, pos, enable, object); } { { if (ImGui::BeginCombo((char*)u8"コンポーネント", item_current.get(), ImGuiComboFlags_NoArrowButton)) // The second parameter is the label previewed before opening the combo. { for (int32 n = 0; n < Component_Items.first.size(); n++) { bool is_selected = (item_current.get() == Component_Items.first.at(n).c_str()); //if (ImGui::Selectable(Component_Items.first.at(n), is_selected)) if (ImGui::Selectable(Component_Items.first.at(n).c_str(), is_selected)) { //item_current = Component_Items.first.at(n).c_str(); //temp_current = Component_Items.second.at(n).c_str(); item_current.reset(Component_Items.first.at(n).c_str()); temp_current.reset(Component_Items.second.at(n).c_str()); } } ImGui::EndCombo(); } } { Draw_Components(object->Get_Component()->Get_All_Components()); } if (ImGui::Button("Add Component")) { if (nullptr != temp_current) { string s(temp_current.get()); Add_Component(object, s); } } if (ImGui::Button("Delete Component")) { if (nullptr != temp_current) { string s(temp_current.get()); Delete_Component(object, s); } } } ImGui::End(); } } void EditTransform(const float32* cameraView, float32* cameraProjection, float32* matrix, bool enable, GAME_OBJECT* object) { static ImGuizmo::OPERATION mCurrentGizmoOperation(ImGuizmo::TRANSLATE); float32 snap[3] = { 0.001f, 0.001f, 0.001f }; if (ImGui::RadioButton("Translate", mCurrentGizmoOperation == ImGuizmo::TRANSLATE)) mCurrentGizmoOperation = ImGuizmo::TRANSLATE; ImGui::SameLine(); if (ImGui::RadioButton("Rotate", mCurrentGizmoOperation == ImGuizmo::ROTATE)) mCurrentGizmoOperation = ImGuizmo::ROTATE; ImGui::SameLine(); if (ImGui::RadioButton("Scale", mCurrentGizmoOperation == ImGuizmo::SCALE)) mCurrentGizmoOperation = ImGuizmo::SCALE; { std::array<float32, 3> Translation{ object->Get_Transform().Get_Position()->x, object->Get_Transform().Get_Position()->y, object->Get_Transform().Get_Position()->z }; const std::array<float32, 3> Translation_Ans{ object->Get_Transform().Get_Position()->x, object->Get_Transform().Get_Position()->y, object->Get_Transform().Get_Position()->z }; std::array<float32, 3> Rotation = { object->Get_Transform().Get_Rotation()->x, object->Get_Transform().Get_Rotation()->y, object->Get_Transform().Get_Rotation()->z }; const std::array<float32, 3> Rotation_Ans = { object->Get_Transform().Get_Rotation()->x, object->Get_Transform().Get_Rotation()->y, object->Get_Transform().Get_Rotation()->z }; float32 R[3] = { object->Get_Transform().Get_Rotation()->x, object->Get_Transform().Get_Rotation()->y, object->Get_Transform().Get_Rotation()->z }; std::array<float32, 3> Scale = { object->Get_Transform().Get_Scaling()->x, object->Get_Transform().Get_Scaling()->y, object->Get_Transform().Get_Scaling()->z }; const std::array<float32, 3> Scale_Ans = { object->Get_Transform().Get_Scaling()->x, object->Get_Transform().Get_Scaling()->y, object->Get_Transform().Get_Scaling()->z }; //ImGuizmo::DecomposeMatrixToComponents(matrix, Translation, Rotation, Scale); ImGui::DragFloat3((char*)u8"トランスフォーム", (float32*)object->Get_Transform().Get_Position(), 0.01f); ImGui::DragFloat3((char*)u8"回転", (float32*)object->Get_Transform().Get_Rotation(), 0.1f); ImGui::DragFloat3((char*)u8"スケール", (float32*)object->Get_Transform().Get_Scaling(), 0.01f); ImGuizmo::DecomposeMatrixToComponents(matrix, Translation.data(), Rotation.data(), Scale.data()); //ImGuizmo::RecomposeMatrixFromComponents(Translation, Rotation, Scale, matrix); ImGuizmo::RecomposeMatrixFromComponents(Translation.data(), Rotation.data(), Scale.data(), matrix); switch (mCurrentGizmoOperation) { case ImGuizmo::TRANSLATE: { if (Translation_Ans != Translation) { Vector3 vec(Translation[0], Translation[1], Translation[2]); object->Get_Transform().Set_Position(vec); } } break; case ImGuizmo::ROTATE: { if (Rotation_Ans != Rotation) { Vector3 vec(Rotation[0], Rotation[1], Rotation[2]); object->Get_Transform().Set_Rotation(vec); } } break; case ImGuizmo::SCALE: { if (Scale_Ans != Scale) { Vector3 vec(Scale[0], Scale[1], Scale[2]); object->Get_Transform().Set_Scaling(vec); } } break; default: break; } if (enable) { //Vector3 vec1(Translation[0], Translation[1], Translation[2]); Vector3 vec2/*(Rotation[0], Rotation[1], Rotation[2])*/; //Vector3 vec3(Scale[0], Scale[1], Scale[2]); //object->Get_Transform().Set_Position(vec1); //object->Set_Rotation(vec2); //object->Get_Transform().Set_Scaling(vec3); ImGui::DragFloat3("Rotation", R, 0.2f, -180.f, 180.f); vec2 = Vector3(R[0], R[1], R[2]); object->Get_Transform().Set_Rotation(vec2); } } ImGuiIO& io = ImGui::GetIO(); ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y); ImGuizmo::Manipulate(cameraView, cameraProjection, mCurrentGizmoOperation, ImGuizmo::LOCAL, matrix, NULL, &snap[0], NULL, NULL); } void My_imgui::Draw_Components(const vector<COMPONENT*>& components) { ImGui::Spacing(); ImGui::Text((char*)u8"コンポーネント"); ImGui::Spacing(); for (const auto& com : components) { ImGui::Spacing(); com->Draw_Inspector(); ImGui::Spacing(); } } void My_imgui::Texture_Import() { static bool flag = false; static bool flag2 = false; static string file_name; ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; if(Texture_Import_Enable) { static char check; ImGui::SetNextWindowSize(ImVec2(360, 167), ImGuiCond_Appearing); if(ImGui::Begin((char*)u8"テクスチャ インポート", &Texture_Import_Enable, window_flags)) { ImGui::Indent(15.0f); ImGui::InputText((char*)u8"テクスチャ名", &file_name); ImGui::SameLine(); HelpMarker((char*)u8"対応フォーマットは 'png' 'jpg''dds'"); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Indent(100); ImVec2 size(100, 40); if (ImGui::Button((char*)u8"インポート", size)) { check = Texture_File_Check(file_name); if (1 == check) { TEXTURE_MANEGER::Get_Instance()->Add(file_name); ImGui::Text((char*)u8"テクスチャが読み込まれました"); } else { flag2 = true; } } ImGui::End(); } if (flag2) { ImGui::SetNextWindowPos(ImVec2(SCREEN_WIDTH * 0.5f - 120.0f, SCREEN_HEIGHT * 0.5f - 55.0f), ImGuiCond_Appearing); if (ImGui::Begin((char*)u8"エラー", &flag2, window_flags)) { ImGui::Indent(20.0f); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); switch (check) { case -1: ImGui::Text((char*)u8"テクスチャ名が入力されてないです"); break; case -2: ImGui::Text((char*)u8"既に読み込んでいるテクスチャです"); break; case -3: ImGui::Text((char*)u8"テクスチャが存在しないです"); break; default: break; } ImGui::End(); } } flag = true; } else { if (flag) { file_name = ""; flag = false; } flag2 = false; } } const char My_imgui::Texture_File_Check(const string& file_name) { if (file_name.empty()) { // テクスチャ名が入力されていない return -1; } size_t file = hash<string>()(file_name);// if (TEXTURE_MANEGER::Get_Instance()->Get_TextureFile().find(file) != TEXTURE_MANEGER::Get_Instance()->Get_TextureFile().end()) { // 既に読み込んでいるテクスチャ return -2; } // ファイルがあるかの判定 { string path = "./asset/texture/"; path += file_name; bool flag = std::filesystem::exists(path); if (false == flag) { // ファイルが存在しない return -3; } } return 1; } void My_imgui::Texture_Delete() { static bool flag = true; static bool flag2 = false; static string file_name; ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; if (Texture_Delete_Enable) { static char check; ImGui::SetNextWindowSize(ImVec2(360, 167), ImGuiCond_Appearing); if(ImGui::Begin((char*)u8"テクスチャ 削除", &Texture_Delete_Enable, window_flags)) { ImGui::Indent(15.0f); ImGui::InputText((char*)u8"テクスチャ名", &file_name); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Indent(100); ImVec2 size(100, 40); if (ImGui::Button((char*)u8"削除", size)) { check = Texture_File_Check(file_name); if (-1 != check) { TEXTURE_MANEGER::Get_Instance()->Unload(file_name); ImGui::Text((char*)u8"テクスチャが削除されました"); } else { flag2 = true; } } ImGui::End(); } if (flag2) { ImGui::SetNextWindowPos(ImVec2(SCREEN_WIDTH * 0.5f - 120.0f, SCREEN_HEIGHT * 0.5f - 55.0f), ImGuiCond_Appearing); if (ImGui::Begin((char*)u8"エラー", &flag2, window_flags)) { ImGui::Indent(20.0f); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); switch (check) { case -1: ImGui::Text((char*)u8"テクスチャ名が入力されてないです"); break; case -3: ImGui::Text((char*)u8"テクスチャが存在しないです"); break; default: break; } ImGui::End(); } } flag = true; } else { if (flag) { file_name.clear(); flag = false; } flag2 = false; } } void My_imgui::Model_Import() { static bool flag = false; static bool flag2 = false; static string file_name; ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; if (Model_Import_Enable) { static char check; ImGui::SetNextWindowSize(ImVec2(360, 167), ImGuiCond_Appearing); ImGui::Begin((char*)u8"モデル インポート", &Model_Import_Enable, window_flags); { ImGui::Indent(15.0f); ImGui::InputText((char*)u8"モデル名", &file_name); ImGui::SameLine(); HelpMarker((char*)u8"対応フォーマットは 'fbx'"); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Indent(100); ImVec2 size(100, 40); if (ImGui::Button((char*)u8"インポート", size)) { check = Model_File_Check(file_name); if (1 == check) { MODEL_MANEGER::Get_Instance()->Add(file_name); ImGui::Text((char*)u8"モデルが読み込まれました"); } else { flag2 = true; } } ImGui::End(); } if (flag2) { ImGui::SetNextWindowPos(ImVec2(SCREEN_WIDTH * 0.5f - 120.0f, SCREEN_HEIGHT * 0.5f - 55.0f), ImGuiCond_Appearing); if (ImGui::Begin((char*)u8"エラー", &flag2, window_flags)) { ImGui::Indent(20.0f); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); switch (check) { case -1: ImGui::Text((char*)u8"モデル名が入力されてないです"); break; case -2: ImGui::Text((char*)u8"既に読み込んでいるモデルです"); break; case -3: ImGui::Text((char*)u8"モデルが存在しないです"); break; default: break; } ImGui::End(); } } flag = true; } else { if (flag) { file_name.clear(); flag = false; } flag2 = false; } } const char My_imgui::Model_File_Check(const string& file_name) { if (file_name.empty()) { // モデル名が入力されていない return -1; } size_t file = hash<string>()(file_name);// if (MODEL_MANEGER::Get_Instance()->Get_ModelFile().find(file) != MODEL_MANEGER::Get_Instance()->Get_ModelFile().end()) { // 既に読み込んでいるモデル return -2; } // ファイルがあるかの判定 { string path = "./asset/model/"; path += file_name; bool flag = std::filesystem::exists(path); if (false == flag) { // ファイルが存在しない return -3; } } return 1; } void My_imgui::Model_Delete() { static bool flag = true; static bool flag2 = false; static string file_name; ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; if (Model_Delete_Enable) { static char check; ImGui::SetNextWindowSize(ImVec2(360, 167), ImGuiCond_Appearing); ImGui::Begin((char*)u8"モデル 削除", &Model_Delete_Enable, window_flags); { ImGui::Indent(15.0f); ImGui::InputText((char*)u8"モデル名", &file_name); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Indent(100); ImVec2 size(100, 40); if (ImGui::Button((char*)u8"削除", size)) { check = Texture_File_Check(file_name); if (-1 != check) { TEXTURE_MANEGER::Get_Instance()->Unload(file_name); ImGui::Text((char*)u8"モデルが削除されました"); } else { flag2 = true; } } } ImGui::End(); { if (flag2) { ImGui::SetNextWindowPos(ImVec2(SCREEN_WIDTH * 0.5f - 120.0f, SCREEN_HEIGHT * 0.5f - 55.0f), ImGuiCond_Appearing); ImGui::Begin((char*)u8"エラー", &flag2, window_flags); ImGui::Indent(20.0f); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Spacing(); switch (check) { case -1: ImGui::Text((char*)u8"モデル名が入力されてないです"); break; case -3: ImGui::Text((char*)u8"モデルが存在しないです"); break; default: break; } ImGui::End(); } } flag = true; } else { if (flag) { file_name = ""; flag = false; } flag2 = false; } } void My_imgui::Setting() { if (Setting_Enable) { float32 color[] = { BOUNDING::Get_Default_Color().r, BOUNDING::Get_Default_Color().g, BOUNDING::Get_Default_Color().b }; ImGui::Begin("Setting", &Setting_Enable); { ImGuiColorEditFlags flag = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueWheel; ImGui::ColorPicker3((char*)u8"カラー", color, flag); } ImGui::End(); COLOR c; c.r = color[0]; c.g = color[1]; c.b = color[2]; c.a = 1.0f; BOUNDING::Set_Default_Color(c); } } void My_imgui::File() { // タイトルバーありの場合、imageyよりWindowSizeがImVec2(17, 40)分大きければ丁度いい // タイトルバーなしの場合、imageyよりWindowSizeがImVec2(13, 16)分大きければ丁度いい //ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize; char i = 0; { //ImGui::SetNextWindowSize(ImVec2(256 + 17, 256 + 40), ImGuiCond_Once); ImGui::Begin("Texture"); auto start = TEXTURE_MANEGER::Get_Instance()->Get_TextureData_Start(); auto end = TEXTURE_MANEGER::Get_Instance()->Get_TextureData_End(); for(auto tex = start; tex != end; tex++) { ImTextureID image = tex->second.Resource.get(); if (i < 3) { ImGui::SameLine(); i++; } else { i = 0; ImGui::NewLine(); } ImGui::Image(image, ImVec2(96, 96)); ImGui::SameLine(); ImGui::Dummy(ImVec2(10, 96)); } ImGui::End(); } } void My_imgui::Light_Setting() { // ライトの設定(ディレクショナルライトではない) auto light_manager = CManager::Get_Instance()->Get_Scene()->Get_Light_Manager(); auto lights = light_manager->Get_Lights(); ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize; ImGui::SetNextWindowSize(ImVec2(500, 500), ImGuiCond_Once); ImGui::Begin("Light", nullptr, window_flags); if (ImGui::TreeNode("Light Tree")) { ImGuiTreeNodeFlags_ node_flags = ImGuiTreeNodeFlags_None; ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); for (int32 i = 0; i < lights->size(); i++) { // Disable the default open on single-click behavior and pass in Selected flag according to our selection state. //if(1 == lights->at(i).Enable) { bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Light %d", i); if (node_open) { { bool flag = lights->at(i).Enable; float32 Position[3] = { lights->at(i).Position.x, lights->at(i).Position.y, lights->at(i).Position.z }; float32 Color[3] = { lights->at(i).Color.r, lights->at(i).Color.g, lights->at(i).Color.b }; UINT Type = lights->at(i).Type;// ImGui::Checkbox("Enable", &flag); ImGui::DragFloat3("Position", Position, 0.01f); ImGui::DragFloat3("Color", Color, 0.01f, 0.f, 1.0f); //// { vector<const char*> Items; Items.emplace_back((char*)u8"ポイントライト"); Items.emplace_back((char*)u8"スポットライト"); Items.emplace_back((char*)u8"無効"); const char* item_current; switch (lights->at(i).Type) { case (UINT)LIGHT_TYPE::POINT: item_current = Items[(UINT)LIGHT_TYPE::POINT]; break; case (UINT)LIGHT_TYPE::SPOT: item_current = Items[(UINT)LIGHT_TYPE::SPOT]; break; case (UINT)LIGHT_TYPE::NONE: item_current = Items[(UINT)LIGHT_TYPE::NONE]; break; } bool is_selected = false; { if (ImGui::BeginCombo((char*)u8"ライトの種類", item_current, ImGuiComboFlags_NoArrowButton)) { for (int32 n = 0; n < Items.size(); n++) { //bool is_selected = (item_current == Items[n]); if (ImGui::Selectable(Items[n], is_selected)) { item_current = Items[n]; is_selected = true; } //if (is_selected) // ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } } if (is_selected) { if (Items[0] == item_current) { lights->at(i).Type = (UINT)LIGHT_TYPE::POINT; } if (Items[1] == item_current) { lights->at(i).Type = (UINT)LIGHT_TYPE::SPOT; } if (Items[2] == item_current) { lights->at(i).Type = (UINT)LIGHT_TYPE::NONE; } } } //// lights->at(i).Enable = flag; lights->at(i).Position = Vector3(Position[0], Position[1], Position[2]); lights->at(i).Color = COLOR(Color[0], Color[1], Color[2], 0.0f); } ImGui::TreePop(); } } } ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); ImGui::TreePop(); } ImGui::End(); } void My_imgui::Add_Component(GAME_OBJECT* object, const string s) { ImGui::Text("%s", s.c_str()); auto scene = CManager::Get_Instance()->Get_Scene(); auto comp = object->Get_Component(); if (string::npos != s.find("AABB")) { comp->Add_Component<BOUNDING_AABB>(scene->Get_Game_Object(object)); return; } if (string::npos != s.find("OBB")) { comp->Add_Component<BOUNDING_OBB>(scene->Get_Game_Object(object)); return; } if (string::npos != s.find("球")) { comp->Add_Component<BOUNDING_SHPERE>(scene->Get_Game_Object(object)); return; } if (string::npos != s.find("カプセル")) { comp->Add_Component<BOUNDING_CAPSULE>(scene->Get_Game_Object(object)); return; } } void My_imgui::Delete_Component(GAME_OBJECT* object, const string s) { ImGui::Text("%s", s.c_str()); auto scene = CManager::Get_Instance()->Get_Scene(); auto comp = object->Get_Component(); COMPONENT* component = nullptr; if (string::npos != s.find("AABB")) { component = comp->Get_Component<BOUNDING_AABB>(); } if (string::npos != s.find("OBB")) { component = comp->Get_Component<BOUNDING_OBB>(); } if (string::npos != s.find("球")) { component = comp->Get_Component<BOUNDING_SHPERE>(); } if (string::npos != s.find("カプセル")) { component = comp->Get_Component<BOUNDING_CAPSULE>(); } if(nullptr == component) return; component->SetDestroy(); } void ImGui::DrawRect(const ImVec2& size, const ImVec4& color, const char* text, const ImVec4& text_color, const float32 frame_size, const ImVec4& frame_color) { ImDrawList* draw_list = ImGui::GetWindowDrawList(); ImGuiStyle& style = ImGui::GetStyle(); const ImVec2 pos = ImGui::GetCurrentWindow()->DC.CursorPos; const ImRect bb(pos, pos + size); // 枠線の描画 { const ImU32 col = ImGui::GetColorU32(frame_color); draw_list->AddRect(bb.Min, bb.Max, col, 0.0f, ImDrawCornerFlags_All, frame_size); } // 矩形の描画 { if (nullptr == text) text = ""; const ImVec2 label_size = ImGui::CalcTextSize(text, NULL, true); const ImU32 col = ImGui::GetColorU32(color); draw_list->AddRectFilled(bb.Min, bb.Max, col); const ImVec4 color = style.Colors[ImGuiCol_Text]; style.Colors[ImGuiCol_Text] = text_color; ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, text, NULL, &label_size, style.ButtonTextAlign, &bb); style.Colors[ImGuiCol_Text] = color; ImGui::Dummy(ImVec2(size.x - frame_size * 2.0f, size.y - frame_size * 2.0f)); } } #endif // _DEBUG
// Copyright 2021 Lawrence Livermore National Security, LLC and other ExaCA Project Developers. // See the top-level LICENSE file for details. // // SPDX-License-Identifier: MIT #ifndef EXACA_PRINT_HPP #define EXACA_PRINT_HPP #include "CAtypes.hpp" #include <Kokkos_Core.hpp> #include <string> void PrintGrainIDsForExaConstit(std::string FName, int nx, int ny, int nz, ViewI3D_H GrainID_WholeDomain, double deltax); void CollectIntField(ViewI3D_H IntVar_WholeDomain, ViewI_H IntVar, int nx, int ny, int nz, int MyXSlices, int MyYSlices, int np, ViewI_H RecvXOffset, ViewI_H RecvYOffset, ViewI_H RecvXSlices, ViewI_H RecvYSlices, ViewI_H RBufSize); void CollectFloatField(ViewF3D_H FloatVar_WholeDomain, ViewF_H FloatVar, int nx, int ny, int nz, int MyXSlices, int MyYSlices, int np, ViewI_H RecvXOffset, ViewI_H RecvYOffset, ViewI_H RecvXSlices, ViewI_H RecvYSlices, ViewI_H RBufSize); void CollectBoolField(ViewI3D_H IntVar_WholeDomain, bool *BoolVar, int nx, int ny, int nz, int MyXSlices, int MyYSlices, int np, ViewI_H RecvXOffset, ViewI_H RecvYOffset, ViewI_H RecvXSlices, ViewI_H RecvYSlices, ViewI_H RBufSize); void SendIntField(ViewI_H VarToSend, int nz, int MyXSlices, int MyYSlices, int SendBufSize); void SendFloatField(ViewF_H VarToSend, int nz, int MyXSlices, int MyYSlices, int SendBufSize); void SendBoolField(bool *VarToSend, int nz, int MyXSlices, int MyYSlices, int SendBufSize); void PrintExaCAData(int id, int np, int nx, int ny, int nz, int MyXSlices, int MyYSlices, int ProcessorsInXDirection, int ProcessorsInYDirection, ViewI_H GrainID, ViewI_H GrainOrientation, ViewI_H CritTimeStep, ViewF_H GrainUnitVector, ViewI_H LayerID, ViewI_H CellType, ViewF_H UndercoolingChange, ViewF_H UndercoolingCurrent, std::string BaseFileName, int DecompositionStrategy, int NGrainOrientations, bool *Melted, std::string PathToOutput, int PrintDebug, bool PrintMisorientation, bool PrintFullOutput); void PrintExaCALog(int id, int np, std::string InputFile, std::string SimulationType, int DecompositionStrategy, int MyXSlices, int MyYSlices, int MyXOffset, int MyYOffset, double AConst, double BConst, double CConst, double DConst, double FreezingRange, double deltax, double NMax, double dTN, double dTsigma, std::string tempfile, int TempFilesInSeries, double HT_deltax, bool RemeltingYN, double deltat, int NumberOfLayers, int LayerHeight, std::string SubstrateFileName, double SubstrateGrainSpacing, bool SubstrateFile, double G, double R, int nx, int ny, int nz, double FractSurfaceSitesActive, std::string PathToOutput, int NSpotsX, int NSpotsY, int SpotOffset, int SpotRadius, std::string BaseFileName, double InitTime, double RunTime, double OutTime, int cycle, double InitMaxTime, double InitMinTime, double NuclMaxTime, double NuclMinTime, double CaptureMaxTime, double CaptureMinTime, double GhostMaxTime, double GhostMinTime, double OutMaxTime, double OutMinTime); void PrintCAFields(int nx, int ny, int nz, ViewI3D_H GrainID_WholeDomain, ViewI3D_H LayerID_WholeDomain, ViewI3D_H CritTimeStep_WholeDomain, ViewI3D_H CellType_WholeDomain, ViewF3D_H UndercoolingChange_WholeDomain, ViewF3D_H UndercoolingCurrent_WholeDomain, ViewI3D_H Melted_WholeDomain, std::string PathToOutput, std::string BaseFileName, int PrintDebug, bool PrintFullOutput); void PrintGrainMisorientations(std::string BaseFileName, std::string PathToOutput, int nx, int ny, int nz, ViewI3D_H Melted_WholeDomain, ViewI3D_H GrainID_WholeDomain, ViewI_H GrainOrientation, ViewF_H GrainUnitVector, int NGrainOrientations); #endif
//===- MCJITObjectCacheTest.cpp - Unit tests for MCJIT object caching -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCJITTestBase.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/ExecutionEngine/MCJIT.h" #include "llvm/ExecutionEngine/ObjectCache.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "gtest/gtest.h" using namespace llvm; namespace { class TestObjectCache : public ObjectCache { public: TestObjectCache() : DuplicateInserted(false) { } void notifyObjectCompiled(const Module *M, MemoryBufferRef Obj) override { // If we've seen this module before, note that. const std::string ModuleID = M->getModuleIdentifier(); if (ObjMap.find(ModuleID) != ObjMap.end()) DuplicateInserted = true; // Store a copy of the buffer in our map. ObjMap[ModuleID] = copyBuffer(Obj); } std::unique_ptr<MemoryBuffer> getObject(const Module *M) override { const MemoryBuffer* BufferFound = getObjectInternal(M); ModulesLookedUp.insert(M->getModuleIdentifier()); if (!BufferFound) return nullptr; // Our test cache wants to maintain ownership of its object buffers // so we make a copy here for the execution engine. return MemoryBuffer::getMemBufferCopy(BufferFound->getBuffer()); } // Test-harness-specific functions bool wereDuplicatesInserted() { return DuplicateInserted; } bool wasModuleLookedUp(const Module *M) { return ModulesLookedUp.find(M->getModuleIdentifier()) != ModulesLookedUp.end(); } const MemoryBuffer* getObjectInternal(const Module* M) { // Look for the module in our map. const std::string ModuleID = M->getModuleIdentifier(); StringMap<const MemoryBuffer *>::iterator it = ObjMap.find(ModuleID); if (it == ObjMap.end()) return nullptr; return it->second; } private: MemoryBuffer *copyBuffer(MemoryBufferRef Buf) { // Create a local copy of the buffer. std::unique_ptr<MemoryBuffer> NewBuffer = MemoryBuffer::getMemBufferCopy(Buf.getBuffer()); MemoryBuffer *Ret = NewBuffer.get(); AllocatedBuffers.push_back(std::move(NewBuffer)); return Ret; } StringMap<const MemoryBuffer *> ObjMap; StringSet<> ModulesLookedUp; SmallVector<std::unique_ptr<MemoryBuffer>, 2> AllocatedBuffers; bool DuplicateInserted; }; class MCJITObjectCacheTest : public testing::Test, public MCJITTestBase { protected: enum { OriginalRC = 6, ReplacementRC = 7 }; void SetUp() override { M.reset(createEmptyModule("<main>")); Main = insertMainFunction(M.get(), OriginalRC); } void compileAndRun(int ExpectedRC = OriginalRC) { // This function shouldn't be called until after SetUp. ASSERT_TRUE(bool(TheJIT)); ASSERT_TRUE(nullptr != Main); // We may be using a null cache, so ensure compilation is valid. TheJIT->finalizeObject(); void *vPtr = TheJIT->getPointerToFunction(Main); EXPECT_TRUE(nullptr != vPtr) << "Unable to get pointer to main() from JIT"; int (*FuncPtr)(void) = (int(*)(void))(intptr_t)vPtr; int returnCode = FuncPtr(); EXPECT_EQ(returnCode, ExpectedRC); } Function *Main; }; TEST_F(MCJITObjectCacheTest, SetNullObjectCache) { SKIP_UNSUPPORTED_PLATFORM; createJIT(std::move(M)); TheJIT->setObjectCache(nullptr); compileAndRun(); } TEST_F(MCJITObjectCacheTest, VerifyBasicObjectCaching) { SKIP_UNSUPPORTED_PLATFORM; std::unique_ptr<TestObjectCache> Cache(new TestObjectCache); // Save a copy of the module pointer before handing it off to MCJIT. const Module * SavedModulePointer = M.get(); createJIT(std::move(M)); TheJIT->setObjectCache(Cache.get()); // Verify that our object cache does not contain the module yet. const MemoryBuffer *ObjBuffer = Cache->getObjectInternal(SavedModulePointer); EXPECT_EQ(nullptr, ObjBuffer); compileAndRun(); // Verify that MCJIT tried to look-up this module in the cache. EXPECT_TRUE(Cache->wasModuleLookedUp(SavedModulePointer)); // Verify that our object cache now contains the module. ObjBuffer = Cache->getObjectInternal(SavedModulePointer); EXPECT_TRUE(nullptr != ObjBuffer); // Verify that the cache was only notified once. EXPECT_FALSE(Cache->wereDuplicatesInserted()); } TEST_F(MCJITObjectCacheTest, VerifyLoadFromCache) { SKIP_UNSUPPORTED_PLATFORM; std::unique_ptr<TestObjectCache> Cache(new TestObjectCache); // Compile this module with an MCJIT engine createJIT(std::move(M)); TheJIT->setObjectCache(Cache.get()); TheJIT->finalizeObject(); // Destroy the MCJIT engine we just used TheJIT.reset(); // Create a new memory manager. MM.reset(new SectionMemoryManager()); // Create a new module and save it. Use a different return code so we can // tell if MCJIT compiled this module or used the cache. M.reset(createEmptyModule("<main>")); Main = insertMainFunction(M.get(), ReplacementRC); const Module * SecondModulePointer = M.get(); // Create a new MCJIT instance to load this module then execute it. createJIT(std::move(M)); TheJIT->setObjectCache(Cache.get()); compileAndRun(); // Verify that MCJIT tried to look-up this module in the cache. EXPECT_TRUE(Cache->wasModuleLookedUp(SecondModulePointer)); // Verify that MCJIT didn't try to cache this again. EXPECT_FALSE(Cache->wereDuplicatesInserted()); } TEST_F(MCJITObjectCacheTest, VerifyNonLoadFromCache) { SKIP_UNSUPPORTED_PLATFORM; std::unique_ptr<TestObjectCache> Cache(new TestObjectCache); // Compile this module with an MCJIT engine createJIT(std::move(M)); TheJIT->setObjectCache(Cache.get()); TheJIT->finalizeObject(); // Destroy the MCJIT engine we just used TheJIT.reset(); // Create a new memory manager. MM.reset(new SectionMemoryManager()); // Create a new module and save it. Use a different return code so we can // tell if MCJIT compiled this module or used the cache. Note that we use // a new module name here so the module shouldn't be found in the cache. M.reset(createEmptyModule("<not-main>")); Main = insertMainFunction(M.get(), ReplacementRC); const Module * SecondModulePointer = M.get(); // Create a new MCJIT instance to load this module then execute it. createJIT(std::move(M)); TheJIT->setObjectCache(Cache.get()); // Verify that our object cache does not contain the module yet. const MemoryBuffer *ObjBuffer = Cache->getObjectInternal(SecondModulePointer); EXPECT_EQ(nullptr, ObjBuffer); // Run the function and look for the replacement return code. compileAndRun(ReplacementRC); // Verify that MCJIT tried to look-up this module in the cache. EXPECT_TRUE(Cache->wasModuleLookedUp(SecondModulePointer)); // Verify that our object cache now contains the module. ObjBuffer = Cache->getObjectInternal(SecondModulePointer); EXPECT_TRUE(nullptr != ObjBuffer); // Verify that MCJIT didn't try to cache this again. EXPECT_FALSE(Cache->wereDuplicatesInserted()); } } // Namespace
// This file is part of snark, a generic and flexible library for robotics research // Copyright (c) 2011 The University of Sydney // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the University of Sydney nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT // HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN // IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cmath> #include <vector> #include <boost/array.hpp> #include <boost/filesystem/operations.hpp> #include <boost/lexical_cast.hpp> #include <comma/math/compare.h> #include "Viewer.h" namespace snark { namespace graphics { namespace View { Viewer::Viewer( const std::vector< comma::csv::options >& options , const comma::csv::options& csv_out , bool labelDuplicated , const QColor4ub& background_color , bool orthographic , double fieldOfView , bool verbose ) : qt3d::view( background_color, fieldOfView, false, orthographic ) , navigate( *this ) , pickId( *this ) , selectPartition( *this ) , selectId( *this ) , selectClip( *this ) , fill( *this ) , m_currentTool( &navigate ) , m_options( options ) , output_with_id( csv_out.has_field( "id" ) ) , m_output_stream( std::cout, csv_out ) , m_labelDuplicated( labelDuplicated ) , verbose_( verbose ) { // quick and dirty, since otherwise dataset construction throws on a separate thread on non-existing file and then segfaults on exit for( std::size_t i = 0; i < m_options.size(); ++i ) { if( !boost::filesystem::exists( m_options[i].filename ) ) { COMMA_THROW( comma::exception, "file " << m_options[i].filename << " does not exist" ); } } } void Viewer::saveStateToFile() {} void Viewer::show( std::size_t i, bool visible ) { m_datasets[i]->visible( visible ); update(); } void Viewer::setWritable( std::size_t i, bool writable ) { m_datasets[i]->writable( writable ); } void Viewer::save() { for( std::size_t i = 0; i < m_datasets.size(); ++i ) { if( m_datasets[i]->writable() ) { m_datasets[i]->save(); } } } const std::vector< boost::shared_ptr< Dataset > >& Viewer::datasets() const { return m_datasets; } Dataset& Viewer::dataset( std::size_t index ) { return *m_datasets[index]; } const Dataset& Viewer::dataset( std::size_t index ) const { return *m_datasets[index]; } void Viewer::reload() { for( std::size_t i = 0; i < m_datasets.size(); ++i ) { std::string filename = m_datasets[i]->filename(); comma::csv::options options = m_datasets[i]->options(); bool writable = m_datasets[i]->writable(); bool visible = m_datasets[i]->visible(); m_datasets[i].reset(); m_datasets[i].reset( new Dataset( filename, options, *m_offset, m_labelDuplicated ) ); if( !m_datasets[i]->valid() ) { std::cerr << "label-points: failed to reload datasets" << std::endl; exit( -1 ); } m_datasets[i]->init(); m_datasets[i]->writable( writable ); m_datasets[i]->visible( visible ); } setCamera(); update(); } void Viewer::setCamera() { assert( !m_datasets.empty() ); snark::math::closed_interval< double, 3 > extents = m_datasets[0]->extents(); for( std::size_t i = 0; i < m_datasets.size(); ++i ) { extents = extents.hull( m_datasets[i]->extents() ); } extents = extents.hull( extents.min() - Eigen::Vector3d( 10, 10, 10 ) ); // expand a bit extents = extents.hull( extents.max() + Eigen::Vector3d( 10, 10, 10 ) ); // expand a bit Eigen::Vector3d minCorner = extents.min() - m_datasets[0]->offset(); Eigen::Vector3d maxCorner = extents.max() - m_datasets[0]->offset(); QVector3D min( minCorner.x(), minCorner.y(), minCorner.z() ); QVector3D max( maxCorner.x(), maxCorner.y(), maxCorner.z() ); updateView( min, max ); lookAtCenter(); updateZFar(); } void Viewer::initializeGL( QGLPainter *painter ) { ::glDisable( GL_LIGHTING ); // setBackgroundColor( QColor( m_background_color.red(), m_background_color.green(), m_background_color.blue() ) ); m_datasets.push_back( boost::shared_ptr< Dataset >( new Dataset( m_options[0].filename, m_options[0], m_labelDuplicated ) ) ); if( !m_datasets[0]->valid() ) { std::cerr << "label-points: failed to load dataset " << m_options[0].filename << std::endl; exit( -1 ); } m_datasets[0]->init(); m_datasets[0]->writable( true ); m_datasets[0]->visible( true ); m_offset = m_datasets[0]->offset(); for( std::size_t i = 1; i < m_options.size(); ++i ) { m_datasets.push_back( boost::shared_ptr< Dataset >( new Dataset( m_options[i].filename, m_options[i], *m_offset, m_labelDuplicated ) ) ); if( !m_datasets.back()->valid() ) { std::cerr << "label-points: failed to load dataset " << m_options[i].filename << std::endl; exit( -1 ); } m_datasets.back()->init(); m_datasets.back()->writable( false ); m_datasets.back()->visible( true ); } setCamera(); } void Viewer::paintGL( QGLPainter *painter ) { updateZFar(); static bool emitted = false; if( !emitted ) { emitted = true; emit initialized(); } // real quick and dirty: somehow emit fails in init() ::glPointSize( 1 ); int selectionPointSize = 1; for( std::size_t i = 0; i < m_datasets.size(); ++i ) { m_datasets[i]->draw( painter ); if( m_datasets[i]->visible() ) { selectionPointSize = 3; } } ::glEnable( GL_POINT_SMOOTH ); ::glPointSize( selectionPointSize ); for( std::size_t i = 0; i < m_datasets.size(); ++i ) { m_datasets[i]->selection().draw( painter ); } ::glDisable( GL_POINT_SMOOTH ); m_currentTool->draw( painter ); draw_coordinates( painter ); } void Viewer::mousePressEvent( QMouseEvent* e ) { m_currentTool->onMousePress( e ); // GL::View::mousePressEvent( e ); } void Viewer::mouseReleaseEvent( QMouseEvent* e ) { m_currentTool->onMouseRelease( e ); // GL::View::mouseReleaseEvent( e ); } void Viewer::mouseMoveEvent( QMouseEvent *e ) { m_currentTool->onMouseMove( e ); // GL::View::mouseMoveEvent( e ); } boost::optional< point_and_id > Viewer::pointSelection( const QPoint& point, bool writableOnly ) { boost::optional< point_and_id > result; boost::optional< QVector3D > point3d = getPoint( point ); if( point3d ) { Eigen::Vector3d p( point3d->x(), point3d->y(), point3d->z() ); if( m_offset ) { p += *m_offset; } if( !output_with_id ) { m_output_stream.write( PointWithId( p ) ); } std::cerr << " clicked point " << std::setprecision( 12 ) << p.transpose() << std::endl; snark::math::closed_interval< double, 3 > e( p - Eigen::Vector3d::Ones(), p + Eigen::Vector3d::Ones() ); double minDistanceSquare = std::numeric_limits< double >::max(); for( std::size_t i = 0; i < m_datasets.size(); ++i ) { if( !m_datasets[i]->visible() || ( writableOnly && !m_datasets[i]->writable() ) ) { continue; } Dataset::Points m = m_datasets[i]->points().find( e.min(), e.max() ); if( verbose_ ) { std::cerr << " found " << m.size() << " point(s) in the neighbourhood" << std::endl; } for( Dataset::Points::ConstEnumerator en = m.begin(); !en.end(); ++en ) { double squared_norm = ( en.key() - p ).squaredNorm(); if( squared_norm < minDistanceSquare ) { minDistanceSquare = squared_norm; result = std::make_pair( en.key(), en.value().id ); } } if( minDistanceSquare <= 0.01 ) { if( output_with_id ) { m_output_stream.write( PointWithId( *result ) ); } if( verbose_ ) { std::cerr << " found point: " << std::setprecision( 12 ) << result->first.transpose() << "; id: " << result->second << std::endl; } return result; } } } return boost::optional< point_and_id >(); } void Viewer::handleId( comma::uint32 id ) { m_id = id; } } } } // namespace snark { namespace graphics { namespace View {
// (C) Copyright Gennadiy Rozental 2001-2005. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile: test_exec_monitor.hpp,v $ // // Version : $Revision: 1.15 $ // // Description : included (vs. linked) version of Test Execution Monitor // *************************************************************************** #ifndef BOOST_INCLUDED_TEST_EXEC_MONITOR_HPP_071894GER #define BOOST_INCLUDED_TEST_EXEC_MONITOR_HPP_071894GER #include <boost/test/impl/compiler_log_formatter.ipp> #include <boost/test/impl/execution_monitor.ipp> #include <boost/test/impl/framework.ipp> #include <boost/test/impl/plain_report_formatter.ipp> #include <boost/test/impl/progress_monitor.ipp> #include <boost/test/impl/results_collector.ipp> #include <boost/test/impl/results_reporter.ipp> #include <boost/test/impl/test_main.ipp> #include <boost/test/impl/test_tools.ipp> #include <boost/test/impl/unit_test_log.ipp> #include <boost/test/impl/unit_test_main.ipp> #include <boost/test/impl/unit_test_monitor.ipp> #include <boost/test/impl/unit_test_parameters.ipp> #include <boost/test/impl/unit_test_suite.ipp> #include <boost/test/impl/xml_log_formatter.ipp> #include <boost/test/impl/xml_report_formatter.ipp> #define BOOST_TEST_INCLUDED #include <boost/test/test_exec_monitor.hpp> // *************************************************************************** // Revision History : // // $Log: test_exec_monitor.hpp,v $ // Revision 1.15 2006/02/06 10:01:55 rogeeff // m,ake name similar to the primary header name // // Revision 1.14 2006/02/01 07:57:49 rogeeff // included components entry points // // Revision 1.13 2005/02/20 08:27:08 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // Revision 1.12 2005/02/01 08:59:38 rogeeff // supplied_log_formatters split // change formatters interface to simplify result interface // // Revision 1.11 2005/02/01 06:40:07 rogeeff // copyright update // old log entries removed // minor stilistic changes // depricated tools removed // // Revision 1.10 2005/01/22 19:22:13 rogeeff // implementation moved into headers section to eliminate dependency of included/minimal component on src directory // // *************************************************************************** #endif // BOOST_INCLUDED_TEST_EXEC_MONITOR_HPP_071894GER
#include<bits/stdc++.h> #define rec(i,x) for(int i=0;i<x;i++) #define MAXN 200005 #define INF 0x3f3f3f3f #define LL long long #define ll long long #define P pair<double,int> using namespace std; template<typename TI> struct BitOp{ //返回:反转pos开始,往右长度为len的区域 inline TI flip(TI op,size_t pos,size_t len=1){return op^(((1<<len)-1)<<pos);} //修改op:将pos开始,长度为len区域的值,设成v的二进制表示形式 inline TI& set(TI& op,size_t pos,int v,size_t len=1){ int o = ((1<<len)-1); return op = (op&(~(o<<pos)))|((v&o)<<pos); } //返回:从pos开始,长度为len的区域 inline int get(TI op,size_t pos, size_t len=1){return (op>>pos)&((1<<len)-1);} //输出二进制,例子:bo.outBits(cout,5); ostream& outBits(ostream& os, TI i){ if(i)outBits(os,(i>>1))<<(i&1); return os; } }; BitOp<int> bo; int main(){ int a=1; bo.outBits(cout,5); return 0; }
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Direbear_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function DinoCharacterStatusComponent_BP_Direbear.DinoCharacterStatusComponent_BP_Direbear_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Direbear // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UDinoCharacterStatusComponent_BP_Direbear_C::ExecuteUbergraph_DinoCharacterStatusComponent_BP_Direbear(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function DinoCharacterStatusComponent_BP_Direbear.DinoCharacterStatusComponent_BP_Direbear_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Direbear"); UDinoCharacterStatusComponent_BP_Direbear_C_ExecuteUbergraph_DinoCharacterStatusComponent_BP_Direbear_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
/* * TLogServer.actor.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project 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 "flow/Hash3.h" #include "flow/UnitTest.h" #include "fdbclient/NativeAPI.actor.h" #include "fdbclient/Notified.h" #include "fdbclient/KeyRangeMap.h" #include "fdbclient/RunTransaction.actor.h" #include "fdbclient/SystemData.h" #include "fdbclient/FDBTypes.h" #include "fdbserver/WorkerInterface.actor.h" #include "fdbserver/LogProtocolMessage.h" #include "fdbserver/SpanContextMessage.h" #include "fdbserver/TLogInterface.h" #include "fdbserver/Knobs.h" #include "fdbserver/IKeyValueStore.h" #include "fdbserver/MutationTracking.h" #include "flow/ActorCollection.h" #include "fdbrpc/FailureMonitor.h" #include "fdbserver/IDiskQueue.h" #include "fdbrpc/sim_validation.h" #include "fdbrpc/simulator.h" #include "fdbrpc/Stats.h" #include "fdbserver/ServerDBInfo.h" #include "fdbserver/LogSystem.h" #include "fdbserver/WaitFailure.h" #include "fdbserver/RecoveryState.h" #include "fdbserver/FDBExecHelper.actor.h" #include "flow/Histogram.h" #include "flow/actorcompiler.h" // This must be the last #include. using std::make_pair; using std::max; using std::min; using std::pair; struct TLogQueueEntryRef { UID id; Version version; Version knownCommittedVersion; StringRef messages; TLogQueueEntryRef() : version(0), knownCommittedVersion(0) {} TLogQueueEntryRef(Arena& a, TLogQueueEntryRef const& from) : version(from.version), knownCommittedVersion(from.knownCommittedVersion), id(from.id), messages(a, from.messages) {} // To change this serialization, ProtocolVersion::TLogQueueEntryRef must be updated, and downgrades need to be // considered template <class Ar> void serialize(Ar& ar) { serializer(ar, version, messages, knownCommittedVersion, id); } size_t expectedSize() const { return messages.expectedSize(); } }; struct AlternativeTLogQueueEntryRef { UID id; Version version; Version knownCommittedVersion; std::vector<TagsAndMessage>* alternativeMessages; AlternativeTLogQueueEntryRef() : version(0), knownCommittedVersion(0), alternativeMessages(nullptr) {} template <class Ar> void serialize(Ar& ar) { ASSERT(!ar.isDeserializing && alternativeMessages); uint32_t msgSize = expectedSize(); serializer(ar, version, msgSize); for (auto& msg : *alternativeMessages) { ar.serializeBytes(msg.message); } serializer(ar, knownCommittedVersion, id); } uint32_t expectedSize() const { uint32_t msgSize = 0; for (auto& msg : *alternativeMessages) { msgSize += msg.message.size(); } return msgSize; } }; typedef Standalone<TLogQueueEntryRef> TLogQueueEntry; struct LogData; struct TLogData; struct TLogQueue final : public IClosable { public: TLogQueue(IDiskQueue* queue, UID dbgid) : queue(queue), dbgid(dbgid) {} // Each packet in the queue is // uint32_t payloadSize // uint8_t payload[payloadSize] (begins with uint64_t protocolVersion via IncludeVersion) // uint8_t validFlag // TLogQueue is a durable queue of TLogQueueEntry objects with an interface similar to IDiskQueue // TLogQueue pushes (but not commits) are atomic - after commit fails to return, a prefix of entire calls to push // are durable. This is // implemented on top of the weaker guarantee of IDiskQueue::commit (that a prefix of bytes is durable) using // validFlag and by padding any incomplete packet with zeros after recovery. // Before calling push, pop, or commit, the user must call readNext() until it throws // end_of_stream(). It may not be called again thereafter. Future<TLogQueueEntry> readNext(TLogData* tLog) { return readNext(this, tLog); } Future<bool> initializeRecovery(IDiskQueue::location recoverAt) { return queue->initializeRecovery(recoverAt); } template <class T> void push(T const& qe, Reference<LogData> logData); void forgetBefore(Version upToVersion, Reference<LogData> logData); void pop(IDiskQueue::location upToLocation); Future<Void> commit() { return queue->commit(); } // Implements IClosable Future<Void> getError() override { return queue->getError(); } Future<Void> onClosed() override { return queue->onClosed(); } void dispose() override { queue->dispose(); delete this; } void close() override { queue->close(); delete this; } private: IDiskQueue* queue; UID dbgid; void updateVersionSizes(const TLogQueueEntry& result, TLogData* tLog, IDiskQueue::location start, IDiskQueue::location end); ACTOR static Future<TLogQueueEntry> readNext(TLogQueue* self, TLogData* tLog) { state TLogQueueEntry result; state int zeroFillSize = 0; loop { state IDiskQueue::location startloc = self->queue->getNextReadLocation(); Standalone<StringRef> h = wait(self->queue->readNext(sizeof(uint32_t))); if (h.size() != sizeof(uint32_t)) { if (h.size()) { TEST(true); // Zero fill within size field int payloadSize = 0; memcpy(&payloadSize, h.begin(), h.size()); zeroFillSize = sizeof(uint32_t) - h.size(); // zero fill the size itself zeroFillSize += payloadSize + 1; // and then the contents and valid flag } break; } state uint32_t payloadSize = *(uint32_t*)h.begin(); ASSERT(payloadSize < (100 << 20)); Standalone<StringRef> e = wait(self->queue->readNext(payloadSize + 1)); if (e.size() != payloadSize + 1) { TEST(true); // Zero fill within payload zeroFillSize = payloadSize + 1 - e.size(); break; } if (e[payloadSize]) { ASSERT(e[payloadSize] == 1); Arena a = e.arena(); ArenaReader ar(a, e.substr(0, payloadSize), IncludeVersion()); ar >> result; const IDiskQueue::location endloc = self->queue->getNextReadLocation(); self->updateVersionSizes(result, tLog, startloc, endloc); return result; } } if (zeroFillSize) { TEST(true); // Fixing a partial commit at the end of the tlog queue for (int i = 0; i < zeroFillSize; i++) self->queue->push(StringRef((const uint8_t*)"", 1)); } throw end_of_stream(); } }; ////// Persistence format (for self->persistentData) // Immutable keys // persistFormat has been mostly invalidated by TLogVersion, and can probably be removed when // 4.6's TLog code is removed. static const KeyValueRef persistFormat(LiteralStringRef("Format"), LiteralStringRef("FoundationDB/LogServer/3/0")); static const KeyRangeRef persistFormatReadableRange(LiteralStringRef("FoundationDB/LogServer/3/0"), LiteralStringRef("FoundationDB/LogServer/4/0")); static const KeyRangeRef persistProtocolVersionKeys(LiteralStringRef("ProtocolVersion/"), LiteralStringRef("ProtocolVersion0")); static const KeyRangeRef persistTLogSpillTypeKeys(LiteralStringRef("TLogSpillType/"), LiteralStringRef("TLogSpillType0")); static const KeyRangeRef persistRecoveryCountKeys = KeyRangeRef(LiteralStringRef("DbRecoveryCount/"), LiteralStringRef("DbRecoveryCount0")); // Updated on updatePersistentData() static const KeyRangeRef persistCurrentVersionKeys = KeyRangeRef(LiteralStringRef("version/"), LiteralStringRef("version0")); static const KeyRangeRef persistKnownCommittedVersionKeys = KeyRangeRef(LiteralStringRef("knownCommitted/"), LiteralStringRef("knownCommitted0")); static const KeyRef persistRecoveryLocationKey = KeyRef(LiteralStringRef("recoveryLocation")); static const KeyRangeRef persistLocalityKeys = KeyRangeRef(LiteralStringRef("Locality/"), LiteralStringRef("Locality0")); static const KeyRangeRef persistLogRouterTagsKeys = KeyRangeRef(LiteralStringRef("LogRouterTags/"), LiteralStringRef("LogRouterTags0")); static const KeyRangeRef persistTxsTagsKeys = KeyRangeRef(LiteralStringRef("TxsTags/"), LiteralStringRef("TxsTags0")); static const KeyRange persistTagMessagesKeys = prefixRange(LiteralStringRef("TagMsg/")); static const KeyRange persistTagMessageRefsKeys = prefixRange(LiteralStringRef("TagMsgRef/")); static const KeyRange persistTagPoppedKeys = prefixRange(LiteralStringRef("TagPop/")); static Key persistTagMessagesKey(UID id, Tag tag, Version version) { BinaryWriter wr(Unversioned()); wr.serializeBytes(persistTagMessagesKeys.begin); wr << id; wr << tag; wr << bigEndian64(version); return wr.toValue(); } static Key persistTagMessageRefsKey(UID id, Tag tag, Version version) { BinaryWriter wr(Unversioned()); wr.serializeBytes(persistTagMessageRefsKeys.begin); wr << id; wr << tag; wr << bigEndian64(version); return wr.toValue(); } static Key persistTagPoppedKey(UID id, Tag tag) { BinaryWriter wr(Unversioned()); wr.serializeBytes(persistTagPoppedKeys.begin); wr << id; wr << tag; return wr.toValue(); } static Value persistTagPoppedValue(Version popped) { return BinaryWriter::toValue(popped, Unversioned()); } static Tag decodeTagPoppedKey(KeyRef id, KeyRef key) { Tag s; BinaryReader rd(key.removePrefix(persistTagPoppedKeys.begin).removePrefix(id), Unversioned()); rd >> s; return s; } static Version decodeTagPoppedValue(ValueRef value) { return BinaryReader::fromStringRef<Version>(value, Unversioned()); } static StringRef stripTagMessagesKey(StringRef key) { return key.substr(sizeof(UID) + sizeof(Tag) + persistTagMessagesKeys.begin.size()); } static Version decodeTagMessagesKey(StringRef key) { return bigEndian64(BinaryReader::fromStringRef<Version>(stripTagMessagesKey(key), Unversioned())); } struct SpilledData { SpilledData() = default; SpilledData(Version version, IDiskQueue::location start, uint32_t length, uint32_t mutationBytes) : version(version), start(start), length(length), mutationBytes(mutationBytes) {} template <class Ar> void serialize(Ar& ar) { serializer(ar, version, start, length, mutationBytes); } Version version = 0; IDiskQueue::location start = 0; uint32_t length = 0; uint32_t mutationBytes = 0; }; struct TLogData : NonCopyable { AsyncTrigger newLogData; // A process has only 1 SharedTLog, which holds data for multiple logs, so that it obeys its assigned memory limit. // A process has only 1 active log and multiple non-active log from old generations. // In the figure below, TLog [1-4] are logs from old generations. // Because SS may need to pull data from old generation log, we keep Tlog [1-4]. // // We always pop the disk queue from the oldest TLog, spill from the oldest TLog that still has // data in memory, and commits to the disk queue come from the most recent TLog. // // SharedTLog // +--------+--------+--------+--------+--------+ // | TLog 1 | TLog 2 | TLog 3 | TLog 4 | TLog 5 | // +--------+--------+--------+--------+--------+ // ^ popOrder ^spillOrder ^committing // // ^popOrder is the location where SS reads the to-be-read data from tlog. // ^committing is the location where the active TLog accepts the pushed data. Deque<UID> popOrder; Deque<UID> spillOrder; std::map<UID, Reference<struct LogData>> id_data; UID dbgid; UID workerID; IKeyValueStore* persistentData; // Durable data on disk that were spilled. IDiskQueue* rawPersistentQueue; // The physical queue the persistentQueue below stores its data. Ideally, log // interface should work without directly accessing rawPersistentQueue TLogQueue* persistentQueue; // Logical queue the log operates on and persist its data. int64_t diskQueueCommitBytes; AsyncVar<bool> largeDiskQueueCommitBytes; // becomes true when diskQueueCommitBytes is greater than MAX_QUEUE_COMMIT_BYTES Reference<AsyncVar<ServerDBInfo> const> dbInfo; Database cx; NotifiedVersion queueCommitEnd; Version queueCommitBegin; int64_t instanceID; int64_t bytesInput; int64_t bytesDurable; int64_t targetVolatileBytes; // The number of bytes of mutations this TLog should hold in memory before spilling. int64_t overheadBytesInput; int64_t overheadBytesDurable; WorkerCache<TLogInterface> tlogCache; FlowLock peekMemoryLimiter; PromiseStream<Future<Void>> sharedActors; Promise<Void> terminated; FlowLock concurrentLogRouterReads; FlowLock persistentDataCommitLock; // Beginning of fields used by snapshot based backup and restore bool ignorePopRequest; // ignore pop request from storage servers double ignorePopDeadline; // time until which the ignorePopRequest will be // honored std::string ignorePopUid; // callers that set ignorePopRequest will set this // extra state, used to validate the ownership of // the set and for callers that unset will // be able to match it up std::string dataFolder; // folder where data is stored std::map<Tag, Version> toBePopped; // map of Tag->Version for all the pops // that came when ignorePopRequest was set Reference<AsyncVar<bool>> degraded; // End of fields used by snapshot based backup and restore std::vector<TagsAndMessage> tempTagMessages; Reference<Histogram> commitLatencyDist; TLogData(UID dbgid, UID workerID, IKeyValueStore* persistentData, IDiskQueue* persistentQueue, Reference<AsyncVar<ServerDBInfo> const> dbInfo, Reference<AsyncVar<bool>> degraded, std::string folder) : dbgid(dbgid), workerID(workerID), instanceID(deterministicRandom()->randomUniqueID().first()), persistentData(persistentData), rawPersistentQueue(persistentQueue), persistentQueue(new TLogQueue(persistentQueue, dbgid)), dbInfo(dbInfo), degraded(degraded), queueCommitBegin(0), queueCommitEnd(0), diskQueueCommitBytes(0), largeDiskQueueCommitBytes(false), bytesInput(0), bytesDurable(0), targetVolatileBytes(SERVER_KNOBS->TLOG_SPILL_THRESHOLD), overheadBytesInput(0), overheadBytesDurable(0), peekMemoryLimiter(SERVER_KNOBS->TLOG_SPILL_REFERENCE_MAX_PEEK_MEMORY_BYTES), concurrentLogRouterReads(SERVER_KNOBS->CONCURRENT_LOG_ROUTER_READS), ignorePopRequest(false), ignorePopDeadline(), ignorePopUid(), dataFolder(folder), toBePopped(), commitLatencyDist(Histogram::getHistogram(LiteralStringRef("tLog"), LiteralStringRef("commit"), Histogram::Unit::microseconds)) { cx = openDBOnServer(dbInfo, TaskPriority::DefaultEndpoint, LockAware::True); } }; struct LogData : NonCopyable, public ReferenceCounted<LogData> { struct TagData : NonCopyable, public ReferenceCounted<TagData> { std::deque<std::pair<Version, LengthPrefixedStringRef>> versionMessages; bool nothingPersistent; // true means tag is *known* to have no messages in persistentData. false means nothing. bool poppedRecently; // `popped` has changed since last updatePersistentData Version popped; // see popped version tracking contract below Version persistentPopped; // The popped version recorded in the btree. Version versionForPoppedLocation; // `poppedLocation` was calculated at this popped version IDiskQueue::location poppedLocation; // The location of the earliest commit with data for this tag. bool unpoppedRecovered; Tag tag; TagData(Tag tag, Version popped, IDiskQueue::location poppedLocation, bool nothingPersistent, bool poppedRecently, bool unpoppedRecovered) : tag(tag), nothingPersistent(nothingPersistent), poppedRecently(poppedRecently), popped(popped), persistentPopped(0), versionForPoppedLocation(0), poppedLocation(poppedLocation), unpoppedRecovered(unpoppedRecovered) {} TagData(TagData&& r) noexcept : versionMessages(std::move(r.versionMessages)), nothingPersistent(r.nothingPersistent), poppedRecently(r.poppedRecently), popped(r.popped), persistentPopped(r.persistentPopped), versionForPoppedLocation(r.versionForPoppedLocation), poppedLocation(r.poppedLocation), tag(r.tag), unpoppedRecovered(r.unpoppedRecovered) {} void operator=(TagData&& r) noexcept { versionMessages = std::move(r.versionMessages); nothingPersistent = r.nothingPersistent; poppedRecently = r.poppedRecently; popped = r.popped; persistentPopped = r.persistentPopped; versionForPoppedLocation = r.versionForPoppedLocation; poppedLocation = r.poppedLocation; tag = r.tag; unpoppedRecovered = r.unpoppedRecovered; } // Erase messages not needed to update *from* versions >= before (thus, messages with toversion <= before) ACTOR Future<Void> eraseMessagesBefore(TagData* self, Version before, TLogData* tlogData, Reference<LogData> logData, TaskPriority taskID) { while (!self->versionMessages.empty() && self->versionMessages.front().first < before) { Version version = self->versionMessages.front().first; std::pair<int, int>& sizes = logData->version_sizes[version]; int64_t messagesErased = 0; while (!self->versionMessages.empty() && self->versionMessages.front().first == version) { auto const& m = self->versionMessages.front(); ++messagesErased; if (self->tag.locality != tagLocalityTxs && self->tag != txsTag) { sizes.first -= m.second.expectedSize(); } else { sizes.second -= m.second.expectedSize(); } self->versionMessages.pop_front(); } int64_t bytesErased = messagesErased * SERVER_KNOBS->VERSION_MESSAGES_ENTRY_BYTES_WITH_OVERHEAD; logData->bytesDurable += bytesErased; tlogData->bytesDurable += bytesErased; tlogData->overheadBytesDurable += bytesErased; wait(yield(taskID)); } return Void(); } Future<Void> eraseMessagesBefore(Version before, TLogData* tlogData, Reference<LogData> logData, TaskPriority taskID) { return eraseMessagesBefore(this, before, tlogData, logData, taskID); } }; Map<Version, std::pair<IDiskQueue::location, IDiskQueue::location>> versionLocation; // For the version of each entry that was push()ed, the [start, end) location of the serialized // bytes /* Popped version tracking contract needed by log system to implement ILogCursor::popped(): - Log server tracks for each (possible) tag a popped_version Impl: TagData::popped (in memory) and persistTagPoppedKeys (in persistentData) - popped_version(tag) is <= the maximum version for which log server (or a predecessor) is ever asked to pop the tag Impl: Only increased by tLogPop() in response to either a pop request or recovery from a predecessor - popped_version(tag) is > the maximum version for which log server is unable to peek messages due to previous pops (on this server or a predecessor) Impl: Increased by tLogPop() atomically with erasing messages from memory; persisted by updatePersistentData() atomically with erasing messages from store; messages are not erased from queue where popped_version is not persisted - LockTLogReply returns all tags which either have messages, or which have nonzero popped_versions Impl: tag_data is present for all such tags - peek(tag, v) returns the popped_version for tag if that is greater than v Impl: Check tag_data->popped (after all waits) */ AsyncTrigger stopCommit; bool stopped, initialized; DBRecoveryCount recoveryCount; // If persistentDataVersion != persistentDurableDataVersion, // then spilling is happening from persistentDurableDataVersion to persistentDataVersion. // Data less than persistentDataDurableVersion is spilled on disk (or fully popped from the TLog); VersionMetricHandle persistentDataVersion, persistentDataDurableVersion; // The last version number in the portion of the log (written|durable) to // persistentData NotifiedVersion version; NotifiedVersion queueCommittedVersion; // The disk queue has committed up until the queueCommittedVersion version. Version queueCommittingVersion; Version knownCommittedVersion; // The maximum version that a proxy has told us that is committed (all TLogs have // ack'd a commit for this version). Version durableKnownCommittedVersion, minKnownCommittedVersion; Version queuePoppedVersion; // The disk queue has been popped up until the location which represents this version. Version minPoppedTagVersion; Tag minPoppedTag; // The tag that makes tLog hold its data and cause tLog's disk queue increasing. Deque<std::pair<Version, Standalone<VectorRef<uint8_t>>>> messageBlocks; std::vector<std::vector<Reference<TagData>>> tag_data; // tag.locality | tag.id int unpoppedRecoveredTags; Reference<TagData> getTagData(Tag tag) { int idx = tag.toTagDataIndex(); if (idx >= tag_data.size()) { tag_data.resize(idx + 1); } if (tag.id >= tag_data[idx].size()) { tag_data[idx].resize(tag.id + 1); } return tag_data[idx][tag.id]; } // only callable after getTagData returns a null reference Reference<TagData> createTagData(Tag tag, Version popped, bool nothingPersistent, bool poppedRecently, bool unpoppedRecovered) { if (tag.locality != tagLocalityLogRouter && tag.locality != tagLocalityTxs && tag != txsTag && allTags.size() && !allTags.count(tag) && popped <= recoveredAt) { popped = recoveredAt + 1; } auto newTagData = makeReference<TagData>(tag, popped, 0, nothingPersistent, poppedRecently, unpoppedRecovered); tag_data[tag.toTagDataIndex()][tag.id] = newTagData; return newTagData; } Map<Version, std::pair<int, int>> version_sizes; CounterCollection cc; Counter bytesInput; Counter bytesDurable; UID logId; ProtocolVersion protocolVersion; Version newPersistentDataVersion; Future<Void> removed; PromiseStream<Future<Void>> addActor; TLogData* tLogData; Promise<Void> recoveryComplete, committingQueue; Version unrecoveredBefore, recoveredAt; struct PeekTrackerData { std::map<int, Promise<std::pair<Version, bool>>> sequence_version; // second: Version is peeked begin version. bool is onlySpilled double lastUpdate; Tag tag; double lastLogged; int64_t totalPeeks; int64_t replyBytes; int64_t duplicatePeeks; double queueTime; double queueMax; double blockTime; double blockMax; double workTime; double workMax; int64_t unblockedPeeks; double idleTime; double idleMax; PeekTrackerData() : lastUpdate(0) { resetMetrics(); } void resetMetrics() { lastLogged = now(); totalPeeks = 0; replyBytes = 0; duplicatePeeks = 0; queueTime = 0; queueMax = 0; blockTime = 0; blockMax = 0; workTime = 0; workMax = 0; unblockedPeeks = 0; idleTime = 0; idleMax = 0; } }; std::map<UID, PeekTrackerData> peekTracker; Reference<AsyncVar<Reference<ILogSystem>>> logSystem; Tag remoteTag; bool isPrimary; int logRouterTags; Version logRouterPoppedVersion, logRouterPopToVersion; int8_t locality; UID recruitmentID; TLogSpillType logSpillType; std::set<Tag> allTags; Future<Void> terminated; FlowLock execOpLock; bool execOpCommitInProgress; int txsTags; explicit LogData(TLogData* tLogData, TLogInterface interf, Tag remoteTag, bool isPrimary, int logRouterTags, int txsTags, UID recruitmentID, ProtocolVersion protocolVersion, TLogSpillType logSpillType, std::vector<Tag> tags, std::string context) : tLogData(tLogData), knownCommittedVersion(0), logId(interf.id()), cc("TLog", interf.id().toString()), bytesInput("BytesInput", cc), bytesDurable("BytesDurable", cc), remoteTag(remoteTag), isPrimary(isPrimary), logRouterTags(logRouterTags), txsTags(txsTags), recruitmentID(recruitmentID), protocolVersion(protocolVersion), logSpillType(logSpillType), logSystem(new AsyncVar<Reference<ILogSystem>>()), logRouterPoppedVersion(0), durableKnownCommittedVersion(0), minKnownCommittedVersion(0), queuePoppedVersion(0), allTags(tags.begin(), tags.end()), terminated(tLogData->terminated.getFuture()), minPoppedTagVersion(0), minPoppedTag(invalidTag), // These are initialized differently on init() or recovery recoveryCount(), stopped(false), initialized(false), queueCommittingVersion(0), newPersistentDataVersion(invalidVersion), unrecoveredBefore(1), recoveredAt(1), unpoppedRecoveredTags(0), logRouterPopToVersion(0), locality(tagLocalityInvalid), execOpCommitInProgress(false) { startRole(Role::TRANSACTION_LOG, interf.id(), tLogData->workerID, { { "SharedTLog", tLogData->dbgid.shortString() } }, context); addActor.send(traceRole(Role::TRANSACTION_LOG, interf.id())); persistentDataVersion.init(LiteralStringRef("TLog.PersistentDataVersion"), cc.id); persistentDataDurableVersion.init(LiteralStringRef("TLog.PersistentDataDurableVersion"), cc.id); version.initMetric(LiteralStringRef("TLog.Version"), cc.id); queueCommittedVersion.initMetric(LiteralStringRef("TLog.QueueCommittedVersion"), cc.id); specialCounter(cc, "Version", [this]() { return this->version.get(); }); specialCounter(cc, "QueueCommittedVersion", [this]() { return this->queueCommittedVersion.get(); }); specialCounter(cc, "PersistentDataVersion", [this]() { return this->persistentDataVersion; }); specialCounter(cc, "PersistentDataDurableVersion", [this]() { return this->persistentDataDurableVersion; }); specialCounter(cc, "KnownCommittedVersion", [this]() { return this->knownCommittedVersion; }); specialCounter(cc, "QueuePoppedVersion", [this]() { return this->queuePoppedVersion; }); specialCounter(cc, "MinPoppedTagVersion", [this]() { return this->minPoppedTagVersion; }); // The locality and id of the tag that is responsible for making the TLog hold onto its oldest piece of data. // If disk queues are growing and no one is sure why, then you shall look at this to find the tag responsible // for why the TLog thinks it can't throw away data. specialCounter(cc, "MinPoppedTagLocality", [this]() { return this->minPoppedTag.locality; }); specialCounter(cc, "MinPoppedTagId", [this]() { return this->minPoppedTag.id; }); specialCounter(cc, "SharedBytesInput", [tLogData]() { return tLogData->bytesInput; }); specialCounter(cc, "SharedBytesDurable", [tLogData]() { return tLogData->bytesDurable; }); specialCounter(cc, "SharedOverheadBytesInput", [tLogData]() { return tLogData->overheadBytesInput; }); specialCounter(cc, "SharedOverheadBytesDurable", [tLogData]() { return tLogData->overheadBytesDurable; }); specialCounter(cc, "PeekMemoryReserved", [tLogData]() { return tLogData->peekMemoryLimiter.activePermits(); }); specialCounter(cc, "PeekMemoryRequestsStalled", [tLogData]() { return tLogData->peekMemoryLimiter.waiters(); }); specialCounter(cc, "Generation", [this]() { return this->recoveryCount; }); } ~LogData() { endRole(Role::TRANSACTION_LOG, logId, "Error", true); if (!terminated.isReady()) { tLogData->bytesDurable += bytesInput.getValue() - bytesDurable.getValue(); TraceEvent("TLogBytesWhenRemoved", logId) .detail("SharedBytesInput", tLogData->bytesInput) .detail("SharedBytesDurable", tLogData->bytesDurable) .detail("LocalBytesInput", bytesInput.getValue()) .detail("LocalBytesDurable", bytesDurable.getValue()); ASSERT_ABORT(tLogData->bytesDurable <= tLogData->bytesInput); Key logIdKey = BinaryWriter::toValue(logId, Unversioned()); tLogData->persistentData->clear(singleKeyRange(logIdKey.withPrefix(persistCurrentVersionKeys.begin))); tLogData->persistentData->clear( singleKeyRange(logIdKey.withPrefix(persistKnownCommittedVersionKeys.begin))); tLogData->persistentData->clear(singleKeyRange(logIdKey.withPrefix(persistLocalityKeys.begin))); tLogData->persistentData->clear(singleKeyRange(logIdKey.withPrefix(persistLogRouterTagsKeys.begin))); tLogData->persistentData->clear(singleKeyRange(logIdKey.withPrefix(persistTxsTagsKeys.begin))); tLogData->persistentData->clear(singleKeyRange(logIdKey.withPrefix(persistRecoveryCountKeys.begin))); tLogData->persistentData->clear(singleKeyRange(logIdKey.withPrefix(persistProtocolVersionKeys.begin))); tLogData->persistentData->clear(singleKeyRange(logIdKey.withPrefix(persistTLogSpillTypeKeys.begin))); tLogData->persistentData->clear(singleKeyRange(logIdKey.withPrefix(persistRecoveryLocationKey))); Key msgKey = logIdKey.withPrefix(persistTagMessagesKeys.begin); tLogData->persistentData->clear(KeyRangeRef(msgKey, strinc(msgKey))); Key msgRefKey = logIdKey.withPrefix(persistTagMessageRefsKeys.begin); tLogData->persistentData->clear(KeyRangeRef(msgRefKey, strinc(msgRefKey))); Key poppedKey = logIdKey.withPrefix(persistTagPoppedKeys.begin); tLogData->persistentData->clear(KeyRangeRef(poppedKey, strinc(poppedKey))); } for (auto it = peekTracker.begin(); it != peekTracker.end(); ++it) { for (auto seq : it->second.sequence_version) { if (!seq.second.isSet()) { seq.second.sendError(timed_out()); } } } } LogEpoch epoch() const { return recoveryCount; } bool shouldSpillByValue(Tag t) const { switch (logSpillType) { case TLogSpillType::VALUE: return true; case TLogSpillType::REFERENCE: return t.locality == tagLocalityTxs || t == txsTag; default: ASSERT(false); return false; } } bool shouldSpillByReference(Tag t) const { return !shouldSpillByValue(t); } }; template <class T> void TLogQueue::push(T const& qe, Reference<LogData> logData) { BinaryWriter wr(Unversioned()); // outer framing is not versioned wr << uint32_t(0); IncludeVersion(ProtocolVersion::withTLogQueueEntryRef()).write(wr); // payload is versioned wr << qe; wr << uint8_t(1); *(uint32_t*)wr.getData() = wr.getLength() - sizeof(uint32_t) - sizeof(uint8_t); const IDiskQueue::location startloc = queue->getNextPushLocation(); // FIXME: push shouldn't return anything. We should call getNextPushLocation() again. const IDiskQueue::location endloc = queue->push(wr.toValue()); //TraceEvent("TLogQueueVersionWritten", dbgid).detail("Size", wr.getLength() - sizeof(uint32_t) - sizeof(uint8_t)).detail("Loc", loc); logData->versionLocation[qe.version] = std::make_pair(startloc, endloc); } void TLogQueue::forgetBefore(Version upToVersion, Reference<LogData> logData) { // Keep only the given and all subsequent version numbers // Find the first version >= upTo auto v = logData->versionLocation.lower_bound(upToVersion); if (v == logData->versionLocation.begin()) return; if (v == logData->versionLocation.end()) { v = logData->versionLocation.lastItem(); } else { v.decrementNonEnd(); } logData->versionLocation.erase(logData->versionLocation.begin(), v); // ... and then we erase that previous version and all prior versions } void TLogQueue::pop(IDiskQueue::location upToLocation) { queue->pop(upToLocation); } void TLogQueue::updateVersionSizes(const TLogQueueEntry& result, TLogData* tLog, IDiskQueue::location start, IDiskQueue::location end) { auto it = tLog->id_data.find(result.id); if (it != tLog->id_data.end()) { it->second->versionLocation[result.version] = std::make_pair(start, end); } } ACTOR Future<Void> tLogLock(TLogData* self, ReplyPromise<TLogLockResult> reply, Reference<LogData> logData) { state Version stopVersion = logData->version.get(); TEST(true); // TLog stopped by recovering master TEST(logData->stopped); // logData already stopped TEST(!logData->stopped); // logData not yet stopped TraceEvent("TLogStop", logData->logId) .detail("Ver", stopVersion) .detail("IsStopped", logData->stopped) .detail("QueueCommitted", logData->queueCommittedVersion.get()); logData->stopped = true; if (!logData->recoveryComplete.isSet()) { logData->recoveryComplete.sendError(end_of_stream()); } // Lock once the current version has been committed wait(logData->queueCommittedVersion.whenAtLeast(stopVersion)); ASSERT(stopVersion == logData->version.get()); TLogLockResult result; result.end = stopVersion; result.knownCommittedVersion = logData->knownCommittedVersion; TraceEvent("TLogStop2", self->dbgid) .detail("LogId", logData->logId) .detail("Ver", stopVersion) .detail("IsStopped", logData->stopped) .detail("QueueCommitted", logData->queueCommittedVersion.get()) .detail("KnownCommitted", result.knownCommittedVersion); reply.send(result); return Void(); } void updatePersistentPopped(TLogData* self, Reference<LogData> logData, Reference<LogData::TagData> data) { if (!data->poppedRecently) return; self->persistentData->set( KeyValueRef(persistTagPoppedKey(logData->logId, data->tag), persistTagPoppedValue(data->popped))); data->poppedRecently = false; data->persistentPopped = data->popped; if (data->nothingPersistent) return; if (logData->shouldSpillByValue(data->tag)) { self->persistentData->clear(KeyRangeRef(persistTagMessagesKey(logData->logId, data->tag, Version(0)), persistTagMessagesKey(logData->logId, data->tag, data->popped))); } else { self->persistentData->clear(KeyRangeRef(persistTagMessageRefsKey(logData->logId, data->tag, Version(0)), persistTagMessageRefsKey(logData->logId, data->tag, data->popped))); } if (data->popped > logData->persistentDataVersion) { data->nothingPersistent = true; } } ACTOR Future<Void> updatePoppedLocation(TLogData* self, Reference<LogData> logData, Reference<LogData::TagData> data) { // For anything spilled by value, we do not need to track its popped location. if (logData->shouldSpillByValue(data->tag)) { return Void(); } if (data->versionForPoppedLocation >= data->persistentPopped) return Void(); data->versionForPoppedLocation = data->persistentPopped; // Use persistentPopped and not popped, so that a pop update received after spilling doesn't cause // us to remove data that still is pointed to by SpilledData in the btree. if (data->persistentPopped <= logData->persistentDataVersion) { // Recover the next needed location in the Disk Queue from the index. RangeResult kvrefs = wait(self->persistentData->readRange( KeyRangeRef(persistTagMessageRefsKey(logData->logId, data->tag, data->persistentPopped), persistTagMessageRefsKey(logData->logId, data->tag, logData->persistentDataVersion + 1)), 1)); if (kvrefs.empty()) { // Nothing was persistent after all. data->nothingPersistent = true; } else { VectorRef<SpilledData> spilledData; BinaryReader r(kvrefs[0].value, AssumeVersion(logData->protocolVersion)); r >> spilledData; for (const SpilledData& sd : spilledData) { if (sd.version >= data->persistentPopped) { data->poppedLocation = sd.start; data->versionForPoppedLocation = sd.version; break; } } } } if (data->persistentPopped >= logData->persistentDataVersion || data->nothingPersistent) { // Then the location must be in memory. auto locationIter = logData->versionLocation.lower_bound(data->persistentPopped); if (locationIter != logData->versionLocation.end()) { data->poppedLocation = locationIter->value.first; data->versionForPoppedLocation = locationIter->key; } else { // No data on disk and no data in RAM. // This TLog instance will be removed soon anyway, so we temporarily freeze our poppedLocation // to avoid trying to track what the ending location of this TLog instance was. } } return Void(); } // It runs against the oldest TLog instance, calculates the first location in the disk queue that contains un-popped // data, and then issues a pop to the disk queue at that location so that anything earlier can be // removed/forgotten/overwritten. In effect, it applies the effect of TLogPop RPCs to disk. ACTOR Future<Void> popDiskQueue(TLogData* self, Reference<LogData> logData) { if (!logData->initialized) return Void(); std::vector<Future<Void>> updates; for (int tagLocality = 0; tagLocality < logData->tag_data.size(); tagLocality++) { for (int tagId = 0; tagId < logData->tag_data[tagLocality].size(); tagId++) { Reference<LogData::TagData> tagData = logData->tag_data[tagLocality][tagId]; if (tagData) { updates.push_back(updatePoppedLocation(self, logData, tagData)); } } } wait(waitForAll(updates)); IDiskQueue::location minLocation = 0; Version minVersion = 0; auto locationIter = logData->versionLocation.lower_bound(logData->persistentDataVersion); if (locationIter != logData->versionLocation.end()) { minLocation = locationIter->value.first; minVersion = locationIter->key; } logData->minPoppedTagVersion = std::numeric_limits<Version>::max(); for (int tagLocality = 0; tagLocality < logData->tag_data.size(); tagLocality++) { for (int tagId = 0; tagId < logData->tag_data[tagLocality].size(); tagId++) { Reference<LogData::TagData> tagData = logData->tag_data[tagLocality][tagId]; if (tagData && logData->shouldSpillByReference(tagData->tag)) { if (!tagData->nothingPersistent) { minLocation = std::min(minLocation, tagData->poppedLocation); minVersion = std::min(minVersion, tagData->popped); } if ((!tagData->nothingPersistent || tagData->versionMessages.size()) && tagData->popped < logData->minPoppedTagVersion) { logData->minPoppedTagVersion = tagData->popped; logData->minPoppedTag = tagData->tag; } } } } if (self->queueCommitEnd.get() > 0) { Version lastCommittedVersion = logData->queueCommittedVersion.get(); IDiskQueue::location lastCommittedLocation = minLocation; auto locationIter = logData->versionLocation.lower_bound(lastCommittedVersion); if (locationIter != logData->versionLocation.end()) { lastCommittedLocation = locationIter->value.first; } self->persistentQueue->pop(std::min(minLocation, lastCommittedLocation)); logData->queuePoppedVersion = std::max(logData->queuePoppedVersion, minVersion); } return Void(); } ACTOR Future<Void> updatePersistentData(TLogData* self, Reference<LogData> logData, Version newPersistentDataVersion) { state BinaryWriter wr(Unversioned()); // PERSIST: Changes self->persistentDataVersion and writes and commits the relevant changes ASSERT(newPersistentDataVersion <= logData->version.get()); ASSERT(newPersistentDataVersion <= logData->queueCommittedVersion.get()); ASSERT(newPersistentDataVersion > logData->persistentDataVersion); ASSERT(logData->persistentDataVersion == logData->persistentDataDurableVersion); logData->newPersistentDataVersion = newPersistentDataVersion; //TraceEvent("UpdatePersistentData", self->dbgid).detail("Seq", newPersistentDataSeq); state bool anyData = false; // For all existing tags state int tagLocality = 0; state int tagId = 0; for (tagLocality = 0; tagLocality < logData->tag_data.size(); tagLocality++) { for (tagId = 0; tagId < logData->tag_data[tagLocality].size(); tagId++) { state Reference<LogData::TagData> tagData = logData->tag_data[tagLocality][tagId]; if (tagData) { wait(tagData->eraseMessagesBefore(tagData->popped, self, logData, TaskPriority::UpdateStorage)); state Version currentVersion = 0; // Clear recently popped versions from persistentData if necessary updatePersistentPopped(self, logData, tagData); state Version lastVersion = std::numeric_limits<Version>::min(); state IDiskQueue::location firstLocation = std::numeric_limits<IDiskQueue::location>::max(); // Transfer unpopped messages with version numbers less than newPersistentDataVersion to persistentData state std::deque<std::pair<Version, LengthPrefixedStringRef>>::iterator msg = tagData->versionMessages.begin(); state int refSpilledTagCount = 0; wr = BinaryWriter(AssumeVersion(logData->protocolVersion)); // We prefix our spilled locations with a count, so that we can read this back out as a VectorRef. wr << uint32_t(0); while (msg != tagData->versionMessages.end() && msg->first <= newPersistentDataVersion) { currentVersion = msg->first; anyData = true; tagData->nothingPersistent = false; if (logData->shouldSpillByValue(tagData->tag)) { wr = BinaryWriter(Unversioned()); for (; msg != tagData->versionMessages.end() && msg->first == currentVersion; ++msg) { wr << msg->second.toStringRef(); } self->persistentData->set(KeyValueRef( persistTagMessagesKey(logData->logId, tagData->tag, currentVersion), wr.toValue())); } else { // spill everything else by reference const IDiskQueue::location begin = logData->versionLocation[currentVersion].first; const IDiskQueue::location end = logData->versionLocation[currentVersion].second; ASSERT(end > begin && end.lo - begin.lo < std::numeric_limits<uint32_t>::max()); uint32_t length = static_cast<uint32_t>(end.lo - begin.lo); refSpilledTagCount++; uint32_t size = 0; for (; msg != tagData->versionMessages.end() && msg->first == currentVersion; ++msg) { // Fast forward until we find a new version. size += msg->second.expectedSize(); } SpilledData spilledData(currentVersion, begin, length, size); wr << spilledData; lastVersion = std::max(currentVersion, lastVersion); firstLocation = std::min(begin, firstLocation); if ((wr.getLength() + sizeof(SpilledData) > SERVER_KNOBS->TLOG_SPILL_REFERENCE_MAX_BYTES_PER_BATCH)) { *(uint32_t*)wr.getData() = refSpilledTagCount; self->persistentData->set(KeyValueRef( persistTagMessageRefsKey(logData->logId, tagData->tag, lastVersion), wr.toValue())); tagData->poppedLocation = std::min(tagData->poppedLocation, firstLocation); refSpilledTagCount = 0; wr = BinaryWriter(AssumeVersion(logData->protocolVersion)); wr << uint32_t(0); } Future<Void> f = yield(TaskPriority::UpdateStorage); if (!f.isReady()) { wait(f); msg = std::upper_bound(tagData->versionMessages.begin(), tagData->versionMessages.end(), std::make_pair(currentVersion, LengthPrefixedStringRef()), CompareFirst<std::pair<Version, LengthPrefixedStringRef>>()); } } } if (refSpilledTagCount > 0) { *(uint32_t*)wr.getData() = refSpilledTagCount; self->persistentData->set( KeyValueRef(persistTagMessageRefsKey(logData->logId, tagData->tag, lastVersion), wr.toValue())); tagData->poppedLocation = std::min(tagData->poppedLocation, firstLocation); } wait(yield(TaskPriority::UpdateStorage)); } } } auto locationIter = logData->versionLocation.lower_bound(newPersistentDataVersion); if (locationIter != logData->versionLocation.end()) { self->persistentData->set( KeyValueRef(persistRecoveryLocationKey, BinaryWriter::toValue(locationIter->value.first, Unversioned()))); } self->persistentData->set( KeyValueRef(BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistCurrentVersionKeys.begin), BinaryWriter::toValue(newPersistentDataVersion, Unversioned()))); self->persistentData->set(KeyValueRef( BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistKnownCommittedVersionKeys.begin), BinaryWriter::toValue(logData->knownCommittedVersion, Unversioned()))); logData->persistentDataVersion = newPersistentDataVersion; wait(self->persistentData->commit()); // SOMEDAY: This seems to be running pretty often, should we slow it down??? wait(delay(0, TaskPriority::UpdateStorage)); // Now that the changes we made to persistentData are durable, erase the data we moved from memory and the queue, // increase bytesDurable accordingly, and update persistentDataDurableVersion. TEST(anyData); // TLog moved data to persistentData logData->persistentDataDurableVersion = newPersistentDataVersion; for (tagLocality = 0; tagLocality < logData->tag_data.size(); tagLocality++) { for (tagId = 0; tagId < logData->tag_data[tagLocality].size(); tagId++) { if (logData->tag_data[tagLocality][tagId]) { wait(logData->tag_data[tagLocality][tagId]->eraseMessagesBefore( newPersistentDataVersion + 1, self, logData, TaskPriority::UpdateStorage)); wait(yield(TaskPriority::UpdateStorage)); } } } logData->version_sizes.erase(logData->version_sizes.begin(), logData->version_sizes.lower_bound(logData->persistentDataDurableVersion)); wait(yield(TaskPriority::UpdateStorage)); while (!logData->messageBlocks.empty() && logData->messageBlocks.front().first <= newPersistentDataVersion) { int64_t bytesErased = int64_t(logData->messageBlocks.front().second.size()) * SERVER_KNOBS->TLOG_MESSAGE_BLOCK_OVERHEAD_FACTOR; logData->bytesDurable += bytesErased; self->bytesDurable += bytesErased; logData->messageBlocks.pop_front(); wait(yield(TaskPriority::UpdateStorage)); } if (logData->bytesDurable.getValue() > logData->bytesInput.getValue() || self->bytesDurable > self->bytesInput) { TraceEvent(SevError, "BytesDurableTooLarge", logData->logId) .detail("SharedBytesInput", self->bytesInput) .detail("SharedBytesDurable", self->bytesDurable) .detail("LocalBytesInput", logData->bytesInput.getValue()) .detail("LocalBytesDurable", logData->bytesDurable.getValue()); } ASSERT(logData->bytesDurable.getValue() <= logData->bytesInput.getValue()); ASSERT(self->bytesDurable <= self->bytesInput); if (self->queueCommitEnd.get() > 0) { // FIXME: Maintain a heap of tags ordered by version to make this O(1) instead of O(n). Version minVersion = std::numeric_limits<Version>::max(); for (tagLocality = 0; tagLocality < logData->tag_data.size(); tagLocality++) { for (tagId = 0; tagId < logData->tag_data[tagLocality].size(); tagId++) { Reference<LogData::TagData> tagData = logData->tag_data[tagLocality][tagId]; if (tagData) { if (logData->shouldSpillByValue(tagData->tag)) { minVersion = std::min(minVersion, newPersistentDataVersion); } else { minVersion = std::min(minVersion, tagData->popped); } } } } if (minVersion != std::numeric_limits<Version>::max()) { self->persistentQueue->forgetBefore( newPersistentDataVersion, logData); // SOMEDAY: this can cause a slow task (~0.5ms), presumably from erasing too many versions. // Should we limit the number of versions cleared at a time? } } logData->newPersistentDataVersion = invalidVersion; return Void(); } ACTOR Future<Void> tLogPopCore(TLogData* self, Tag inputTag, Version to, Reference<LogData> logData) { state Version upTo = to; int8_t tagLocality = inputTag.locality; if (isPseudoLocality(tagLocality)) { if (logData->logSystem->get().isValid()) { upTo = logData->logSystem->get()->popPseudoLocalityTag(inputTag, to); tagLocality = tagLocalityLogRouter; } else { TraceEvent(SevWarn, "TLogPopNoLogSystem", self->dbgid) .detail("Locality", tagLocality) .detail("Version", upTo); return Void(); } } state Tag tag(tagLocality, inputTag.id); auto tagData = logData->getTagData(tag); if (!tagData) { tagData = logData->createTagData(tag, upTo, true, true, false); } else if (upTo > tagData->popped) { tagData->popped = upTo; tagData->poppedRecently = true; if (tagData->unpoppedRecovered && upTo > logData->recoveredAt) { tagData->unpoppedRecovered = false; logData->unpoppedRecoveredTags--; TraceEvent("TLogPoppedTag", logData->logId) .detail("Tags", logData->unpoppedRecoveredTags) .detail("Tag", tag.toString()) .detail("DurableKCVer", logData->durableKnownCommittedVersion) .detail("RecoveredAt", logData->recoveredAt); if (logData->unpoppedRecoveredTags == 0 && logData->durableKnownCommittedVersion >= logData->recoveredAt && logData->recoveryComplete.canBeSet()) { logData->recoveryComplete.send(Void()); } } uint64_t PoppedVersionLag = logData->persistentDataDurableVersion - logData->queuePoppedVersion; if ( SERVER_KNOBS->ENABLE_DETAILED_TLOG_POP_TRACE && (logData->queuePoppedVersion > 0) && //avoid generating massive events at beginning (tagData->unpoppedRecovered || PoppedVersionLag >= SERVER_KNOBS->TLOG_POPPED_VER_LAG_THRESHOLD_FOR_TLOGPOP_TRACE)) { //when recovery or long lag TraceEvent("TLogPopDetails", logData->logId) .detail("Tag", tagData->tag.toString()) .detail("UpTo", upTo) .detail("PoppedVersionLag", PoppedVersionLag) .detail("MinPoppedTag", logData->minPoppedTag.toString()) .detail("QueuePoppedVersion", logData->queuePoppedVersion) .detail("UnpoppedRecovered", tagData->unpoppedRecovered ? "True" : "False") .detail("NothingPersistent", tagData->nothingPersistent ? "True" : "False"); } if (upTo > logData->persistentDataDurableVersion) wait(tagData->eraseMessagesBefore(upTo, self, logData, TaskPriority::TLogPop)); //TraceEvent("TLogPop", logData->logId).detail("Tag", tag.toString()).detail("To", upTo); } return Void(); } ACTOR Future<Void> processPopRequests(TLogData* self, Reference<LogData> logData) { state std::vector<Future<Void>> ignoredPops; state std::map<Tag, Version>::const_iterator it; state int ignoredPopsPlayed = 0; state std::map<Tag, Version> toBePopped; toBePopped = std::move(self->toBePopped); self->toBePopped.clear(); self->ignorePopRequest = false; self->ignorePopDeadline = 0.0; self->ignorePopUid = ""; for (it = toBePopped.cbegin(); it != toBePopped.cend(); ++it) { const auto& [tag, version] = *it; TraceEvent("PlayIgnoredPop").detail("Tag", tag.toString()).detail("Version", version); ignoredPops.push_back(tLogPopCore(self, tag, version, logData)); if (++ignoredPopsPlayed % SERVER_KNOBS->TLOG_POP_BATCH_SIZE == 0) { TEST(true); // Yielding while processing pop requests wait(yield()); } } wait(waitForAll(ignoredPops)); TraceEvent("ResetIgnorePopRequest") .detail("IgnorePopRequest", self->ignorePopRequest) .detail("IgnorePopDeadline", self->ignorePopDeadline); return Void(); } ACTOR Future<Void> tLogPop(TLogData* self, TLogPopRequest req, Reference<LogData> logData) { if (self->ignorePopRequest) { TraceEvent(SevDebug, "IgnoringPopRequest").detail("IgnorePopDeadline", self->ignorePopDeadline); auto& v = self->toBePopped[req.tag]; v = std::max(v, req.to); TraceEvent(SevDebug, "IgnoringPopRequest") .detail("IgnorePopDeadline", self->ignorePopDeadline) .detail("Tag", req.tag.toString()) .detail("Version", req.to); } else { wait(tLogPopCore(self, req.tag, req.to, logData)); } req.reply.send(Void()); return Void(); } // This function (and updatePersistentData, which is called by this function) run at a low priority and can soak up all // CPU resources. For this reason, they employ aggressive use of yields to avoid causing slow tasks that could introduce // latencies for more important work (e.g. commits). // This actor is just a loop that calls updatePersistentData and popDiskQueue whenever // (a) there's data to be spilled or (b) we should update metadata after some commits have been fully popped. ACTOR Future<Void> updateStorage(TLogData* self) { while (self->spillOrder.size() && !self->id_data.count(self->spillOrder.front())) { self->spillOrder.pop_front(); } if (!self->spillOrder.size()) { wait(delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage)); return Void(); } state Reference<LogData> logData = self->id_data[self->spillOrder.front()]; state Version nextVersion = 0; state int totalSize = 0; state FlowLock::Releaser commitLockReleaser; // FIXME: This policy for calculating the cache pop version could end up popping recent data in the remote DC after // two consecutive recoveries. // It also does not protect against spilling the cache tag directly, so it is theoretically possible to spill this // tag; which is not intended to ever happen. Optional<Version> cachePopVersion; for (auto& it : self->id_data) { if (!it.second->stopped) { if (it.second->version.get() - it.second->unrecoveredBefore > SERVER_KNOBS->MAX_VERSIONS_IN_FLIGHT + SERVER_KNOBS->MAX_CACHE_VERSIONS) { cachePopVersion = it.second->version.get() - SERVER_KNOBS->MAX_CACHE_VERSIONS; } break; } } if (cachePopVersion.present()) { state std::vector<Future<Void>> cachePopFutures; for (auto& it : self->id_data) { cachePopFutures.push_back(tLogPop(self, TLogPopRequest(cachePopVersion.get(), 0, cacheTag), it.second)); } wait(waitForAll(cachePopFutures)); } if (logData->stopped) { if (self->bytesInput - self->bytesDurable >= self->targetVolatileBytes) { while (logData->persistentDataDurableVersion != logData->version.get()) { totalSize = 0; Map<Version, std::pair<int, int>>::iterator sizeItr = logData->version_sizes.begin(); nextVersion = logData->version.get(); while (totalSize < SERVER_KNOBS->REFERENCE_SPILL_UPDATE_STORAGE_BYTE_LIMIT && sizeItr != logData->version_sizes.end()) { totalSize += sizeItr->value.first + sizeItr->value.second; ++sizeItr; nextVersion = sizeItr == logData->version_sizes.end() ? logData->version.get() : sizeItr->key; } wait(logData->queueCommittedVersion.whenAtLeast(nextVersion)); wait(delay(0, TaskPriority::UpdateStorage)); //TraceEvent("TlogUpdatePersist", self->dbgid).detail("LogId", logData->logId).detail("NextVersion", nextVersion).detail("Version", logData->version.get()).detail("PersistentDataDurableVer", logData->persistentDataDurableVersion).detail("QueueCommitVer", logData->queueCommittedVersion.get()).detail("PersistDataVer", logData->persistentDataVersion); if (nextVersion > logData->persistentDataVersion) { wait(self->persistentDataCommitLock.take()); commitLockReleaser = FlowLock::Releaser(self->persistentDataCommitLock); wait(updatePersistentData(self, logData, nextVersion)); // Concurrently with this loop, the last stopped TLog could have been removed. if (self->popOrder.size()) { wait(popDiskQueue(self, self->id_data[self->popOrder.front()])); } commitLockReleaser.release(); } else { wait(delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage)); } if (logData->removed.isReady()) { break; } } if (logData->persistentDataDurableVersion == logData->version.get()) { self->spillOrder.pop_front(); } wait(delay(0.0, TaskPriority::UpdateStorage)); } else { wait(delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage)); } } else if (logData->initialized) { ASSERT(self->spillOrder.size() == 1); if (logData->version_sizes.empty()) { nextVersion = logData->version.get(); } else { // Double check that a running TLog wasn't wrongly affected by spilling locked SharedTLogs. ASSERT_WE_THINK(self->targetVolatileBytes == SERVER_KNOBS->TLOG_SPILL_THRESHOLD); Map<Version, std::pair<int, int>>::iterator sizeItr = logData->version_sizes.begin(); while (totalSize < SERVER_KNOBS->REFERENCE_SPILL_UPDATE_STORAGE_BYTE_LIMIT && sizeItr != logData->version_sizes.end() && (logData->bytesInput.getValue() - logData->bytesDurable.getValue() - totalSize >= self->targetVolatileBytes || sizeItr->value.first == 0)) { totalSize += sizeItr->value.first + sizeItr->value.second; ++sizeItr; nextVersion = sizeItr == logData->version_sizes.end() ? logData->version.get() : sizeItr->key; } } //TraceEvent("UpdateStorageVer", logData->logId).detail("NextVersion", nextVersion).detail("PersistentDataVersion", logData->persistentDataVersion).detail("TotalSize", totalSize); wait(logData->queueCommittedVersion.whenAtLeast(nextVersion)); wait(delay(0, TaskPriority::UpdateStorage)); if (nextVersion > logData->persistentDataVersion) { wait(self->persistentDataCommitLock.take()); commitLockReleaser = FlowLock::Releaser(self->persistentDataCommitLock); wait(updatePersistentData(self, logData, nextVersion)); if (self->popOrder.size()) { wait(popDiskQueue(self, self->id_data[self->popOrder.front()])); } commitLockReleaser.release(); } if (totalSize < SERVER_KNOBS->REFERENCE_SPILL_UPDATE_STORAGE_BYTE_LIMIT) { wait(delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage)); } else { // recovery wants to commit to persistant data when updatePersistentData is not active, this delay ensures // that immediately after updatePersist returns another one has not been started yet. wait(delay(0.0, TaskPriority::UpdateStorage)); } } else { wait(delay(BUGGIFY ? SERVER_KNOBS->BUGGIFY_TLOG_STORAGE_MIN_UPDATE_INTERVAL : SERVER_KNOBS->TLOG_STORAGE_MIN_UPDATE_INTERVAL, TaskPriority::UpdateStorage)); } return Void(); } ACTOR Future<Void> updateStorageLoop(TLogData* self) { wait(delay(0, TaskPriority::UpdateStorage)); loop { wait(updateStorage(self)); } } void commitMessages(TLogData* self, Reference<LogData> logData, Version version, const std::vector<TagsAndMessage>& taggedMessages) { // SOMEDAY: This method of copying messages is reasonably memory efficient, but it's still a lot of bytes copied. // Find a way to do the memory allocation right as we receive the messages in the network layer. int64_t addedBytes = 0; int64_t overheadBytes = 0; int expectedBytes = 0; int txsBytes = 0; if (!taggedMessages.size()) { return; } int msgSize = 0; for (auto& i : taggedMessages) { msgSize += i.message.size(); } // Grab the last block in the blocks list so we can share its arena // We pop all of the elements of it to create a "fresh" vector that starts at the end of the previous vector Standalone<VectorRef<uint8_t>> block; if (logData->messageBlocks.empty()) { block = Standalone<VectorRef<uint8_t>>(); block.reserve(block.arena(), std::max<int64_t>(SERVER_KNOBS->TLOG_MESSAGE_BLOCK_BYTES, msgSize)); } else { block = logData->messageBlocks.back().second; } block.pop_front(block.size()); for (auto& msg : taggedMessages) { if (msg.message.size() > block.capacity() - block.size()) { logData->messageBlocks.emplace_back(version, block); addedBytes += int64_t(block.size()) * SERVER_KNOBS->TLOG_MESSAGE_BLOCK_OVERHEAD_FACTOR; block = Standalone<VectorRef<uint8_t>>(); block.reserve(block.arena(), std::max<int64_t>(SERVER_KNOBS->TLOG_MESSAGE_BLOCK_BYTES, msgSize)); } DEBUG_TAGS_AND_MESSAGE("TLogCommitMessages", version, msg.getRawMessage()) .detail("UID", self->dbgid) .detail("LogId", logData->logId); block.append(block.arena(), msg.message.begin(), msg.message.size()); for (auto tag : msg.tags) { if (logData->locality == tagLocalitySatellite) { if (!(tag.locality == tagLocalityTxs || tag.locality == tagLocalityLogRouter || tag == txsTag)) { continue; } } else if (!(logData->locality == tagLocalitySpecial || logData->locality == tag.locality || tag.locality < 0)) { continue; } if (tag.locality == tagLocalityLogRouter) { if (!logData->logRouterTags) { continue; } tag.id = tag.id % logData->logRouterTags; } if (tag.locality == tagLocalityTxs) { if (logData->txsTags > 0) { tag.id = tag.id % logData->txsTags; } else { tag = txsTag; } } Reference<LogData::TagData> tagData = logData->getTagData(tag); if (!tagData) { tagData = logData->createTagData(tag, 0, true, true, false); } if (version >= tagData->popped) { tagData->versionMessages.emplace_back( version, LengthPrefixedStringRef((uint32_t*)(block.end() - msg.message.size()))); if (tagData->versionMessages.back().second.expectedSize() > SERVER_KNOBS->MAX_MESSAGE_SIZE) { TraceEvent(SevWarnAlways, "LargeMessage") .detail("Size", tagData->versionMessages.back().second.expectedSize()); } if (tag.locality != tagLocalityTxs && tag != txsTag) { expectedBytes += tagData->versionMessages.back().second.expectedSize(); } else { txsBytes += tagData->versionMessages.back().second.expectedSize(); } // The factor of VERSION_MESSAGES_OVERHEAD is intended to be an overestimate of the actual memory used // to store this data in a std::deque. In practice, this number is probably something like 528/512 // ~= 1.03, but this could vary based on the implementation. There will also be a fixed overhead per // std::deque, but its size should be trivial relative to the size of the TLog queue and can be thought // of as increasing the capacity of the queue slightly. overheadBytes += SERVER_KNOBS->VERSION_MESSAGES_ENTRY_BYTES_WITH_OVERHEAD; } } msgSize -= msg.message.size(); } logData->messageBlocks.emplace_back(version, block); addedBytes += int64_t(block.size()) * SERVER_KNOBS->TLOG_MESSAGE_BLOCK_OVERHEAD_FACTOR; addedBytes += overheadBytes; logData->version_sizes[version] = std::make_pair(expectedBytes, txsBytes); logData->bytesInput += addedBytes; self->bytesInput += addedBytes; self->overheadBytesInput += overheadBytes; //TraceEvent("TLogPushed", self->dbgid).detail("Bytes", addedBytes).detail("MessageBytes", messages.size()).detail("Tags", tags.size()).detail("ExpectedBytes", expectedBytes).detail("MCount", mCount).detail("TCount", tCount); } void commitMessages(TLogData* self, Reference<LogData> logData, Version version, Arena arena, StringRef messages) { ArenaReader rd(arena, messages, Unversioned()); self->tempTagMessages.clear(); while (!rd.empty()) { TagsAndMessage tagsAndMsg; tagsAndMsg.loadFromArena(&rd, nullptr); self->tempTagMessages.push_back(std::move(tagsAndMsg)); } commitMessages(self, logData, version, self->tempTagMessages); } Version poppedVersion(Reference<LogData> self, Tag tag) { auto tagData = self->getTagData(tag); if (!tagData) { if (tag == txsTag || tag.locality == tagLocalityTxs) { return 0; } return self->recoveredAt; } return tagData->popped; } std::deque<std::pair<Version, LengthPrefixedStringRef>>& getVersionMessages(Reference<LogData> self, Tag tag) { auto tagData = self->getTagData(tag); if (!tagData) { static std::deque<std::pair<Version, LengthPrefixedStringRef>> empty; return empty; } return tagData->versionMessages; }; void peekMessagesFromMemory(Reference<LogData> self, TLogPeekRequest const& req, BinaryWriter& messages, Version& endVersion) { ASSERT(!messages.getLength()); auto& deque = getVersionMessages(self, req.tag); //TraceEvent("TLogPeekMem", self->dbgid).detail("Tag", req.tag1).detail("PDS", self->persistentDataSequence).detail("PDDS", self->persistentDataDurableSequence).detail("Oldest", map1.empty() ? 0 : map1.begin()->key ).detail("OldestMsgCount", map1.empty() ? 0 : map1.begin()->value.size()); Version begin = std::max(req.begin, self->persistentDataDurableVersion + 1); auto it = std::lower_bound(deque.begin(), deque.end(), std::make_pair(begin, LengthPrefixedStringRef()), CompareFirst<std::pair<Version, LengthPrefixedStringRef>>()); Version currentVersion = -1; for (; it != deque.end(); ++it) { if (it->first != currentVersion) { if (messages.getLength() >= SERVER_KNOBS->DESIRED_TOTAL_BYTES) { endVersion = currentVersion + 1; //TraceEvent("TLogPeekMessagesReached2", self->dbgid); break; } currentVersion = it->first; messages << VERSION_HEADER << currentVersion; } // We need the 4 byte length prefix to be a TagsAndMessage format, but that prefix is added as part of StringRef // serialization. int offset = messages.getLength(); messages << it->second.toStringRef(); void* data = messages.getData(); DEBUG_TAGS_AND_MESSAGE( "TLogPeek", currentVersion, StringRef((uint8_t*)data + offset, messages.getLength() - offset)) .detail("LogId", self->logId) .detail("PeekTag", req.tag); } } ACTOR Future<std::vector<StringRef>> parseMessagesForTag(StringRef commitBlob, Tag tag, int logRouters) { // See the comment in LogSystem.cpp for the binary format of commitBlob. state std::vector<StringRef> relevantMessages; state BinaryReader rd(commitBlob, AssumeVersion(g_network->protocolVersion())); while (!rd.empty()) { TagsAndMessage tagsAndMessage; tagsAndMessage.loadFromArena(&rd, nullptr); for (Tag t : tagsAndMessage.tags) { if (t == tag || (tag.locality == tagLocalityLogRouter && t.locality == tagLocalityLogRouter && t.id % logRouters == tag.id)) { // Mutations that are in the partially durable span between known comitted version and // recovery version get copied to the new log generation. These commits might have had more // log router tags than what now exist, so we mod them down to what we have. relevantMessages.push_back(tagsAndMessage.getRawMessage()); break; } } wait(yield()); } return relevantMessages; } ACTOR Future<Void> tLogPeekMessages(TLogData* self, TLogPeekRequest req, Reference<LogData> logData) { state BinaryWriter messages(Unversioned()); state BinaryWriter messages2(Unversioned()); state int sequence = -1; state UID peekId; state double queueStart = now(); if (req.tag.locality == tagLocalityTxs && req.tag.id >= logData->txsTags && logData->txsTags > 0) { req.tag.id = req.tag.id % logData->txsTags; } if (req.sequence.present()) { try { peekId = req.sequence.get().first; sequence = req.sequence.get().second; if (sequence >= SERVER_KNOBS->PARALLEL_GET_MORE_REQUESTS && logData->peekTracker.find(peekId) == logData->peekTracker.end()) { throw operation_obsolete(); } auto& trackerData = logData->peekTracker[peekId]; if (sequence == 0 && trackerData.sequence_version.find(0) == trackerData.sequence_version.end()) { trackerData.tag = req.tag; trackerData.sequence_version[0].send(std::make_pair(req.begin, req.onlySpilled)); } auto seqBegin = trackerData.sequence_version.begin(); // The peek cursor and this comparison need to agree about the maximum number of in-flight requests. while (trackerData.sequence_version.size() && seqBegin->first <= sequence - SERVER_KNOBS->PARALLEL_GET_MORE_REQUESTS) { if (seqBegin->second.canBeSet()) { seqBegin->second.sendError(operation_obsolete()); } trackerData.sequence_version.erase(seqBegin); seqBegin = trackerData.sequence_version.begin(); } if (trackerData.sequence_version.size() && sequence < seqBegin->first) { throw operation_obsolete(); } Future<std::pair<Version, bool>> fPrevPeekData = trackerData.sequence_version[sequence].getFuture(); if (fPrevPeekData.isReady()) { trackerData.unblockedPeeks++; double t = now() - trackerData.lastUpdate; if (t > trackerData.idleMax) trackerData.idleMax = t; trackerData.idleTime += t; } trackerData.lastUpdate = now(); std::pair<Version, bool> prevPeekData = wait(fPrevPeekData); req.begin = std::max(prevPeekData.first, req.begin); req.onlySpilled = prevPeekData.second; wait(yield()); } catch (Error& e) { if (e.code() == error_code_timed_out || e.code() == error_code_operation_obsolete) { req.reply.sendError(e); return Void(); } else { throw; } } } state double blockStart = now(); if (req.returnIfBlocked && logData->version.get() < req.begin) { req.reply.sendError(end_of_stream()); if (req.sequence.present()) { auto& trackerData = logData->peekTracker[peekId]; auto& sequenceData = trackerData.sequence_version[sequence + 1]; trackerData.lastUpdate = now(); if (!sequenceData.isSet()) { sequenceData.send(std::make_pair(req.begin, req.onlySpilled)); } } return Void(); } //TraceEvent("TLogPeekMessages0", self->dbgid).detail("ReqBeginEpoch", req.begin.epoch).detail("ReqBeginSeq", req.begin.sequence).detail("Epoch", self->epoch()).detail("PersistentDataSeq", self->persistentDataSequence).detail("Tag1", req.tag1).detail("Tag2", req.tag2); // Wait until we have something to return that the caller doesn't already have if (logData->version.get() < req.begin) { wait(logData->version.whenAtLeast(req.begin)); wait(delay(SERVER_KNOBS->TLOG_PEEK_DELAY, g_network->getCurrentTask())); } if (logData->locality != tagLocalitySatellite && req.tag.locality == tagLocalityLogRouter) { wait(self->concurrentLogRouterReads.take()); state FlowLock::Releaser globalReleaser(self->concurrentLogRouterReads); wait(delay(0.0, TaskPriority::Low)); } if (req.begin <= logData->persistentDataDurableVersion && req.tag.locality != tagLocalityTxs && req.tag != txsTag) { // Reading spilled data will almost always imply that the storage server is >5s behind the rest // of the cluster. We shouldn't prioritize spending CPU on helping this server catch up // slightly faster over keeping the rest of the cluster operating normally. // txsTag is only ever peeked on recovery, and we would still wish to prioritize requests // that impact recovery duration. wait(delay(0, TaskPriority::TLogSpilledPeekReply)); } state double workStart = now(); Version poppedVer = poppedVersion(logData, req.tag); if (poppedVer > req.begin) { TLogPeekReply rep; rep.maxKnownVersion = logData->version.get(); rep.minKnownCommittedVersion = logData->minKnownCommittedVersion; rep.popped = poppedVer; rep.end = poppedVer; rep.onlySpilled = false; if (req.sequence.present()) { auto& trackerData = logData->peekTracker[peekId]; auto& sequenceData = trackerData.sequence_version[sequence + 1]; trackerData.lastUpdate = now(); if (trackerData.sequence_version.size() && sequence + 1 < trackerData.sequence_version.begin()->first) { req.reply.sendError(operation_obsolete()); if (!sequenceData.isSet()) sequenceData.sendError(operation_obsolete()); return Void(); } if (sequenceData.isSet()) { if (sequenceData.getFuture().get().first != rep.end) { TEST(true); // tlog peek second attempt ended at a different version req.reply.sendError(operation_obsolete()); return Void(); } } else { sequenceData.send(std::make_pair(rep.end, rep.onlySpilled)); } rep.begin = req.begin; } req.reply.send(rep); return Void(); } state Version endVersion = logData->version.get() + 1; state bool onlySpilled = false; // grab messages from disk //TraceEvent("TLogPeekMessages", self->dbgid).detail("ReqBeginEpoch", req.begin.epoch).detail("ReqBeginSeq", req.begin.sequence).detail("Epoch", self->epoch()).detail("PersistentDataSeq", self->persistentDataSequence).detail("Tag1", req.tag1).detail("Tag2", req.tag2); if (req.begin <= logData->persistentDataDurableVersion) { // Just in case the durable version changes while we are waiting for the read, we grab this data from memory. We // may or may not actually send it depending on whether we get enough data from disk. SOMEDAY: Only do this if // an initial attempt to read from disk results in insufficient data and the required data is no longer in // memory SOMEDAY: Should we only send part of the messages we collected, to actually limit the size of the // result? if (req.onlySpilled) { endVersion = logData->persistentDataDurableVersion + 1; } else { peekMessagesFromMemory(logData, req, messages2, endVersion); } if (logData->shouldSpillByValue(req.tag)) { RangeResult kvs = wait(self->persistentData->readRange( KeyRangeRef(persistTagMessagesKey(logData->logId, req.tag, req.begin), persistTagMessagesKey(logData->logId, req.tag, logData->persistentDataDurableVersion + 1)), SERVER_KNOBS->DESIRED_TOTAL_BYTES, SERVER_KNOBS->DESIRED_TOTAL_BYTES)); for (auto& kv : kvs) { auto ver = decodeTagMessagesKey(kv.key); messages << VERSION_HEADER << ver; messages.serializeBytes(kv.value); } if (kvs.expectedSize() >= SERVER_KNOBS->DESIRED_TOTAL_BYTES) { endVersion = decodeTagMessagesKey(kvs.end()[-1].key) + 1; onlySpilled = true; } else { messages.serializeBytes(messages2.toValue()); } } else { // FIXME: Limit to approximately DESIRED_TOTATL_BYTES somehow. RangeResult kvrefs = wait(self->persistentData->readRange( KeyRangeRef( persistTagMessageRefsKey(logData->logId, req.tag, req.begin), persistTagMessageRefsKey(logData->logId, req.tag, logData->persistentDataDurableVersion + 1)), SERVER_KNOBS->TLOG_SPILL_REFERENCE_MAX_BATCHES_PER_PEEK + 1)); //TraceEvent("TLogPeekResults", self->dbgid).detail("ForAddress", req.reply.getEndpoint().getPrimaryAddress()).detail("Tag1Results", s1).detail("Tag2Results", s2).detail("Tag1ResultsLim", kv1.size()).detail("Tag2ResultsLim", kv2.size()).detail("Tag1ResultsLast", kv1.size() ? kv1[0].key : "").detail("Tag2ResultsLast", kv2.size() ? kv2[0].key : "").detail("Limited", limited).detail("NextEpoch", next_pos.epoch).detail("NextSeq", next_pos.sequence).detail("NowEpoch", self->epoch()).detail("NowSeq", self->sequence.getNextSequence()); state std::vector<std::pair<IDiskQueue::location, IDiskQueue::location>> commitLocations; state bool earlyEnd = false; uint32_t mutationBytes = 0; state uint64_t commitBytes = 0; state Version firstVersion = std::numeric_limits<Version>::max(); for (int i = 0; i < kvrefs.size() && i < SERVER_KNOBS->TLOG_SPILL_REFERENCE_MAX_BATCHES_PER_PEEK; i++) { auto& kv = kvrefs[i]; VectorRef<SpilledData> spilledData; BinaryReader r(kv.value, AssumeVersion(logData->protocolVersion)); r >> spilledData; for (const SpilledData& sd : spilledData) { if (mutationBytes >= SERVER_KNOBS->DESIRED_TOTAL_BYTES) { earlyEnd = true; break; } if (sd.version >= req.begin) { firstVersion = std::min(firstVersion, sd.version); const IDiskQueue::location end = sd.start.lo + sd.length; commitLocations.emplace_back(sd.start, end); // This isn't perfect, because we aren't accounting for page boundaries, but should be // close enough. commitBytes += sd.length; mutationBytes += sd.mutationBytes; } } if (earlyEnd) break; } earlyEnd = earlyEnd || (kvrefs.size() >= SERVER_KNOBS->TLOG_SPILL_REFERENCE_MAX_BATCHES_PER_PEEK + 1); wait(self->peekMemoryLimiter.take(TaskPriority::TLogSpilledPeekReply, commitBytes)); state FlowLock::Releaser memoryReservation(self->peekMemoryLimiter, commitBytes); state std::vector<Future<Standalone<StringRef>>> messageReads; messageReads.reserve(commitLocations.size()); for (const auto& pair : commitLocations) { messageReads.push_back(self->rawPersistentQueue->read(pair.first, pair.second, CheckHashes::True)); } commitLocations.clear(); wait(waitForAll(messageReads)); state Version lastRefMessageVersion = 0; state int index = 0; loop { if (index >= messageReads.size()) break; Standalone<StringRef> queueEntryData = messageReads[index].get(); uint8_t valid; const uint32_t length = *(uint32_t*)queueEntryData.begin(); queueEntryData = queueEntryData.substr(4, queueEntryData.size() - 4); BinaryReader rd(queueEntryData, IncludeVersion()); state TLogQueueEntry entry; rd >> entry >> valid; ASSERT(valid == 0x01); ASSERT(length + sizeof(valid) == queueEntryData.size()); messages << VERSION_HEADER << entry.version; std::vector<StringRef> rawMessages = wait(parseMessagesForTag(entry.messages, req.tag, logData->logRouterTags)); for (const StringRef& msg : rawMessages) { messages.serializeBytes(msg); DEBUG_TAGS_AND_MESSAGE("TLogPeekFromDisk", entry.version, msg) .detail("UID", self->dbgid) .detail("LogId", logData->logId) .detail("PeekTag", req.tag); } lastRefMessageVersion = entry.version; index++; } messageReads.clear(); memoryReservation.release(); if (earlyEnd) { endVersion = lastRefMessageVersion + 1; onlySpilled = true; } else { messages.serializeBytes(messages2.toValue()); } } } else { if (req.onlySpilled) { endVersion = logData->persistentDataDurableVersion + 1; } else { peekMessagesFromMemory(logData, req, messages, endVersion); } //TraceEvent("TLogPeekResults", self->dbgid).detail("ForAddress", req.reply.getEndpoint().getPrimaryAddress()).detail("MessageBytes", messages.getLength()).detail("NextEpoch", next_pos.epoch).detail("NextSeq", next_pos.sequence).detail("NowSeq", self->sequence.getNextSequence()); } TLogPeekReply reply; reply.maxKnownVersion = logData->version.get(); reply.minKnownCommittedVersion = logData->minKnownCommittedVersion; reply.messages = messages.toValue(); reply.end = endVersion; reply.onlySpilled = onlySpilled; //TraceEvent("TlogPeek", self->dbgid).detail("LogId", logData->logId).detail("Tag", req.tag.toString()). // detail("BeginVer", req.begin).detail("EndVer", reply.end). // detail("MsgBytes", reply.messages.expectedSize()). // detail("ForAddress", req.reply.getEndpoint().getPrimaryAddress()); if (req.sequence.present()) { auto& trackerData = logData->peekTracker[peekId]; trackerData.lastUpdate = now(); double queueT = blockStart - queueStart; double blockT = workStart - blockStart; double workT = now() - workStart; trackerData.totalPeeks++; trackerData.replyBytes += reply.messages.size(); if (queueT > trackerData.queueMax) trackerData.queueMax = queueT; if (blockT > trackerData.blockMax) trackerData.blockMax = blockT; if (workT > trackerData.workMax) trackerData.workMax = workT; trackerData.queueTime += queueT; trackerData.blockTime += blockT; trackerData.workTime += workT; auto& sequenceData = trackerData.sequence_version[sequence + 1]; if (trackerData.sequence_version.size() && sequence + 1 < trackerData.sequence_version.begin()->first) { req.reply.sendError(operation_obsolete()); if (!sequenceData.isSet()) { // It would technically be more correct to .send({req.begin, req.onlySpilled}), as the next // request might still be in the window of active requests, but LogSystemPeekCursor will // throw away all future responses upon getting an operation_obsolete(), so computing a // response will probably be a waste of CPU. sequenceData.sendError(operation_obsolete()); } return Void(); } if (sequenceData.isSet()) { trackerData.duplicatePeeks++; if (sequenceData.getFuture().get().first != reply.end) { TEST(true); // tlog peek second attempt ended at a different version (2) req.reply.sendError(operation_obsolete()); return Void(); } } else { sequenceData.send(std::make_pair(reply.end, reply.onlySpilled)); } reply.begin = req.begin; } req.reply.send(reply); return Void(); } ACTOR Future<Void> doQueueCommit(TLogData* self, Reference<LogData> logData, std::vector<Reference<LogData>> missingFinalCommit) { state Version ver = logData->version.get(); state Version commitNumber = self->queueCommitBegin + 1; state Version knownCommittedVersion = logData->knownCommittedVersion; self->queueCommitBegin = commitNumber; logData->queueCommittingVersion = ver; g_network->setCurrentTask(TaskPriority::TLogCommitReply); Future<Void> c = self->persistentQueue->commit(); self->diskQueueCommitBytes = 0; self->largeDiskQueueCommitBytes.set(false); wait(ioDegradedOrTimeoutError( c, SERVER_KNOBS->MAX_STORAGE_COMMIT_TIME, self->degraded, SERVER_KNOBS->TLOG_DEGRADED_DURATION)); if (g_network->isSimulated() && !g_simulator.speedUpSimulation && BUGGIFY_WITH_PROB(0.0001)) { wait(delay(6.0)); } wait(self->queueCommitEnd.whenAtLeast(commitNumber - 1)); // Calling check_yield instead of yield to avoid a destruction ordering problem in simulation if (g_network->check_yield(g_network->getCurrentTask())) { wait(delay(0, g_network->getCurrentTask())); } ASSERT(ver > logData->queueCommittedVersion.get()); logData->durableKnownCommittedVersion = knownCommittedVersion; if (logData->unpoppedRecoveredTags == 0 && knownCommittedVersion >= logData->recoveredAt && logData->recoveryComplete.canBeSet()) { TraceEvent("TLogRecoveryComplete", logData->logId) .detail("Tags", logData->unpoppedRecoveredTags) .detail("DurableKCVer", logData->durableKnownCommittedVersion) .detail("RecoveredAt", logData->recoveredAt); logData->recoveryComplete.send(Void()); } //TraceEvent("TLogCommitDurable", self->dbgid).detail("Version", ver); if (logData->logSystem->get() && (!logData->isPrimary || logData->logRouterPoppedVersion < logData->logRouterPopToVersion)) { logData->logRouterPoppedVersion = ver; logData->logSystem->get()->pop(ver, logData->remoteTag, knownCommittedVersion, logData->locality); } logData->queueCommittedVersion.set(ver); self->queueCommitEnd.set(commitNumber); for (auto& it : missingFinalCommit) { TraceEvent("TLogCommitMissingFinalCommit", self->dbgid) .detail("LogId", logData->logId) .detail("Version", it->version.get()) .detail("QueueVer", it->queueCommittedVersion.get()); TEST(true); // A TLog was replaced before having a chance to commit its queue it->queueCommittedVersion.set(it->version.get()); } return Void(); } ACTOR Future<Void> commitQueue(TLogData* self) { state Reference<LogData> logData; state std::vector<Reference<LogData>> missingFinalCommit; loop { int foundCount = 0; for (auto it : self->id_data) { if (!it.second->stopped) { logData = it.second; foundCount++; } else if (it.second->version.get() > std::max(it.second->queueCommittingVersion, it.second->queueCommittedVersion.get())) { missingFinalCommit.push_back(it.second); } } ASSERT(foundCount < 2); if (!foundCount) { wait(self->newLogData.onTrigger()); continue; } TraceEvent("CommitQueueNewLog", self->dbgid) .detail("LogId", logData->logId) .detail("Version", logData->version.get()) .detail("Committing", logData->queueCommittingVersion) .detail("Commmitted", logData->queueCommittedVersion.get()); if (logData->committingQueue.canBeSet()) { logData->committingQueue.send(Void()); } loop { if (logData->stopped && logData->version.get() == std::max(logData->queueCommittingVersion, logData->queueCommittedVersion.get())) { wait(logData->queueCommittedVersion.whenAtLeast(logData->version.get())); break; } choose { when(wait(logData->version.whenAtLeast( std::max(logData->queueCommittingVersion, logData->queueCommittedVersion.get()) + 1))) { while (self->queueCommitBegin != self->queueCommitEnd.get() && !self->largeDiskQueueCommitBytes.get()) { wait(self->queueCommitEnd.whenAtLeast(self->queueCommitBegin) || self->largeDiskQueueCommitBytes.onChange()); } self->sharedActors.send(doQueueCommit(self, logData, missingFinalCommit)); missingFinalCommit.clear(); } when(wait(self->newLogData.onTrigger())) {} } } } } ACTOR Future<Void> tLogCommit(TLogData* self, TLogCommitRequest req, Reference<LogData> logData, PromiseStream<Void> warningCollectorInput) { state Span span("TLog:tLogCommit"_loc, req.spanContext); state Optional<UID> tlogDebugID; if (req.debugID.present()) { tlogDebugID = nondeterministicRandom()->randomUniqueID(); g_traceBatch.addAttach("CommitAttachID", req.debugID.get().first(), tlogDebugID.get().first()); g_traceBatch.addEvent("CommitDebug", tlogDebugID.get().first(), "TLog.tLogCommit.BeforeWaitForVersion"); } logData->minKnownCommittedVersion = std::max(logData->minKnownCommittedVersion, req.minKnownCommittedVersion); wait(logData->version.whenAtLeast(req.prevVersion)); // Calling check_yield instead of yield to avoid a destruction ordering problem in simulation if (g_network->check_yield(g_network->getCurrentTask())) { wait(delay(0, g_network->getCurrentTask())); } state double waitStartT = 0; while (self->bytesInput - self->bytesDurable >= SERVER_KNOBS->TLOG_HARD_LIMIT_BYTES && !logData->stopped) { if (now() - waitStartT >= 1) { TraceEvent(SevWarn, "TLogUpdateLag", logData->logId) .detail("Version", logData->version.get()) .detail("PersistentDataVersion", logData->persistentDataVersion) .detail("PersistentDataDurableVersion", logData->persistentDataDurableVersion); waitStartT = now(); } wait(delayJittered(.005, TaskPriority::TLogCommit)); } if (logData->stopped) { req.reply.sendError(tlog_stopped()); return Void(); } state double beforeCommitT = now(); // Not a duplicate (check relies on critical section between here self->version.set() below!) state bool isNotDuplicate = (logData->version.get() == req.prevVersion); if (isNotDuplicate) { if (req.debugID.present()) g_traceBatch.addEvent("CommitDebug", tlogDebugID.get().first(), "TLog.tLogCommit.Before"); //TraceEvent("TLogCommit", logData->logId).detail("Version", req.version); commitMessages(self, logData, req.version, req.arena, req.messages); logData->knownCommittedVersion = std::max(logData->knownCommittedVersion, req.knownCommittedVersion); TLogQueueEntryRef qe; // Log the changes to the persistent queue, to be committed by commitQueue() qe.version = req.version; qe.knownCommittedVersion = logData->knownCommittedVersion; qe.messages = req.messages; qe.id = logData->logId; self->persistentQueue->push(qe, logData); self->diskQueueCommitBytes += qe.expectedSize(); if (self->diskQueueCommitBytes > SERVER_KNOBS->MAX_QUEUE_COMMIT_BYTES) { self->largeDiskQueueCommitBytes.set(true); } // Notifies the commitQueue actor to commit persistentQueue, and also unblocks tLogPeekMessages actors logData->version.set(req.version); if (req.debugID.present()) g_traceBatch.addEvent("CommitDebug", tlogDebugID.get().first(), "TLog.tLogCommit.AfterTLogCommit"); } // Send replies only once all prior messages have been received and committed. state Future<Void> stopped = logData->stopCommit.onTrigger(); wait( timeoutWarning(logData->queueCommittedVersion.whenAtLeast(req.version) || stopped, 0.1, warningCollectorInput)); if (stopped.isReady()) { ASSERT(logData->stopped); req.reply.sendError(tlog_stopped()); return Void(); } if (isNotDuplicate) { self->commitLatencyDist->sampleSeconds(now() - beforeCommitT); } if (req.debugID.present()) g_traceBatch.addEvent("CommitDebug", tlogDebugID.get().first(), "TLog.tLogCommit.After"); req.reply.send(logData->durableKnownCommittedVersion); return Void(); } ACTOR Future<Void> initPersistentState(TLogData* self, Reference<LogData> logData) { wait(self->persistentDataCommitLock.take()); state FlowLock::Releaser commitLockReleaser(self->persistentDataCommitLock); // PERSIST: Initial setup of persistentData for a brand new tLog for a new database state IKeyValueStore* storage = self->persistentData; wait(ioTimeoutError(storage->init(), SERVER_KNOBS->TLOG_MAX_CREATE_DURATION)); storage->set(persistFormat); storage->set( KeyValueRef(BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistCurrentVersionKeys.begin), BinaryWriter::toValue(logData->version.get(), Unversioned()))); storage->set(KeyValueRef( BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistKnownCommittedVersionKeys.begin), BinaryWriter::toValue(logData->knownCommittedVersion, Unversioned()))); storage->set(KeyValueRef(BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistLocalityKeys.begin), BinaryWriter::toValue(logData->locality, Unversioned()))); storage->set( KeyValueRef(BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistLogRouterTagsKeys.begin), BinaryWriter::toValue(logData->logRouterTags, Unversioned()))); storage->set(KeyValueRef(BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistTxsTagsKeys.begin), BinaryWriter::toValue(logData->txsTags, Unversioned()))); storage->set( KeyValueRef(BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistRecoveryCountKeys.begin), BinaryWriter::toValue(logData->recoveryCount, Unversioned()))); storage->set( KeyValueRef(BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistProtocolVersionKeys.begin), BinaryWriter::toValue(logData->protocolVersion, Unversioned()))); storage->set( KeyValueRef(BinaryWriter::toValue(logData->logId, Unversioned()).withPrefix(persistTLogSpillTypeKeys.begin), BinaryWriter::toValue(logData->logSpillType, AssumeVersion(logData->protocolVersion)))); for (auto tag : logData->allTags) { ASSERT(!logData->getTagData(tag)); logData->createTagData(tag, 0, true, true, true); updatePersistentPopped(self, logData, logData->getTagData(tag)); } TraceEvent("TLogInitCommit", logData->logId); wait(ioTimeoutError(self->persistentData->commit(), SERVER_KNOBS->TLOG_MAX_CREATE_DURATION)); return Void(); } ACTOR Future<Void> rejoinMasters(TLogData* self, TLogInterface tli, DBRecoveryCount recoveryCount, Future<Void> registerWithMaster, bool isPrimary) { state UID lastMasterID(0, 0); loop { auto const& inf = self->dbInfo->get(); bool isDisplaced = !std::count(inf.priorCommittedLogServers.begin(), inf.priorCommittedLogServers.end(), tli.id()); if (isPrimary) { isDisplaced = isDisplaced && inf.recoveryCount >= recoveryCount && inf.recoveryState != RecoveryState::UNINITIALIZED; } else { isDisplaced = isDisplaced && ((inf.recoveryCount > recoveryCount && inf.recoveryState != RecoveryState::UNINITIALIZED) || (inf.recoveryCount == recoveryCount && inf.recoveryState == RecoveryState::FULLY_RECOVERED)); } isDisplaced = isDisplaced && !inf.logSystemConfig.hasTLog(tli.id()); if (isDisplaced) { TraceEvent("TLogDisplaced", tli.id()) .detail("Reason", "DBInfoDoesNotContain") .detail("RecoveryCount", recoveryCount) .detail("InfRecoveryCount", inf.recoveryCount) .detail("RecoveryState", (int)inf.recoveryState) .detail("LogSysConf", describe(inf.logSystemConfig.tLogs)) .detail("PriorLogs", describe(inf.priorCommittedLogServers)) .detail("OldLogGens", inf.logSystemConfig.oldTLogs.size()); if (BUGGIFY) wait(delay(SERVER_KNOBS->BUGGIFY_WORKER_REMOVED_MAX_LAG * deterministicRandom()->random01())); throw worker_removed(); } if (registerWithMaster.isReady()) { if (self->dbInfo->get().master.id() != lastMasterID) { // The TLogRejoinRequest is needed to establish communications with a new master, which doesn't have our // TLogInterface TLogRejoinRequest req(tli); TraceEvent("TLogRejoining", tli.id()).detail("Master", self->dbInfo->get().master.id()); choose { when(TLogRejoinReply rep = wait(brokenPromiseToNever(self->dbInfo->get().master.tlogRejoin.getReply(req)))) { if (rep.masterIsRecovered) lastMasterID = self->dbInfo->get().master.id(); } when(wait(self->dbInfo->onChange())) {} } } else { wait(self->dbInfo->onChange()); } } else { wait(registerWithMaster || self->dbInfo->onChange()); } } } ACTOR Future<Void> respondToRecovered(TLogInterface tli, Promise<Void> recoveryComplete) { state bool finishedRecovery = true; try { wait(recoveryComplete.getFuture()); } catch (Error& e) { if (e.code() != error_code_end_of_stream) { throw; } finishedRecovery = false; } TraceEvent("TLogRespondToRecovered", tli.id()).detail("Finished", finishedRecovery); loop { TLogRecoveryFinishedRequest req = waitNext(tli.recoveryFinished.getFuture()); if (finishedRecovery) { req.reply.send(Void()); } else { req.reply.send(Never()); } } } ACTOR Future<Void> cleanupPeekTrackers(LogData* logData) { loop { double minTimeUntilExpiration = SERVER_KNOBS->PEEK_TRACKER_EXPIRATION_TIME; auto it = logData->peekTracker.begin(); while (it != logData->peekTracker.end()) { double timeUntilExpiration = it->second.lastUpdate + SERVER_KNOBS->PEEK_TRACKER_EXPIRATION_TIME - now(); if (timeUntilExpiration < 1.0e-6) { for (auto seq : it->second.sequence_version) { if (!seq.second.isSet()) { seq.second.sendError(timed_out()); } } it = logData->peekTracker.erase(it); } else { minTimeUntilExpiration = std::min(minTimeUntilExpiration, timeUntilExpiration); ++it; } } wait(delay(minTimeUntilExpiration)); } } ACTOR Future<Void> logPeekTrackers(LogData* logData) { loop { int64_t logThreshold = 1; if (logData->peekTracker.size() > SERVER_KNOBS->PEEK_LOGGING_AMOUNT) { std::vector<int64_t> peekCounts; peekCounts.reserve(logData->peekTracker.size()); for (auto& it : logData->peekTracker) { peekCounts.push_back(it.second.totalPeeks); } size_t pivot = peekCounts.size() - SERVER_KNOBS->PEEK_LOGGING_AMOUNT; std::nth_element(peekCounts.begin(), peekCounts.begin() + pivot, peekCounts.end()); logThreshold = std::max<int64_t>(1, peekCounts[pivot]); } int logCount = 0; for (auto& it : logData->peekTracker) { if (it.second.totalPeeks >= logThreshold) { logCount++; TraceEvent("PeekMetrics", logData->logId) .detail("Tag", it.second.tag.toString()) .detail("Elapsed", now() - it.second.lastLogged) .detail("MeanReplyBytes", it.second.replyBytes / it.second.totalPeeks) .detail("TotalPeeks", it.second.totalPeeks) .detail("UnblockedPeeks", it.second.unblockedPeeks) .detail("DuplicatePeeks", it.second.duplicatePeeks) .detail("Sequence", it.second.sequence_version.size() ? it.second.sequence_version.begin()->first : -1) .detail("IdleSeconds", it.second.idleTime) .detail("IdleMax", it.second.idleMax) .detail("QueueSeconds", it.second.queueTime) .detail("QueueMax", it.second.queueMax) .detail("BlockSeconds", it.second.blockTime) .detail("BlockMax", it.second.blockMax) .detail("WorkSeconds", it.second.workTime) .detail("WorkMax", it.second.workMax); it.second.resetMetrics(); } } wait(delay(SERVER_KNOBS->PEEK_LOGGING_DELAY * std::max(1, logCount))); } } void getQueuingMetrics(TLogData* self, Reference<LogData> logData, TLogQueuingMetricsRequest const& req) { TLogQueuingMetricsReply reply; reply.localTime = now(); reply.instanceID = self->instanceID; reply.bytesInput = self->bytesInput; reply.bytesDurable = self->bytesDurable; reply.storageBytes = self->persistentData->getStorageBytes(); // FIXME: Add the knownCommittedVersion to this message and change ratekeeper to use that version. reply.v = logData->durableKnownCommittedVersion; req.reply.send(reply); } ACTOR Future<Void> tLogSnapCreate(TLogSnapRequest snapReq, TLogData* self, Reference<LogData> logData) { if (self->ignorePopUid != snapReq.snapUID.toString()) { snapReq.reply.sendError(operation_failed()); return Void(); } ExecCmdValueString snapArg(snapReq.snapPayload); try { int err = wait(execHelper(&snapArg, snapReq.snapUID, self->dataFolder, snapReq.role.toString())); std::string uidStr = snapReq.snapUID.toString(); TraceEvent("ExecTraceTLog") .detail("Uid", uidStr) .detail("Status", err) .detail("Role", snapReq.role) .detail("Value", self->dataFolder) .detail("ExecPayload", snapReq.snapPayload) .detail("PersistentDataVersion", logData->persistentDataVersion) .detail("PersistentDatadurableVersion", logData->persistentDataDurableVersion) .detail("QueueCommittedVersion", logData->queueCommittedVersion.get()) .detail("Version", logData->version.get()); if (err != 0) { throw operation_failed(); } snapReq.reply.send(Void()); } catch (Error& e) { TraceEvent("TLogExecHelperError").error(e, true /*includeCancelled */); if (e.code() != error_code_operation_cancelled) { snapReq.reply.sendError(e); } else { throw e; } } return Void(); } ACTOR Future<Void> tLogEnablePopReq(TLogEnablePopRequest enablePopReq, TLogData* self, Reference<LogData> logData) { if (self->ignorePopUid != enablePopReq.snapUID.toString()) { TraceEvent(SevWarn, "TLogPopDisableEnableUidMismatch") .detail("IgnorePopUid", self->ignorePopUid) .detail("UidStr", enablePopReq.snapUID.toString()); enablePopReq.reply.sendError(operation_failed()); return Void(); } TraceEvent("EnableTLogPlayAllIgnoredPops2") .detail("UidStr", enablePopReq.snapUID.toString()) .detail("IgnorePopUid", self->ignorePopUid) .detail("IgnorePopRequest", self->ignorePopRequest) .detail("IgnorePopDeadline", self->ignorePopDeadline) .detail("PersistentDataVersion", logData->persistentDataVersion) .detail("PersistentDataDurableVersion", logData->persistentDataDurableVersion) .detail("QueueCommittedVersion", logData->queueCommittedVersion.get()) .detail("Version", logData->version.get()); wait(processPopRequests(self, logData)); enablePopReq.reply.send(Void()); return Void(); } ACTOR Future<Void> serveTLogInterface(TLogData* self, TLogInterface tli, Reference<LogData> logData, PromiseStream<Void> warningCollectorInput) { state Future<Void> dbInfoChange = Void(); loop choose { when(wait(dbInfoChange)) { dbInfoChange = self->dbInfo->onChange(); bool found = false; if (self->dbInfo->get().recoveryState >= RecoveryState::ACCEPTING_COMMITS) { for (auto& logs : self->dbInfo->get().logSystemConfig.tLogs) { if (std::count(logs.tLogs.begin(), logs.tLogs.end(), logData->logId)) { found = true; break; } } } if (found && self->dbInfo->get().logSystemConfig.recruitmentID == logData->recruitmentID) { logData->logSystem->set(ILogSystem::fromServerDBInfo(self->dbgid, self->dbInfo->get())); if (!logData->isPrimary) { logData->logSystem->get()->pop(logData->logRouterPoppedVersion, logData->remoteTag, logData->durableKnownCommittedVersion, logData->locality); } if (!logData->isPrimary && logData->stopped) { TraceEvent("TLogAlreadyStopped", self->dbgid).detail("LogId", logData->logId); logData->removed = logData->removed && logData->logSystem->get()->endEpoch(); } } else { logData->logSystem->set(Reference<ILogSystem>()); } } when(TLogPeekRequest req = waitNext(tli.peekMessages.getFuture())) { logData->addActor.send(tLogPeekMessages(self, req, logData)); } when(TLogPopRequest req = waitNext(tli.popMessages.getFuture())) { logData->addActor.send(tLogPop(self, req, logData)); } when(TLogCommitRequest req = waitNext(tli.commit.getFuture())) { //TraceEvent("TLogCommitReq", logData->logId).detail("Ver", req.version).detail("PrevVer", req.prevVersion).detail("LogVer", logData->version.get()); ASSERT(logData->isPrimary); TEST(logData->stopped); // TLogCommitRequest while stopped if (!logData->stopped) logData->addActor.send(tLogCommit(self, req, logData, warningCollectorInput)); else req.reply.sendError(tlog_stopped()); } when(ReplyPromise<TLogLockResult> reply = waitNext(tli.lock.getFuture())) { logData->addActor.send(tLogLock(self, reply, logData)); } when(TLogQueuingMetricsRequest req = waitNext(tli.getQueuingMetrics.getFuture())) { getQueuingMetrics(self, logData, req); } when(TLogConfirmRunningRequest req = waitNext(tli.confirmRunning.getFuture())) { if (req.debugID.present()) { UID tlogDebugID = nondeterministicRandom()->randomUniqueID(); g_traceBatch.addAttach("TransactionAttachID", req.debugID.get().first(), tlogDebugID.first()); g_traceBatch.addEvent("TransactionDebug", tlogDebugID.first(), "TLogServer.TLogConfirmRunningRequest"); } if (!logData->stopped) req.reply.send(Void()); else req.reply.sendError(tlog_stopped()); } when(TLogDisablePopRequest req = waitNext(tli.disablePopRequest.getFuture())) { if (self->ignorePopUid != "") { TraceEvent(SevWarn, "TLogPopDisableonDisable") .detail("IgnorePopUid", self->ignorePopUid) .detail("UidStr", req.snapUID.toString()) .detail("PersistentDataVersion", logData->persistentDataVersion) .detail("PersistentDatadurableVersion", logData->persistentDataDurableVersion) .detail("QueueCommittedVersion", logData->queueCommittedVersion.get()) .detail("Version", logData->version.get()); req.reply.sendError(operation_failed()); } else { // FIXME: As part of reverting snapshot V1, make ignorePopUid a UID instead of string self->ignorePopRequest = true; self->ignorePopUid = req.snapUID.toString(); self->ignorePopDeadline = g_network->now() + SERVER_KNOBS->TLOG_IGNORE_POP_AUTO_ENABLE_DELAY; req.reply.send(Void()); } } when(TLogEnablePopRequest enablePopReq = waitNext(tli.enablePopRequest.getFuture())) { logData->addActor.send(tLogEnablePopReq(enablePopReq, self, logData)); } when(TLogSnapRequest snapReq = waitNext(tli.snapRequest.getFuture())) { logData->addActor.send(tLogSnapCreate(snapReq, self, logData)); } when(wait(self->ignorePopRequest ? delayUntil(self->ignorePopDeadline) : Never())) { TEST(true); // Hit ignorePopDeadline TraceEvent("EnableTLogPlayAllIgnoredPops").detail("IgnoredPopDeadline", self->ignorePopDeadline); logData->addActor.send(processPopRequests(self, logData)); } } } void removeLog(TLogData* self, Reference<LogData> logData) { TraceEvent("TLogRemoved", self->dbgid) .detail("LogId", logData->logId) .detail("Input", logData->bytesInput.getValue()) .detail("Durable", logData->bytesDurable.getValue()); logData->stopped = true; if (!logData->recoveryComplete.isSet()) { logData->recoveryComplete.sendError(end_of_stream()); } logData->addActor = PromiseStream<Future<Void>>(); // there could be items still in the promise stream if one of the // actors threw an error immediately self->id_data.erase(logData->logId); while (self->popOrder.size() && !self->id_data.count(self->popOrder.front())) { self->popOrder.pop_front(); } if (self->id_data.size() == 0) { throw worker_removed(); } } // remote tLog pull data from log routers ACTOR Future<Void> pullAsyncData(TLogData* self, Reference<LogData> logData, std::vector<Tag> tags, Version beginVersion, Optional<Version> endVersion, bool poppedIsKnownCommitted) { state Future<Void> dbInfoChange = Void(); state Reference<ILogSystem::IPeekCursor> r; state Version tagAt = beginVersion; state Version lastVer = 0; if (endVersion.present()) { TraceEvent("TLogRestoreReplicationFactor", self->dbgid) .detail("LogId", logData->logId) .detail("Locality", logData->locality) .detail("RecoverFrom", beginVersion) .detail("RecoverTo", endVersion.get()); } while (!endVersion.present() || logData->version.get() < endVersion.get()) { loop { choose { when(wait(r ? r->getMore(TaskPriority::TLogCommit) : Never())) { break; } when(wait(dbInfoChange)) { if (logData->logSystem->get()) { r = logData->logSystem->get()->peek(logData->logId, tagAt, endVersion, tags, true); } else { r = Reference<ILogSystem::IPeekCursor>(); } dbInfoChange = logData->logSystem->onChange(); } } } state double waitStartT = 0; while (self->bytesInput - self->bytesDurable >= SERVER_KNOBS->TLOG_HARD_LIMIT_BYTES && !logData->stopped) { if (now() - waitStartT >= 1) { TraceEvent(SevWarn, "TLogUpdateLag", logData->logId) .detail("Version", logData->version.get()) .detail("PersistentDataVersion", logData->persistentDataVersion) .detail("PersistentDataDurableVersion", logData->persistentDataDurableVersion); waitStartT = now(); } wait(delayJittered(.005, TaskPriority::TLogCommit)); } state Version ver = 0; state std::vector<TagsAndMessage> messages; loop { state bool foundMessage = r->hasMessage(); if (!foundMessage || r->version().version != ver) { ASSERT(r->version().version > lastVer); if (ver) { if (logData->stopped || (endVersion.present() && ver > endVersion.get())) { return Void(); } if (poppedIsKnownCommitted) { logData->knownCommittedVersion = std::max(logData->knownCommittedVersion, r->popped()); logData->minKnownCommittedVersion = std::max(logData->minKnownCommittedVersion, r->getMinKnownCommittedVersion()); } commitMessages(self, logData, ver, messages); if (self->terminated.isSet()) { return Void(); } // Log the changes to the persistent queue, to be committed by commitQueue() AlternativeTLogQueueEntryRef qe; qe.version = ver; qe.knownCommittedVersion = logData->knownCommittedVersion; qe.alternativeMessages = &messages; qe.id = logData->logId; self->persistentQueue->push(qe, logData); self->diskQueueCommitBytes += qe.expectedSize(); if (self->diskQueueCommitBytes > SERVER_KNOBS->MAX_QUEUE_COMMIT_BYTES) { self->largeDiskQueueCommitBytes.set(true); } // Notifies the commitQueue actor to commit persistentQueue, and also unblocks tLogPeekMessages // actors logData->version.set(ver); wait(yield(TaskPriority::TLogCommit)); } lastVer = ver; ver = r->version().version; messages.clear(); if (!foundMessage) { ver--; if (ver > logData->version.get()) { if (logData->stopped || (endVersion.present() && ver > endVersion.get())) { return Void(); } if (poppedIsKnownCommitted) { logData->knownCommittedVersion = std::max(logData->knownCommittedVersion, r->popped()); logData->minKnownCommittedVersion = std::max(logData->minKnownCommittedVersion, r->getMinKnownCommittedVersion()); } if (self->terminated.isSet()) { return Void(); } // Log the changes to the persistent queue, to be committed by commitQueue() TLogQueueEntryRef qe; qe.version = ver; qe.knownCommittedVersion = logData->knownCommittedVersion; qe.messages = StringRef(); qe.id = logData->logId; self->persistentQueue->push(qe, logData); self->diskQueueCommitBytes += qe.expectedSize(); if (self->diskQueueCommitBytes > SERVER_KNOBS->MAX_QUEUE_COMMIT_BYTES) { self->largeDiskQueueCommitBytes.set(true); } // Notifies the commitQueue actor to commit persistentQueue, and also unblocks tLogPeekMessages // actors logData->version.set(ver); wait(yield(TaskPriority::TLogCommit)); } break; } } messages.emplace_back(r->getMessageWithTags(), r->getTags()); r->nextMessage(); } tagAt = std::max(r->version().version, logData->version.get() + 1); } return Void(); } ACTOR Future<Void> tLogCore(TLogData* self, Reference<LogData> logData, TLogInterface tli, bool pulledRecoveryVersions) { if (logData->removed.isReady()) { wait(delay(0)); // to avoid iterator invalidation in restorePersistentState when removed is already ready ASSERT(logData->removed.isError()); if (logData->removed.getError().code() != error_code_worker_removed) { throw logData->removed.getError(); } removeLog(self, logData); return Void(); } state PromiseStream<Void> warningCollectorInput; state Future<Void> warningCollector = timeoutWarningCollector(warningCollectorInput.getFuture(), 1.0, "TLogQueueCommitSlow", self->dbgid); state Future<Void> error = actorCollection(logData->addActor.getFuture()); logData->addActor.send(waitFailureServer(tli.waitFailure.getFuture())); logData->addActor.send(logData->removed); // FIXME: update tlogMetrics to include new information, or possibly only have one copy for the shared instance logData->addActor.send(traceCounters("TLogMetrics", logData->logId, SERVER_KNOBS->STORAGE_LOGGING_DELAY, &logData->cc, logData->logId.toString() + "/TLogMetrics", [self=self](TraceEvent& te) { StorageBytes sbTlog = self->persistentData->getStorageBytes(); te.detail("KvstoreBytesUsed", sbTlog.used); te.detail("KvstoreBytesFree", sbTlog.free); te.detail("KvstoreBytesAvailable", sbTlog.available); te.detail("KvstoreBytesTotal", sbTlog.total); te.detail("KvstoreBytesTemp", sbTlog.temp); StorageBytes sbQueue = self->rawPersistentQueue->getStorageBytes(); te.detail("QueueDiskBytesUsed", sbQueue.used); te.detail("QueueDiskBytesFree", sbQueue.free); te.detail("QueueDiskBytesAvailable", sbQueue.available); te.detail("QueueDiskBytesTotal", sbQueue.total); te.detail("QueueDiskBytesTemp", sbQueue.temp); })); logData->addActor.send(serveTLogInterface(self, tli, logData, warningCollectorInput)); logData->addActor.send(cleanupPeekTrackers(logData.getPtr())); logData->addActor.send(logPeekTrackers(logData.getPtr())); if (!logData->isPrimary) { std::vector<Tag> tags; tags.push_back(logData->remoteTag); logData->addActor.send( pullAsyncData(self, logData, tags, pulledRecoveryVersions ? logData->recoveredAt + 1 : logData->unrecoveredBefore, Optional<Version>(), true)); } try { wait(error); throw internal_error(); } catch (Error& e) { if (e.code() != error_code_worker_removed) throw; removeLog(self, logData); return Void(); } } ACTOR Future<Void> checkEmptyQueue(TLogData* self) { TraceEvent("TLogCheckEmptyQueueBegin", self->dbgid); try { bool recoveryFinished = wait(self->persistentQueue->initializeRecovery(0)); if (recoveryFinished) return Void(); TLogQueueEntry r = wait(self->persistentQueue->readNext(self)); throw internal_error(); } catch (Error& e) { if (e.code() != error_code_end_of_stream) throw; TraceEvent("TLogCheckEmptyQueueEnd", self->dbgid); return Void(); } } ACTOR Future<Void> checkRecovered(TLogData* self) { TraceEvent("TLogCheckRecoveredBegin", self->dbgid); Optional<Value> v = wait(self->persistentData->readValue(StringRef())); TraceEvent("TLogCheckRecoveredEnd", self->dbgid); return Void(); } // Recovery persistent state of tLog from disk ACTOR Future<Void> restorePersistentState(TLogData* self, LocalityData locality, Promise<Void> oldLog, Promise<Void> recovered, PromiseStream<InitializeTLogRequest> tlogRequests) { state double startt = now(); state Reference<LogData> logData; state KeyRange tagKeys; // PERSIST: Read basic state from persistentData; replay persistentQueue but don't erase it TraceEvent("TLogRestorePersistentState", self->dbgid); state IKeyValueStore* storage = self->persistentData; wait(storage->init()); state Future<Optional<Value>> fFormat = storage->readValue(persistFormat.key); state Future<Optional<Value>> fRecoveryLocation = storage->readValue(persistRecoveryLocationKey); state Future<RangeResult> fVers = storage->readRange(persistCurrentVersionKeys); state Future<RangeResult> fKnownCommitted = storage->readRange(persistKnownCommittedVersionKeys); state Future<RangeResult> fLocality = storage->readRange(persistLocalityKeys); state Future<RangeResult> fLogRouterTags = storage->readRange(persistLogRouterTagsKeys); state Future<RangeResult> fTxsTags = storage->readRange(persistTxsTagsKeys); state Future<RangeResult> fRecoverCounts = storage->readRange(persistRecoveryCountKeys); state Future<RangeResult> fProtocolVersions = storage->readRange(persistProtocolVersionKeys); state Future<RangeResult> fTLogSpillTypes = storage->readRange(persistTLogSpillTypeKeys); // FIXME: metadata in queue? wait(waitForAll(std::vector{ fFormat, fRecoveryLocation })); wait(waitForAll(std::vector{ fVers, fKnownCommitted, fLocality, fLogRouterTags, fTxsTags, fRecoverCounts, fProtocolVersions, fTLogSpillTypes })); if (fFormat.get().present() && !persistFormatReadableRange.contains(fFormat.get().get())) { // FIXME: remove when we no longer need to test upgrades from 4.X releases if (g_network->isSimulated()) { TraceEvent("ElapsedTime").detail("SimTime", now()).detail("RealTime", 0).detail("RandomUnseed", 0); flushAndExit(0); } TraceEvent(SevError, "UnsupportedDBFormat", self->dbgid) .detail("Format", fFormat.get().get()) .detail("Expected", persistFormat.value.toString()); throw worker_recovery_failed(); } if (!fFormat.get().present()) { RangeResult v = wait(self->persistentData->readRange(KeyRangeRef(StringRef(), LiteralStringRef("\xff")), 1)); if (!v.size()) { TEST(true); // The DB is completely empty, so it was never initialized. Delete it. throw worker_removed(); } else { // This should never happen TraceEvent(SevError, "NoDBFormatKey", self->dbgid).detail("FirstKey", v[0].key); ASSERT(false); throw worker_recovery_failed(); } } state std::vector<Future<ErrorOr<Void>>> removed; ASSERT(fFormat.get().get() == LiteralStringRef("FoundationDB/LogServer/3/0")); ASSERT(fVers.get().size() == fRecoverCounts.get().size()); state std::map<UID, int8_t> id_locality; for (auto it : fLocality.get()) { id_locality[BinaryReader::fromStringRef<UID>(it.key.removePrefix(persistLocalityKeys.begin), Unversioned())] = BinaryReader::fromStringRef<int8_t>(it.value, Unversioned()); } state std::map<UID, int> id_logRouterTags; for (auto it : fLogRouterTags.get()) { id_logRouterTags[BinaryReader::fromStringRef<UID>(it.key.removePrefix(persistLogRouterTagsKeys.begin), Unversioned())] = BinaryReader::fromStringRef<int>(it.value, Unversioned()); } state std::map<UID, int> id_txsTags; for (auto it : fTxsTags.get()) { id_txsTags[BinaryReader::fromStringRef<UID>(it.key.removePrefix(persistTxsTagsKeys.begin), Unversioned())] = BinaryReader::fromStringRef<int>(it.value, Unversioned()); } state std::map<UID, Version> id_knownCommitted; for (auto it : fKnownCommitted.get()) { id_knownCommitted[BinaryReader::fromStringRef<UID>(it.key.removePrefix(persistKnownCommittedVersionKeys.begin), Unversioned())] = BinaryReader::fromStringRef<Version>(it.value, Unversioned()); } state IDiskQueue::location minimumRecoveryLocation = 0; if (fRecoveryLocation.get().present()) { minimumRecoveryLocation = BinaryReader::fromStringRef<IDiskQueue::location>(fRecoveryLocation.get().get(), Unversioned()); } state int idx = 0; state Promise<Void> registerWithMaster; state std::map<UID, TLogInterface> id_interf; state std::vector<std::pair<Version, UID>> logsByVersion; for (idx = 0; idx < fVers.get().size(); idx++) { state KeyRef rawId = fVers.get()[idx].key.removePrefix(persistCurrentVersionKeys.begin); UID id1 = BinaryReader::fromStringRef<UID>(rawId, Unversioned()); UID id2 = BinaryReader::fromStringRef<UID>( fRecoverCounts.get()[idx].key.removePrefix(persistRecoveryCountKeys.begin), Unversioned()); ASSERT(id1 == id2); TLogInterface recruited(id1, self->dbgid, locality); recruited.initEndpoints(); DUMPTOKEN(recruited.peekMessages); DUMPTOKEN(recruited.popMessages); DUMPTOKEN(recruited.commit); DUMPTOKEN(recruited.lock); DUMPTOKEN(recruited.getQueuingMetrics); DUMPTOKEN(recruited.confirmRunning); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.recoveryFinished); DUMPTOKEN(recruited.disablePopRequest); DUMPTOKEN(recruited.enablePopRequest); DUMPTOKEN(recruited.snapRequest); ProtocolVersion protocolVersion = BinaryReader::fromStringRef<ProtocolVersion>(fProtocolVersions.get()[idx].value, Unversioned()); TLogSpillType logSpillType = BinaryReader::fromStringRef<TLogSpillType>(fTLogSpillTypes.get()[idx].value, AssumeVersion(protocolVersion)); // We do not need the remoteTag, because we will not be loading any additional data logData = makeReference<LogData>(self, recruited, Tag(), true, id_logRouterTags[id1], id_txsTags[id1], UID(), protocolVersion, logSpillType, std::vector<Tag>(), "Restored"); logData->locality = id_locality[id1]; logData->stopped = true; self->id_data[id1] = logData; id_interf[id1] = recruited; logData->knownCommittedVersion = id_knownCommitted[id1]; Version ver = BinaryReader::fromStringRef<Version>(fVers.get()[idx].value, Unversioned()); logData->persistentDataVersion = ver; logData->persistentDataDurableVersion = ver; logData->version.set(ver); logData->recoveryCount = BinaryReader::fromStringRef<DBRecoveryCount>(fRecoverCounts.get()[idx].value, Unversioned()); logData->removed = rejoinMasters(self, recruited, logData->recoveryCount, registerWithMaster.getFuture(), false); removed.push_back(errorOr(logData->removed)); logsByVersion.emplace_back(ver, id1); TraceEvent("TLogPersistentStateRestore", self->dbgid) .detail("LogId", logData->logId) .detail("Ver", ver) .detail("RecoveryCount", logData->recoveryCount); // Restore popped keys. Pop operations that took place after the last (committed) updatePersistentDataVersion // might be lost, but that is fine because we will get the corresponding data back, too. tagKeys = prefixRange(rawId.withPrefix(persistTagPoppedKeys.begin)); loop { if (logData->removed.isReady()) break; RangeResult data = wait(self->persistentData->readRange(tagKeys, BUGGIFY ? 3 : 1 << 30, 1 << 20)); if (!data.size()) break; ((KeyRangeRef&)tagKeys) = KeyRangeRef(keyAfter(data.back().key, tagKeys.arena()), tagKeys.end); for (auto& kv : data) { Tag tag = decodeTagPoppedKey(rawId, kv.key); Version popped = decodeTagPoppedValue(kv.value); TraceEvent("TLogRestorePopped", logData->logId).detail("Tag", tag.toString()).detail("To", popped); auto tagData = logData->getTagData(tag); ASSERT(!tagData); logData->createTagData(tag, popped, false, false, false); logData->getTagData(tag)->persistentPopped = popped; } } } std::sort(logsByVersion.begin(), logsByVersion.end()); for (const auto& pair : logsByVersion) { // TLogs that have been fully spilled won't have queue entries read in the loop below. self->popOrder.push_back(pair.second); } logsByVersion.clear(); state Future<Void> allRemoved = waitForAll(removed); state UID lastId = UID(1, 1); // initialized so it will not compare equal to a default UID state double recoverMemoryLimit = SERVER_KNOBS->TLOG_RECOVER_MEMORY_LIMIT; if (BUGGIFY) recoverMemoryLimit = std::max<double>(SERVER_KNOBS->BUGGIFY_RECOVER_MEMORY_LIMIT, (double)SERVER_KNOBS->TLOG_SPILL_THRESHOLD); try { bool recoveryFinished = wait(self->persistentQueue->initializeRecovery(minimumRecoveryLocation)); if (recoveryFinished) throw end_of_stream(); loop { if (allRemoved.isReady()) { TEST(true); // all tlogs removed during queue recovery throw worker_removed(); } choose { when(TLogQueueEntry qe = wait(self->persistentQueue->readNext(self))) { if (qe.id != lastId) { lastId = qe.id; auto it = self->id_data.find(qe.id); if (it != self->id_data.end()) { logData = it->second; } else { logData = Reference<LogData>(); } } //TraceEvent("TLogRecoveredQE", self->dbgid).detail("LogId", qe.id).detail("Ver", qe.version).detail("MessageBytes", qe.messages.size()).detail("Tags", qe.tags.size()) // .detail("Tag0", qe.tags.size() ? qe.tags[0].tag : invalidTag).detail("Version", // logData->version.get()); if (logData) { if (!self->spillOrder.size() || self->spillOrder.back() != qe.id) { self->spillOrder.push_back(qe.id); } logData->knownCommittedVersion = std::max(logData->knownCommittedVersion, qe.knownCommittedVersion); if (qe.version > logData->version.get()) { commitMessages(self, logData, qe.version, qe.arena(), qe.messages); logData->version.set(qe.version); logData->queueCommittedVersion.set(qe.version); while (self->bytesInput - self->bytesDurable >= recoverMemoryLimit) { TEST(true); // Flush excess data during TLog queue recovery TraceEvent("FlushLargeQueueDuringRecovery", self->dbgid) .detail("LogId", logData->logId) .detail("BytesInput", self->bytesInput) .detail("BytesDurable", self->bytesDurable) .detail("Version", logData->version.get()) .detail("PVer", logData->persistentDataVersion); choose { when(wait(updateStorage(self))) {} when(wait(allRemoved)) { throw worker_removed(); } } } } else { // Updating persistRecoveryLocation and persistCurrentVersion at the same time, // transactionally, should mean that we never read any TLogQueueEntry that has already // been spilled. ASSERT_WE_THINK(qe.version == logData->version.get()); } } } when(wait(allRemoved)) { throw worker_removed(); } } } } catch (Error& e) { if (e.code() != error_code_end_of_stream) throw; } TraceEvent("TLogRestorePersistentStateDone", self->dbgid).detail("Took", now() - startt); TEST(now() - startt >= 1.0); // TLog recovery took more than 1 second for (auto it : self->id_data) { if (it.second->queueCommittedVersion.get() == 0) { TraceEvent("TLogZeroVersion", self->dbgid).detail("LogId", it.first); it.second->queueCommittedVersion.set(it.second->version.get()); } it.second->recoveryComplete.sendError(end_of_stream()); self->sharedActors.send(tLogCore(self, it.second, id_interf[it.first], false)); } if (registerWithMaster.canBeSet()) registerWithMaster.send(Void()); return Void(); } bool tlogTerminated(TLogData* self, IKeyValueStore* persistentData, TLogQueue* persistentQueue, Error const& e) { // Dispose the IKVS (destroying its data permanently) only if this shutdown is definitely permanent. Otherwise just // close it. if (e.code() == error_code_worker_removed || e.code() == error_code_recruitment_failed) { persistentData->dispose(); persistentQueue->dispose(); } else { persistentData->close(); persistentQueue->close(); } if (e.code() == error_code_worker_removed || e.code() == error_code_recruitment_failed || e.code() == error_code_file_not_found) { TraceEvent("TLogTerminated", self->dbgid).error(e, true); return true; } else return false; } ACTOR Future<Void> updateLogSystem(TLogData* self, Reference<LogData> logData, LogSystemConfig recoverFrom, Reference<AsyncVar<Reference<ILogSystem>>> logSystem) { loop { bool found = self->dbInfo->get().logSystemConfig.recruitmentID == logData->recruitmentID; if (found) { if (self->dbInfo->get().logSystemConfig.isNextGenerationOf(recoverFrom)) { logSystem->set(ILogSystem::fromOldLogSystemConfig( logData->logId, self->dbInfo->get().myLocality, self->dbInfo->get().logSystemConfig)); } else if (self->dbInfo->get().logSystemConfig.isEqualIds(recoverFrom)) { logSystem->set(ILogSystem::fromLogSystemConfig( logData->logId, self->dbInfo->get().myLocality, self->dbInfo->get().logSystemConfig, false, true)); } else if (self->dbInfo->get().recoveryState >= RecoveryState::ACCEPTING_COMMITS) { logSystem->set(ILogSystem::fromLogSystemConfig( logData->logId, self->dbInfo->get().myLocality, self->dbInfo->get().logSystemConfig, true)); } else { found = false; } } if (!found) { logSystem->set(Reference<ILogSystem>()); } else { logData->logSystem->get()->pop(logData->logRouterPoppedVersion, logData->remoteTag, logData->durableKnownCommittedVersion, logData->locality); } TraceEvent("TLogUpdate", self->dbgid) .detail("LogId", logData->logId) .detail("RecruitmentID", logData->recruitmentID) .detail("DbRecruitmentID", self->dbInfo->get().logSystemConfig.recruitmentID) .detail("RecoverFrom", recoverFrom.toString()) .detail("DbInfo", self->dbInfo->get().logSystemConfig.toString()) .detail("Found", found) .detail("LogSystem", (bool)logSystem->get()) .detail("RecoveryState", (int)self->dbInfo->get().recoveryState); for (const auto& it : self->dbInfo->get().logSystemConfig.oldTLogs) { TraceEvent("TLogUpdateOld", self->dbgid).detail("LogId", logData->logId).detail("DbInfo", it.toString()); } wait(self->dbInfo->onChange()); } } void stopAllTLogs(TLogData* self, UID newLogId) { for (auto it : self->id_data) { if (!it.second->stopped) { TraceEvent("TLogStoppedByNewRecruitment", self->dbgid) .detail("LogId", it.second->logId) .detail("StoppedId", it.first.toString()) .detail("RecruitedId", newLogId) .detail("EndEpoch", it.second->logSystem->get().getPtr() != 0); if (!it.second->isPrimary && it.second->logSystem->get()) { it.second->removed = it.second->removed && it.second->logSystem->get()->endEpoch(); } if (it.second->committingQueue.canBeSet()) { it.second->committingQueue.sendError(worker_removed()); } } it.second->stopped = true; if (!it.second->recoveryComplete.isSet()) { it.second->recoveryComplete.sendError(end_of_stream()); } it.second->stopCommit.trigger(); } } // Start the tLog role for a worker ACTOR Future<Void> tLogStart(TLogData* self, InitializeTLogRequest req, LocalityData locality) { state TLogInterface recruited(self->dbgid, locality); recruited.initEndpoints(); DUMPTOKEN(recruited.peekMessages); DUMPTOKEN(recruited.popMessages); DUMPTOKEN(recruited.commit); DUMPTOKEN(recruited.lock); DUMPTOKEN(recruited.getQueuingMetrics); DUMPTOKEN(recruited.confirmRunning); DUMPTOKEN(recruited.waitFailure); DUMPTOKEN(recruited.recoveryFinished); DUMPTOKEN(recruited.disablePopRequest); DUMPTOKEN(recruited.enablePopRequest); DUMPTOKEN(recruited.snapRequest); stopAllTLogs(self, recruited.id()); bool recovering = (req.recoverFrom.logSystemType == LogSystemType::tagPartitioned); state Reference<LogData> logData = makeReference<LogData>(self, recruited, req.remoteTag, req.isPrimary, req.logRouterTags, req.txsTags, req.recruitmentID, g_network->protocolVersion(), req.spillType, req.allTags, recovering ? "Recovered" : "Recruited"); self->id_data[recruited.id()] = logData; logData->locality = req.locality; logData->recoveryCount = req.epoch; logData->removed = rejoinMasters(self, recruited, req.epoch, Future<Void>(Void()), req.isPrimary); self->popOrder.push_back(recruited.id()); self->spillOrder.push_back(recruited.id()); TraceEvent("TLogStart", logData->logId).detail("RecoveryCount", logData->recoveryCount); state Future<Void> updater; state bool pulledRecoveryVersions = false; try { if (logData->removed.isReady()) { throw logData->removed.getError(); } if (recovering) { logData->unrecoveredBefore = req.startVersion; logData->recoveredAt = req.recoverAt; logData->knownCommittedVersion = req.startVersion - 1; logData->persistentDataVersion = logData->unrecoveredBefore - 1; logData->persistentDataDurableVersion = logData->unrecoveredBefore - 1; logData->queueCommittedVersion.set(logData->unrecoveredBefore - 1); logData->version.set(logData->unrecoveredBefore - 1); logData->unpoppedRecoveredTags = req.allTags.size(); wait(initPersistentState(self, logData) || logData->removed); TraceEvent("TLogRecover", self->dbgid) .detail("LogId", logData->logId) .detail("At", req.recoverAt) .detail("Known", req.knownCommittedVersion) .detail("Unrecovered", logData->unrecoveredBefore) .detail("Tags", describe(req.recoverTags)) .detail("Locality", req.locality) .detail("LogRouterTags", logData->logRouterTags); if (logData->recoveryComplete.isSet()) { throw worker_removed(); } updater = updateLogSystem(self, logData, req.recoverFrom, logData->logSystem); logData->initialized = true; self->newLogData.trigger(); if ((req.isPrimary || req.recoverFrom.logRouterTags == 0) && !logData->stopped && logData->unrecoveredBefore <= req.recoverAt) { if (req.recoverFrom.logRouterTags > 0 && req.locality != tagLocalitySatellite) { logData->logRouterPopToVersion = req.recoverAt; std::vector<Tag> tags; tags.push_back(logData->remoteTag); wait(pullAsyncData(self, logData, tags, logData->unrecoveredBefore, req.recoverAt, true) || logData->removed); } else if (!req.recoverTags.empty()) { ASSERT(logData->unrecoveredBefore > req.knownCommittedVersion); wait(pullAsyncData( self, logData, req.recoverTags, req.knownCommittedVersion + 1, req.recoverAt, false) || logData->removed); } pulledRecoveryVersions = true; logData->knownCommittedVersion = req.recoverAt; } if ((req.isPrimary || req.recoverFrom.logRouterTags == 0) && logData->version.get() < req.recoverAt && !logData->stopped) { // Log the changes to the persistent queue, to be committed by commitQueue() TLogQueueEntryRef qe; qe.version = req.recoverAt; qe.knownCommittedVersion = logData->knownCommittedVersion; qe.messages = StringRef(); qe.id = logData->logId; self->persistentQueue->push(qe, logData); self->diskQueueCommitBytes += qe.expectedSize(); if (self->diskQueueCommitBytes > SERVER_KNOBS->MAX_QUEUE_COMMIT_BYTES) { self->largeDiskQueueCommitBytes.set(true); } logData->version.set(req.recoverAt); } if (logData->recoveryComplete.isSet()) { throw worker_removed(); } logData->addActor.send(respondToRecovered(recruited, logData->recoveryComplete)); } else { // Brand new tlog, initialization has already been done by caller wait(initPersistentState(self, logData) || logData->removed); if (logData->recoveryComplete.isSet()) { throw worker_removed(); } logData->initialized = true; self->newLogData.trigger(); logData->recoveryComplete.send(Void()); } wait(logData->committingQueue.getFuture() || logData->removed); } catch (Error& e) { req.reply.sendError(recruitment_failed()); if (e.code() != error_code_worker_removed) { throw; } wait(delay(0.0)); // if multiple recruitment requests were already in the promise stream make sure they are all // started before any are removed removeLog(self, logData); return Void(); } req.reply.send(recruited); TraceEvent("TLogReady", logData->logId) .detail("AllTags", describe(req.allTags)) .detail("Locality", logData->locality); updater = Void(); wait(tLogCore(self, logData, recruited, pulledRecoveryVersions)); return Void(); } ACTOR Future<Void> startSpillingInTenSeconds(TLogData* self, UID tlogId, Reference<AsyncVar<UID>> activeSharedTLog) { wait(delay(10)); if (activeSharedTLog->get() != tlogId) { // TODO: This should fully spill, but currently doing so will cause us to no longer update poppedVersion // and QuietDatabase will hang thinking our TLog is behind. TraceEvent("SharedTLogBeginSpilling", self->dbgid).detail("NowActive", activeSharedTLog->get()); self->targetVolatileBytes = SERVER_KNOBS->REFERENCE_SPILL_UPDATE_STORAGE_BYTE_LIMIT * 2; } else { TraceEvent("SharedTLogSkipSpilling", self->dbgid).detail("NowActive", activeSharedTLog->get()); } return Void(); } // New tLog (if !recoverFrom.size()) or restore from network ACTOR Future<Void> tLog(IKeyValueStore* persistentData, IDiskQueue* persistentQueue, Reference<AsyncVar<ServerDBInfo> const> db, LocalityData locality, PromiseStream<InitializeTLogRequest> tlogRequests, UID tlogId, UID workerID, bool restoreFromDisk, Promise<Void> oldLog, Promise<Void> recovered, std::string folder, Reference<AsyncVar<bool>> degraded, Reference<AsyncVar<UID>> activeSharedTLog) { state TLogData self(tlogId, workerID, persistentData, persistentQueue, db, degraded, folder); state Future<Void> error = actorCollection(self.sharedActors.getFuture()); TraceEvent("SharedTlog", tlogId); try { if (restoreFromDisk) { wait(restorePersistentState(&self, locality, oldLog, recovered, tlogRequests)); } else { wait(ioTimeoutError(checkEmptyQueue(&self) && checkRecovered(&self), SERVER_KNOBS->TLOG_MAX_CREATE_DURATION)); } // Disk errors need a chance to kill this actor. wait(delay(0.000001)); if (recovered.canBeSet()) recovered.send(Void()); self.sharedActors.send(commitQueue(&self)); self.sharedActors.send(updateStorageLoop(&self)); self.sharedActors.send(traceRole(Role::SHARED_TRANSACTION_LOG, tlogId)); state Future<Void> activeSharedChange = Void(); loop { choose { when(InitializeTLogRequest req = waitNext(tlogRequests.getFuture())) { if (!self.tlogCache.exists(req.recruitmentID)) { self.tlogCache.set(req.recruitmentID, req.reply.getFuture()); self.sharedActors.send( self.tlogCache.removeOnReady(req.recruitmentID, tLogStart(&self, req, locality))); } else { forwardPromise(req.reply, self.tlogCache.get(req.recruitmentID)); } } when(wait(error)) { throw internal_error(); } when(wait(activeSharedChange)) { if (activeSharedTLog->get() == tlogId) { TraceEvent("SharedTLogNowActive", self.dbgid).detail("NowActive", activeSharedTLog->get()); self.targetVolatileBytes = SERVER_KNOBS->TLOG_SPILL_THRESHOLD; } else { stopAllTLogs(&self, tlogId); TraceEvent("SharedTLogQueueSpilling", self.dbgid).detail("NowActive", activeSharedTLog->get()); self.sharedActors.send(startSpillingInTenSeconds(&self, tlogId, activeSharedTLog)); } activeSharedChange = activeSharedTLog->onChange(); } } } } catch (Error& e) { self.terminated.send(Void()); TraceEvent("TLogError", tlogId).error(e, true); if (recovered.canBeSet()) recovered.send(Void()); while (!tlogRequests.isEmpty()) { tlogRequests.getFuture().pop().reply.sendError(recruitment_failed()); } for (auto& it : self.id_data) { if (!it.second->recoveryComplete.isSet()) { it.second->recoveryComplete.sendError(end_of_stream()); } } if (tlogTerminated(&self, persistentData, self.persistentQueue, e)) { return Void(); } else { throw; } } } // UNIT TESTS struct DequeAllocatorStats { static int64_t allocatedBytes; }; int64_t DequeAllocatorStats::allocatedBytes = 0; template <class T> struct DequeAllocator : std::allocator<T> { template <typename U> struct rebind { typedef DequeAllocator<U> other; }; DequeAllocator() {} template <typename U> DequeAllocator(DequeAllocator<U> const& u) : std::allocator<T>(u) {} T* allocate(std::size_t n, std::allocator<void>::const_pointer hint = 0) { DequeAllocatorStats::allocatedBytes += n * sizeof(T); // fprintf(stderr, "Allocating %lld objects for %lld bytes (total allocated: %lld)\n", n, n * sizeof(T), // DequeAllocatorStats::allocatedBytes); return std::allocator<T>::allocate(n, hint); } void deallocate(T* p, std::size_t n) { DequeAllocatorStats::allocatedBytes -= n * sizeof(T); // fprintf(stderr, "Deallocating %lld objects for %lld bytes (total allocated: %lld)\n", n, n * sizeof(T), // DequeAllocatorStats::allocatedBytes); return std::allocator<T>::deallocate(p, n); } }; TEST_CASE("/fdbserver/tlogserver/VersionMessagesOverheadFactor") { typedef std::pair<Version, LengthPrefixedStringRef> TestType; // type used by versionMessages for (int i = 1; i < 9; ++i) { for (int j = 0; j < 20; ++j) { DequeAllocatorStats::allocatedBytes = 0; DequeAllocator<TestType> allocator; std::deque<TestType, DequeAllocator<TestType>> d(allocator); int numElements = deterministicRandom()->randomInt(pow(10, i - 1), pow(10, i)); for (int k = 0; k < numElements; ++k) { d.push_back(TestType()); } int removedElements = 0; // deterministicRandom()->randomInt(0, numElements); // FIXME: the overhead factor // does not accurately account for removal! for (int k = 0; k < removedElements; ++k) { d.pop_front(); } int64_t dequeBytes = DequeAllocatorStats::allocatedBytes + sizeof(std::deque<TestType>); int64_t insertedBytes = (numElements - removedElements) * sizeof(TestType); double overheadFactor = std::max<double>(insertedBytes, dequeBytes - 10000) / insertedBytes; // We subtract 10K here as an estimated upper bound for the fixed cost of an std::deque // fprintf(stderr, "%d elements (%d inserted, %d removed):\n", numElements-removedElements, numElements, // removedElements); fprintf(stderr, "Allocated %lld bytes to store %lld bytes (%lf overhead factor)\n", // dequeBytes, insertedBytes, overheadFactor); ASSERT(overheadFactor * 1024 <= SERVER_KNOBS->VERSION_MESSAGES_OVERHEAD_FACTOR_1024THS); } } return Void(); }
// Copyright (C) 2019. Huawei Technologies Co., Ltd. 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. #include "cpu/general/tensor_computing_general.h" template<typename T> EE clip(T* input, T* output, U32 len, T min_value, T max_value) { for (U32 i = 0; i < len; i++) { T value = input[i]; value = (value > min_value) ? value : min_value; value = (value < max_value) ? value : max_value; output[i] = value; } return SUCCESS; } EE clip_general(void *minValue, void *maxValue, TensorDesc inputDesc, void* input, TensorDesc outputDesc, void *output) { UNUSED(outputDesc); if (nullptr == minValue || nullptr == maxValue || nullptr == input || nullptr == output) CHECK_STATUS_WITH_RETURN(NULL_POINTER); EE ret = SUCCESS; switch (inputDesc.dt) { case DT_F16: { ret = clip<F16>((F16 *)input, (F16 *)output, tensorNumElements(inputDesc), *((F16 *)minValue), *((F16 *)maxValue)); break; } default: ret = NOT_SUPPORTED; break; } return ret; }
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_SWAR_FUNCTIONS_SCALAR_SPLATTED_SUM_HPP_INCLUDED #define BOOST_SIMD_SWAR_FUNCTIONS_SCALAR_SPLATTED_SUM_HPP_INCLUDED #include <boost/simd/swar/functions/splatted_sum.hpp> namespace boost { namespace simd { namespace ext { BOOST_DISPATCH_IMPLEMENT ( splatted_sum_, tag::cpu_ , (A0) , ( scalar_< unspecified_<A0> >) ) { typedef A0 result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0) const { return a0; } }; } } } #endif
/** @file utf8itor.cc * @brief iterate over a utf8 string. */ /* Copyright (C) 2006,2007,2010,2013,2015 Olly Betts * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "xapian/unicode.h" #include <cstring> using namespace std; static inline bool bad_cont(unsigned char ch) { return (ch & 0xc0) != 0x80; } namespace Xapian { namespace Unicode { // buf should be at least 4 bytes. unsigned nonascii_to_utf8(unsigned ch, char * buf) { if (ch < 0x800) { buf[0] = char(0xc0 | (ch >> 6)); buf[1] = char(0x80 | (ch & 0x3f)); return 2; } if (ch < 0x10000) { buf[0] = char(0xe0 | (ch >> 12)); buf[1] = char(0x80 | ((ch >> 6) & 0x3f)); buf[2] = char(0x80 | (ch & 0x3f)); return 3; } if (ch < 0x200000) { buf[0] = char(0xf0 | (ch >> 18)); buf[1] = char(0x80 | ((ch >> 12) & 0x3f)); buf[2] = char(0x80 | ((ch >> 6) & 0x3f)); buf[3] = char(0x80 | (ch & 0x3f)); return 4; } // Unicode doesn't specify any characters above 0x10ffff. // Should we be presented with such a numeric character // entity or similar, we just replace it with nothing. return 0; } } Utf8Iterator::Utf8Iterator(const char *p_) { assign(p_, strlen(p_)); } bool Utf8Iterator::calculate_sequence_length() const XAPIAN_NOEXCEPT { // Handle invalid UTF-8, overlong sequences, and truncated sequences as // if the text was actually in ISO-8859-1 since we need to do something // with it, and this seems the most likely reason why we'd have invalid // UTF-8. unsigned char ch = *p; seqlen = 1; // Single byte encoding (0x00-0x7f) or invalid (0x80-0xbf) or overlong // sequence (0xc0-0xc1). // // (0xc0 and 0xc1 would start 2 byte sequences for characters which are // representable in a single byte, and we should not decode these.) if (ch < 0xc2) return (ch < 0x80); if (ch < 0xe0) { if (p + 1 == end || // Not enough bytes bad_cont(p[1])) // Invalid return false; seqlen = 2; return true; } if (ch < 0xf0) { if (end - p < 3 || // Not enough bytes bad_cont(p[1]) || bad_cont(p[2]) || // Invalid (p[0] == 0xe0 && p[1] < 0xa0)) // Overlong encoding return false; seqlen = 3; return true; } if (ch >= 0xf5 || // Code value above Unicode end - p < 4 || // Not enough bytes bad_cont(p[1]) || bad_cont(p[2]) || bad_cont(p[3]) || // Invalid (p[0] == 0xf0 && p[1] < 0x90) || // Overlong encoding (p[0] == 0xf4 && p[1] >= 0x90)) // Code value above Unicode return false; seqlen = 4; return true; } unsigned Utf8Iterator::operator*() const XAPIAN_NOEXCEPT { if (p == NULL) return unsigned(-1); if (seqlen == 0) calculate_sequence_length(); unsigned char ch = *p; if (seqlen == 1) return ch; if (seqlen == 2) return ((ch & 0x1f) << 6) | (p[1] & 0x3f); if (seqlen == 3) return ((ch & 0x0f) << 12) | ((p[1] & 0x3f) << 6) | (p[2] & 0x3f); return ((ch & 0x07) << 18) | ((p[1] & 0x3f) << 12) | ((p[2] & 0x3f) << 6) | (p[3] & 0x3f); } unsigned Utf8Iterator::strict_deref() const XAPIAN_NOEXCEPT { if (p == NULL) return unsigned(-1); if (seqlen == 0) { if (!calculate_sequence_length()) return unsigned(*p) | 0x80000000; } unsigned char ch = *p; if (seqlen == 1) return ch; if (seqlen == 2) return ((ch & 0x1f) << 6) | (p[1] & 0x3f); if (seqlen == 3) return ((ch & 0x0f) << 12) | ((p[1] & 0x3f) << 6) | (p[2] & 0x3f); return ((ch & 0x07) << 18) | ((p[1] & 0x3f) << 12) | ((p[2] & 0x3f) << 6) | (p[3] & 0x3f); } }
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECorePython/ScopedGILRelease.h" #include "Gaffer/StringPlug.h" #include "GafferBindings/ValuePlugBinding.h" #include "GafferBindings/StringPlugBinding.h" using namespace boost::python; using namespace Gaffer; using namespace GafferBindings; namespace { void setValue( StringPlug *plug, const std::string& value ) { // we use a GIL release here to prevent a lock in the case where this triggers a graph // evaluation which decides to go back into python on another thread: IECorePython::ScopedGILRelease r; plug->setValue( value ); } std::string getValue( const StringPlug *plug, const IECore::MurmurHash *precomputedHash ) { // Must release GIL in case computation spawns threads which need // to reenter Python. IECorePython::ScopedGILRelease r; return plug->getValue( precomputedHash ); } std::string substitutionsRepr( unsigned substitutions ) { static const Context::Substitutions values[] = { Context::FrameSubstitutions, Context::VariableSubstitutions, Context::EscapeSubstitutions, Context::TildeSubstitutions, Context::NoSubstitutions }; static const char *names[] = { "FrameSubstitutions", "VariableSubstitutions", "EscapeSubstitutions", "TildeSubstitutions", NULL }; if( substitutions == Context::AllSubstitutions ) { return "Gaffer.Context.Substitutions.AllSubstitutions"; } else if( substitutions == Context::NoSubstitutions ) { return "Gaffer.Context.Substitutions.NoSubstitutions"; } std::string result; for( int i = 0; names[i]; ++i ) { if( substitutions & values[i] ) { if( result.size() ) { result += " | "; } result += "Gaffer.Context.Substitutions." + std::string( names[i] ); } } return result; } std::string maskedRepr( const Gaffer::StringPlug *plug, unsigned flagsMask, const Serialisation *serialisation ) { std::string extraArguments; if( plug->substitutions() != Context::AllSubstitutions ) { extraArguments = "substitutions = " + substitutionsRepr( plug->substitutions() ); } return ValuePlugSerialiser::repr( plug, flagsMask, extraArguments, serialisation ); } std::string repr( const Gaffer::StringPlug *plug ) { return maskedRepr( plug, Plug::All, NULL ); } class StringPlugSerialiser : public ValuePlugSerialiser { public : virtual std::string constructor( const Gaffer::GraphComponent *graphComponent, const Serialisation &serialisation ) const { return maskedRepr( static_cast<const StringPlug *>( graphComponent ), Plug::All & ~Plug::ReadOnly, &serialisation ); } }; } // namespace void GafferBindings::bindStringPlug() { PlugClass<StringPlug>() .def( boost::python::init<const std::string &, Gaffer::Plug::Direction, const std::string &, unsigned, unsigned>( ( boost::python::arg_( "name" )=Gaffer::GraphComponent::defaultName<StringPlug>(), boost::python::arg_( "direction" )=Gaffer::Plug::In, boost::python::arg_( "defaultValue" )="", boost::python::arg_( "flags" )=Gaffer::Plug::Default, boost::python::arg_( "substitutions" )=Gaffer::Context::AllSubstitutions ) ) ) .def( "__repr__", &repr ) .def( "substitutions", &StringPlug::substitutions ) .def( "defaultValue", &StringPlug::defaultValue, return_value_policy<boost::python::copy_const_reference>() ) .def( "setValue", &setValue ) .def( "getValue", &getValue, ( boost::python::arg( "_precomputedHash" ) = object() ) ) ; Serialisation::registerSerialiser( StringPlug::staticTypeId(), new StringPlugSerialiser ); }
#include "common/http/http1/codec_impl.h" #include <cstdint> #include <memory> #include <string> #include "envoy/buffer/buffer.h" #include "envoy/http/codec.h" #include "envoy/http/header_map.h" #include "envoy/network/connection.h" #include "common/common/enum_to_int.h" #include "common/common/utility.h" #include "common/http/exception.h" #include "common/http/header_utility.h" #include "common/http/headers.h" #include "common/http/http1/header_formatter.h" #include "common/http/utility.h" #include "common/runtime/runtime_impl.h" #include "absl/container/fixed_array.h" #include "absl/strings/ascii.h" namespace Envoy { namespace Http { namespace Http1 { namespace { struct Http1ResponseCodeDetailValues { const absl::string_view TooManyHeaders = "http1.too_many_headers"; const absl::string_view HeadersTooLarge = "http1.headers_too_large"; const absl::string_view HttpCodecError = "http1.codec_error"; const absl::string_view InvalidCharacters = "http1.invalid_characters"; const absl::string_view ConnectionHeaderSanitization = "http1.connection_header_rejected"; const absl::string_view InvalidUrl = "http1.invalid_url"; const absl::string_view InvalidTransferEncoding = "http1.invalid_transfer_encoding"; }; struct Http1HeaderTypesValues { const absl::string_view Headers = "headers"; const absl::string_view Trailers = "trailers"; }; using Http1ResponseCodeDetails = ConstSingleton<Http1ResponseCodeDetailValues>; using Http1HeaderTypes = ConstSingleton<Http1HeaderTypesValues>; const StringUtil::CaseUnorderedSet& caseUnorderdSetContainingUpgradeAndHttp2Settings() { CONSTRUCT_ON_FIRST_USE(StringUtil::CaseUnorderedSet, Http::Headers::get().ConnectionValues.Upgrade, Http::Headers::get().ConnectionValues.Http2Settings); } HeaderKeyFormatterPtr formatter(const Http::Http1Settings& settings) { if (settings.header_key_format_ == Http1Settings::HeaderKeyFormat::ProperCase) { return std::make_unique<ProperCaseHeaderKeyFormatter>(); } return nullptr; } } // namespace const std::string StreamEncoderImpl::CRLF = "\r\n"; // Last chunk as defined here https://tools.ietf.org/html/rfc7230#section-4.1 const std::string StreamEncoderImpl::LAST_CHUNK = "0\r\n"; StreamEncoderImpl::StreamEncoderImpl(ConnectionImpl& connection, HeaderKeyFormatter* header_key_formatter) : connection_(connection), disable_chunk_encoding_(false), chunk_encoding_(true), processing_100_continue_(false), is_response_to_head_request_(false), is_content_length_allowed_(true), header_key_formatter_(header_key_formatter) { if (connection_.connection().aboveHighWatermark()) { runHighWatermarkCallbacks(); } } void StreamEncoderImpl::encodeHeader(const char* key, uint32_t key_size, const char* value, uint32_t value_size) { ASSERT(key_size > 0); connection_.copyToBuffer(key, key_size); connection_.addCharToBuffer(':'); connection_.addCharToBuffer(' '); connection_.copyToBuffer(value, value_size); connection_.addToBuffer(CRLF); } void StreamEncoderImpl::encodeHeader(absl::string_view key, absl::string_view value) { this->encodeHeader(key.data(), key.size(), value.data(), value.size()); } void StreamEncoderImpl::encodeFormattedHeader(absl::string_view key, absl::string_view value) { if (header_key_formatter_ != nullptr) { encodeHeader(header_key_formatter_->format(key), value); } else { encodeHeader(key, value); } } void ResponseEncoderImpl::encode100ContinueHeaders(const ResponseHeaderMap& headers) { ASSERT(headers.Status()->value() == "100"); processing_100_continue_ = true; encodeHeaders(headers, false); processing_100_continue_ = false; } void StreamEncoderImpl::encodeHeadersBase(const RequestOrResponseHeaderMap& headers, bool end_stream) { bool saw_content_length = false; headers.iterate( [](const HeaderEntry& header, void* context) -> HeaderMap::Iterate { absl::string_view key_to_use = header.key().getStringView(); uint32_t key_size_to_use = header.key().size(); // Translate :authority -> host so that upper layers do not need to deal with this. if (key_size_to_use > 1 && key_to_use[0] == ':' && key_to_use[1] == 'a') { key_to_use = absl::string_view(Headers::get().HostLegacy.get()); key_size_to_use = Headers::get().HostLegacy.get().size(); } // Skip all headers starting with ':' that make it here. if (key_to_use[0] == ':') { return HeaderMap::Iterate::Continue; } static_cast<StreamEncoderImpl*>(context)->encodeFormattedHeader( key_to_use, header.value().getStringView()); return HeaderMap::Iterate::Continue; }, this); if (headers.ContentLength()) { saw_content_length = true; } ASSERT(!headers.TransferEncoding()); // Assume we are chunk encoding unless we are passed a content length or this is a header only // response. Upper layers generally should strip transfer-encoding since it only applies to // HTTP/1.1. The codec will infer it based on the type of response. // for streaming (e.g. SSE stream sent to hystrix dashboard), we do not want // chunk transfer encoding but we don't have a content-length so disable_chunk_encoding_ is // consulted before enabling chunk encoding. // // Note that for HEAD requests Envoy does best-effort guessing when there is no // content-length. If a client makes a HEAD request for an upstream resource // with no bytes but the upstream response doesn't include "Content-length: 0", // Envoy will incorrectly assume a subsequent response to GET will be chunk encoded. if (saw_content_length || disable_chunk_encoding_) { chunk_encoding_ = false; } else { if (processing_100_continue_) { // Make sure we don't serialize chunk information with 100-Continue headers. chunk_encoding_ = false; } else if (end_stream && !is_response_to_head_request_) { // If this is a headers-only stream, append an explicit "Content-Length: 0" unless it's a // response to a HEAD request. // For 204s and 1xx where content length is disallowed, don't append the content length but // also don't chunk encode. if (is_content_length_allowed_) { encodeFormattedHeader(Headers::get().ContentLength.get(), "0"); } chunk_encoding_ = false; } else if (connection_.protocol() == Protocol::Http10) { chunk_encoding_ = false; } else { encodeFormattedHeader(Headers::get().TransferEncoding.get(), Headers::get().TransferEncodingValues.Chunked); // We do not apply chunk encoding for HTTP upgrades. // If there is a body in a WebSocket Upgrade response, the chunks will be // passed through via maybeDirectDispatch so we need to avoid appending // extra chunk boundaries. // // When sending a response to a HEAD request Envoy may send an informational // "Transfer-Encoding: chunked" header, but should not send a chunk encoded body. chunk_encoding_ = !Utility::isUpgrade(headers) && !is_response_to_head_request_; } } connection_.addToBuffer(CRLF); if (end_stream) { endEncode(); } else { connection_.flushOutput(); } } void StreamEncoderImpl::encodeData(Buffer::Instance& data, bool end_stream) { // end_stream may be indicated with a zero length data buffer. If that is the case, so not // actually write the zero length buffer out. if (data.length() > 0) { if (chunk_encoding_) { connection_.buffer().add(absl::StrCat(absl::Hex(data.length()), CRLF)); } connection_.buffer().move(data); if (chunk_encoding_) { connection_.buffer().add(CRLF); } } if (end_stream) { endEncode(); } else { connection_.flushOutput(); } } void StreamEncoderImpl::encodeTrailersBase(const HeaderMap& trailers) { if (!connection_.enableTrailers()) { return endEncode(); } // Trailers only matter if it is a chunk transfer encoding // https://tools.ietf.org/html/rfc7230#section-4.4 if (chunk_encoding_) { // Finalize the body connection_.buffer().add(LAST_CHUNK); trailers.iterate( [](const HeaderEntry& header, void* context) -> HeaderMap::Iterate { static_cast<StreamEncoderImpl*>(context)->encodeFormattedHeader( header.key().getStringView(), header.value().getStringView()); return HeaderMap::Iterate::Continue; }, this); connection_.flushOutput(); connection_.buffer().add(CRLF); } connection_.flushOutput(); connection_.onEncodeComplete(); } void StreamEncoderImpl::encodeMetadata(const MetadataMapVector&) { connection_.stats().metadata_not_supported_error_.inc(); } void StreamEncoderImpl::endEncode() { if (chunk_encoding_) { connection_.buffer().add(LAST_CHUNK); connection_.buffer().add(CRLF); } connection_.flushOutput(true); connection_.onEncodeComplete(); } void ServerConnectionImpl::maybeAddSentinelBufferFragment(Buffer::WatermarkBuffer& output_buffer) { if (!flood_protection_) { return; } // It's messy and complicated to try to tag the final write of an HTTP response for response // tracking for flood protection. Instead, write an empty buffer fragment after the response, // to allow for tracking. // When the response is written out, the fragment will be deleted and the counter will be updated // by ServerConnectionImpl::releaseOutboundResponse() auto fragment = Buffer::OwnedBufferFragmentImpl::create(absl::string_view("", 0), response_buffer_releasor_); output_buffer.addBufferFragment(*fragment.release()); ASSERT(outbound_responses_ < max_outbound_responses_); outbound_responses_++; } void ServerConnectionImpl::doFloodProtectionChecks() const { if (!flood_protection_) { return; } // Before processing another request, make sure that we are below the response flood protection // threshold. if (outbound_responses_ >= max_outbound_responses_) { ENVOY_CONN_LOG(trace, "error accepting request: too many pending responses queued", connection_); stats_.response_flood_.inc(); throw FrameFloodException("Too many responses queued."); } } void ConnectionImpl::flushOutput(bool end_encode) { if (end_encode) { // If this is an HTTP response in ServerConnectionImpl, track outbound responses for flood // protection maybeAddSentinelBufferFragment(output_buffer_); } connection().write(output_buffer_, false); ASSERT(0UL == output_buffer_.length()); } void ConnectionImpl::addToBuffer(absl::string_view data) { output_buffer_.add(data); } void ConnectionImpl::addCharToBuffer(char c) { output_buffer_.add(&c, 1); } void ConnectionImpl::addIntToBuffer(uint64_t i) { output_buffer_.add(absl::StrCat(i)); } void ConnectionImpl::copyToBuffer(const char* data, uint64_t length) { output_buffer_.add(data, length); } void StreamEncoderImpl::resetStream(StreamResetReason reason) { connection_.onResetStreamBase(reason); } void StreamEncoderImpl::readDisable(bool disable) { connection_.readDisable(disable); } uint32_t StreamEncoderImpl::bufferLimit() { return connection_.bufferLimit(); } const Network::Address::InstanceConstSharedPtr& StreamEncoderImpl::connectionLocalAddress() { return connection_.connection().localAddress(); } static const char RESPONSE_PREFIX[] = "HTTP/1.1 "; static const char HTTP_10_RESPONSE_PREFIX[] = "HTTP/1.0 "; void ResponseEncoderImpl::encodeHeaders(const ResponseHeaderMap& headers, bool end_stream) { started_response_ = true; // The contract is that client codecs must ensure that :status is present. ASSERT(headers.Status() != nullptr); uint64_t numeric_status = Utility::getResponseStatus(headers); if (connection_.protocol() == Protocol::Http10 && connection_.supports_http_10()) { connection_.copyToBuffer(HTTP_10_RESPONSE_PREFIX, sizeof(HTTP_10_RESPONSE_PREFIX) - 1); } else { connection_.copyToBuffer(RESPONSE_PREFIX, sizeof(RESPONSE_PREFIX) - 1); } connection_.addIntToBuffer(numeric_status); connection_.addCharToBuffer(' '); const char* status_string = CodeUtility::toString(static_cast<Code>(numeric_status)); uint32_t status_string_len = strlen(status_string); connection_.copyToBuffer(status_string, status_string_len); connection_.addCharToBuffer('\r'); connection_.addCharToBuffer('\n'); if (numeric_status == 204 || numeric_status < 200) { // Per https://tools.ietf.org/html/rfc7230#section-3.3.2 setIsContentLengthAllowed(false); } else { // Make sure that if we encodeHeaders(100) then encodeHeaders(200) that we // set is_content_length_allowed_ back to true. setIsContentLengthAllowed(true); } encodeHeadersBase(headers, end_stream); } static const char REQUEST_POSTFIX[] = " HTTP/1.1\r\n"; void RequestEncoderImpl::encodeHeaders(const RequestHeaderMap& headers, bool end_stream) { const HeaderEntry* method = headers.Method(); const HeaderEntry* path = headers.Path(); if (!method || !path) { throw CodecClientException(":method and :path must be specified"); } if (method->value() == Headers::get().MethodValues.Head) { head_request_ = true; } connection_.copyToBuffer(method->value().getStringView().data(), method->value().size()); connection_.addCharToBuffer(' '); connection_.copyToBuffer(path->value().getStringView().data(), path->value().size()); connection_.copyToBuffer(REQUEST_POSTFIX, sizeof(REQUEST_POSTFIX) - 1); encodeHeadersBase(headers, end_stream); } http_parser_settings ConnectionImpl::settings_{ [](http_parser* parser) -> int { static_cast<ConnectionImpl*>(parser->data)->onMessageBeginBase(); return 0; }, [](http_parser* parser, const char* at, size_t length) -> int { static_cast<ConnectionImpl*>(parser->data)->onUrl(at, length); return 0; }, nullptr, // on_status [](http_parser* parser, const char* at, size_t length) -> int { static_cast<ConnectionImpl*>(parser->data)->onHeaderField(at, length); return 0; }, [](http_parser* parser, const char* at, size_t length) -> int { static_cast<ConnectionImpl*>(parser->data)->onHeaderValue(at, length); return 0; }, [](http_parser* parser) -> int { return static_cast<ConnectionImpl*>(parser->data)->onHeadersCompleteBase(); }, [](http_parser* parser, const char* at, size_t length) -> int { static_cast<ConnectionImpl*>(parser->data)->onBody(at, length); return 0; }, [](http_parser* parser) -> int { static_cast<ConnectionImpl*>(parser->data)->onMessageCompleteBase(); return 0; }, nullptr, // on_chunk_header nullptr // on_chunk_complete }; ConnectionImpl::ConnectionImpl(Network::Connection& connection, Stats::Scope& stats, http_parser_type type, uint32_t max_headers_kb, const uint32_t max_headers_count, HeaderKeyFormatterPtr&& header_key_formatter, bool enable_trailers) : connection_(connection), stats_{ALL_HTTP1_CODEC_STATS(POOL_COUNTER_PREFIX(stats, "http1."))}, header_key_formatter_(std::move(header_key_formatter)), processing_trailers_(false), handling_upgrade_(false), reset_stream_called_(false), deferred_end_stream_headers_(false), strict_header_validation_( Runtime::runtimeFeatureEnabled("envoy.reloadable_features.strict_header_validation")), connection_header_sanitization_(Runtime::runtimeFeatureEnabled( "envoy.reloadable_features.connection_header_sanitization")), enable_trailers_(enable_trailers), reject_unsupported_transfer_encodings_(Runtime::runtimeFeatureEnabled( "envoy.reloadable_features.reject_unsupported_transfer_encodings")), output_buffer_([&]() -> void { this->onBelowLowWatermark(); }, [&]() -> void { this->onAboveHighWatermark(); }), max_headers_kb_(max_headers_kb), max_headers_count_(max_headers_count) { output_buffer_.setWatermarks(connection.bufferLimit()); http_parser_init(&parser_, type); parser_.data = this; } void ConnectionImpl::completeLastHeader() { ENVOY_CONN_LOG(trace, "completed header: key={} value={}", connection_, current_header_field_.getStringView(), current_header_value_.getStringView()); auto& headers_or_trailers = headersOrTrailers(); if (!current_header_field_.empty()) { current_header_field_.inlineTransform([](char c) { return absl::ascii_tolower(c); }); headers_or_trailers.addViaMove(std::move(current_header_field_), std::move(current_header_value_)); } // Check if the number of headers exceeds the limit. if (headers_or_trailers.size() > max_headers_count_) { error_code_ = Http::Code::RequestHeaderFieldsTooLarge; sendProtocolError(Http1ResponseCodeDetails::get().TooManyHeaders); const absl::string_view header_type = processing_trailers_ ? Http1HeaderTypes::get().Trailers : Http1HeaderTypes::get().Headers; throw CodecProtocolException(absl::StrCat(header_type, " size exceeds limit")); } header_parsing_state_ = HeaderParsingState::Field; ASSERT(current_header_field_.empty()); ASSERT(current_header_value_.empty()); } bool ConnectionImpl::maybeDirectDispatch(Buffer::Instance& data) { if (!handling_upgrade_) { // Only direct dispatch for Upgrade requests. return false; } ssize_t total_parsed = 0; for (const Buffer::RawSlice& slice : data.getRawSlices()) { total_parsed += slice.len_; onBody(static_cast<const char*>(slice.mem_), slice.len_); } ENVOY_CONN_LOG(trace, "direct-dispatched {} bytes", connection_, total_parsed); data.drain(total_parsed); return true; } void ConnectionImpl::dispatch(Buffer::Instance& data) { ENVOY_CONN_LOG(trace, "parsing {} bytes", connection_, data.length()); if (maybeDirectDispatch(data)) { return; } // Always unpause before dispatch. http_parser_pause(&parser_, 0); ssize_t total_parsed = 0; if (data.length() > 0) { for (const Buffer::RawSlice& slice : data.getRawSlices()) { total_parsed += dispatchSlice(static_cast<const char*>(slice.mem_), slice.len_); } } else { dispatchSlice(nullptr, 0); } ENVOY_CONN_LOG(trace, "parsed {} bytes", connection_, total_parsed); data.drain(total_parsed); // If an upgrade has been handled and there is body data or early upgrade // payload to send on, send it on. maybeDirectDispatch(data); } size_t ConnectionImpl::dispatchSlice(const char* slice, size_t len) { ssize_t rc = http_parser_execute(&parser_, &settings_, slice, len); if (HTTP_PARSER_ERRNO(&parser_) != HPE_OK && HTTP_PARSER_ERRNO(&parser_) != HPE_PAUSED) { sendProtocolError(Http1ResponseCodeDetails::get().HttpCodecError); throw CodecProtocolException("http/1.1 protocol error: " + std::string(http_errno_name(HTTP_PARSER_ERRNO(&parser_)))); } return rc; } void ConnectionImpl::onHeaderField(const char* data, size_t length) { // We previously already finished up the headers, these headers are // now trailers. if (header_parsing_state_ == HeaderParsingState::Done) { if (!enable_trailers_) { // Ignore trailers. return; } processing_trailers_ = true; header_parsing_state_ = HeaderParsingState::Field; } if (header_parsing_state_ == HeaderParsingState::Value) { completeLastHeader(); } current_header_field_.append(data, length); } void ConnectionImpl::onHeaderValue(const char* data, size_t length) { if (header_parsing_state_ == HeaderParsingState::Done && !enable_trailers_) { // Ignore trailers. return; } if (processing_trailers_) { maybeAllocTrailers(); } // Work around a bug in http_parser where trailing whitespace is not trimmed // as the spec requires: https://tools.ietf.org/html/rfc7230#section-3.2.4 const absl::string_view header_value = StringUtil::trim(absl::string_view(data, length)); if (strict_header_validation_) { if (!Http::HeaderUtility::headerIsValid(header_value)) { ENVOY_CONN_LOG(debug, "invalid header value: {}", connection_, header_value); error_code_ = Http::Code::BadRequest; sendProtocolError(Http1ResponseCodeDetails::get().InvalidCharacters); throw CodecProtocolException("http/1.1 protocol error: header value contains invalid chars"); } } header_parsing_state_ = HeaderParsingState::Value; current_header_value_.append(header_value.data(), header_value.length()); const uint32_t total = current_header_field_.size() + current_header_value_.size() + headersOrTrailers().byteSize(); if (total > (max_headers_kb_ * 1024)) { const absl::string_view header_type = processing_trailers_ ? Http1HeaderTypes::get().Trailers : Http1HeaderTypes::get().Headers; error_code_ = Http::Code::RequestHeaderFieldsTooLarge; sendProtocolError(Http1ResponseCodeDetails::get().HeadersTooLarge); throw CodecProtocolException(absl::StrCat(header_type, " size exceeds limit")); } } int ConnectionImpl::onHeadersCompleteBase() { ASSERT(!processing_trailers_); ENVOY_CONN_LOG(trace, "onHeadersCompleteBase", connection_); completeLastHeader(); if (!(parser_.http_major == 1 && parser_.http_minor == 1)) { // This is not necessarily true, but it's good enough since higher layers only care if this is // HTTP/1.1 or not. protocol_ = Protocol::Http10; } RequestOrResponseHeaderMap& request_or_response_headers = requestOrResponseHeaders(); if (Utility::isUpgrade(request_or_response_headers)) { // Ignore h2c upgrade requests until we support them. // See https://github.com/envoyproxy/envoy/issues/7161 for details. if (request_or_response_headers.Upgrade() && absl::EqualsIgnoreCase(request_or_response_headers.Upgrade()->value().getStringView(), Http::Headers::get().UpgradeValues.H2c)) { ENVOY_CONN_LOG(trace, "removing unsupported h2c upgrade headers.", connection_); request_or_response_headers.removeUpgrade(); if (request_or_response_headers.Connection()) { const auto& tokens_to_remove = caseUnorderdSetContainingUpgradeAndHttp2Settings(); std::string new_value = StringUtil::removeTokens( request_or_response_headers.Connection()->value().getStringView(), ",", tokens_to_remove, ","); if (new_value.empty()) { request_or_response_headers.removeConnection(); } else { request_or_response_headers.setConnection(new_value); } } request_or_response_headers.remove(Headers::get().Http2Settings); } else { ENVOY_CONN_LOG(trace, "codec entering upgrade mode.", connection_); handling_upgrade_ = true; } } // Per https://tools.ietf.org/html/rfc7230#section-3.3.1 Envoy should reject // transfer-codings it does not understand. if (request_or_response_headers.TransferEncoding()) { const absl::string_view encoding = request_or_response_headers.TransferEncoding()->value().getStringView(); if (reject_unsupported_transfer_encodings_ && !absl::EqualsIgnoreCase(encoding, Headers::get().TransferEncodingValues.Chunked)) { error_code_ = Http::Code::NotImplemented; sendProtocolError(Http1ResponseCodeDetails::get().InvalidTransferEncoding); throw CodecProtocolException("http/1.1 protocol error: unsupported transfer encoding"); } } int rc = onHeadersComplete(); header_parsing_state_ = HeaderParsingState::Done; // Returning 2 informs http_parser to not expect a body or further data on this connection. return handling_upgrade_ ? 2 : rc; } void ConnectionImpl::onMessageCompleteBase() { ENVOY_CONN_LOG(trace, "message complete", connection_); if (handling_upgrade_) { // If this is an upgrade request, swallow the onMessageComplete. The // upgrade payload will be treated as stream body. ASSERT(!deferred_end_stream_headers_); ENVOY_CONN_LOG(trace, "Pausing parser due to upgrade.", connection_); http_parser_pause(&parser_, 1); return; } // If true, this indicates we were processing trailers and must // move the last header into current_header_map_ if (header_parsing_state_ == HeaderParsingState::Value) { completeLastHeader(); } onMessageComplete(); } void ConnectionImpl::onMessageBeginBase() { ENVOY_CONN_LOG(trace, "message begin", connection_); // Make sure that if HTTP/1.0 and HTTP/1.1 requests share a connection Envoy correctly sets // protocol for each request. Envoy defaults to 1.1 but sets the protocol to 1.0 where applicable // in onHeadersCompleteBase protocol_ = Protocol::Http11; processing_trailers_ = false; header_parsing_state_ = HeaderParsingState::Field; allocHeaders(); onMessageBegin(); } void ConnectionImpl::onResetStreamBase(StreamResetReason reason) { ASSERT(!reset_stream_called_); reset_stream_called_ = true; onResetStream(reason); } ServerConnectionImpl::ServerConnectionImpl(Network::Connection& connection, Stats::Scope& stats, ServerConnectionCallbacks& callbacks, const Http1Settings& settings, uint32_t max_request_headers_kb, const uint32_t max_request_headers_count) : ConnectionImpl(connection, stats, HTTP_REQUEST, max_request_headers_kb, max_request_headers_count, formatter(settings), settings.enable_trailers_), callbacks_(callbacks), codec_settings_(settings), response_buffer_releasor_([this](const Buffer::OwnedBufferFragmentImpl* fragment) { releaseOutboundResponse(fragment); }), // Pipelining is generally not well supported on the internet and has a series of dangerous // overflow bugs. As such we are disabling it for now, and removing this temporary override if // no one objects. If you use this integer to restore prior behavior, contact the // maintainer team as it will otherwise be removed entirely soon. max_outbound_responses_( Runtime::getInteger("envoy.do_not_use_going_away_max_http2_outbound_responses", 2)), flood_protection_( Runtime::runtimeFeatureEnabled("envoy.reloadable_features.http1_flood_protection")) {} void ServerConnectionImpl::onEncodeComplete() { if (active_request_.value().remote_complete_) { // Only do this if remote is complete. If we are replying before the request is complete the // only logical thing to do is for higher level code to reset() / close the connection so we // leave the request around so that it can fire reset callbacks. active_request_.reset(); } } void ServerConnectionImpl::handlePath(RequestHeaderMap& headers, unsigned int method) { HeaderString path(Headers::get().Path); bool is_connect = (method == HTTP_CONNECT); // The url is relative or a wildcard when the method is OPTIONS. Nothing to do here. auto& active_request = active_request_.value(); if (!active_request.request_url_.getStringView().empty() && (active_request.request_url_.getStringView()[0] == '/' || ((method == HTTP_OPTIONS) && active_request.request_url_.getStringView()[0] == '*'))) { headers.addViaMove(std::move(path), std::move(active_request.request_url_)); return; } // If absolute_urls and/or connect are not going be handled, copy the url and return. // This forces the behavior to be backwards compatible with the old codec behavior. if (!codec_settings_.allow_absolute_url_) { headers.addViaMove(std::move(path), std::move(active_request.request_url_)); return; } if (is_connect) { headers.addViaMove(std::move(path), std::move(active_request.request_url_)); return; } Utility::Url absolute_url; if (!absolute_url.initialize(active_request.request_url_.getStringView())) { sendProtocolError(Http1ResponseCodeDetails::get().InvalidUrl); throw CodecProtocolException("http/1.1 protocol error: invalid url in request line"); } // RFC7230#5.7 // When a proxy receives a request with an absolute-form of // request-target, the proxy MUST ignore the received Host header field // (if any) and instead replace it with the host information of the // request-target. A proxy that forwards such a request MUST generate a // new Host field-value based on the received request-target rather than // forward the received Host field-value. headers.setHost(absolute_url.host_and_port()); headers.setPath(absolute_url.path_and_query_params()); active_request.request_url_.clear(); } int ServerConnectionImpl::onHeadersComplete() { // Handle the case where response happens prior to request complete. It's up to upper layer code // to disconnect the connection but we shouldn't fire any more events since it doesn't make // sense. if (active_request_.has_value()) { auto& active_request = active_request_.value(); auto& headers = absl::get<RequestHeaderMapPtr>(headers_or_trailers_); ENVOY_CONN_LOG(trace, "Server: onHeadersComplete size={}", connection_, headers->size()); const char* method_string = http_method_str(static_cast<http_method>(parser_.method)); if (!handling_upgrade_ && connection_header_sanitization_ && headers->Connection()) { // If we fail to sanitize the request, return a 400 to the client if (!Utility::sanitizeConnectionHeader(*headers)) { absl::string_view header_value = headers->Connection()->value().getStringView(); ENVOY_CONN_LOG(debug, "Invalid nominated headers in Connection: {}", connection_, header_value); error_code_ = Http::Code::BadRequest; sendProtocolError(Http1ResponseCodeDetails::get().ConnectionHeaderSanitization); throw CodecProtocolException("Invalid nominated headers in Connection."); } } // Inform the response encoder about any HEAD method, so it can set content // length and transfer encoding headers correctly. active_request.response_encoder_.isResponseToHeadRequest(parser_.method == HTTP_HEAD); // Currently, CONNECT is not supported, however; http_parser_parse_url needs to know about // CONNECT handlePath(*headers, parser_.method); ASSERT(active_request.request_url_.empty()); headers->setMethod(method_string); // Make sure the host is valid. auto details = HeaderUtility::requestHeadersValid(*headers); if (details.has_value()) { sendProtocolError(details.value().get()); throw CodecProtocolException( "http/1.1 protocol error: request headers failed spec compliance checks"); } // Determine here whether we have a body or not. This uses the new RFC semantics where the // presence of content-length or chunked transfer-encoding indicates a body vs. a particular // method. If there is no body, we defer raising decodeHeaders() until the parser is flushed // with message complete. This allows upper layers to behave like HTTP/2 and prevents a proxy // scenario where the higher layers stream through and implicitly switch to chunked transfer // encoding because end stream with zero body length has not yet been indicated. if (parser_.flags & F_CHUNKED || (parser_.content_length > 0 && parser_.content_length != ULLONG_MAX) || handling_upgrade_) { active_request.request_decoder_->decodeHeaders(std::move(headers), false); // If the connection has been closed (or is closing) after decoding headers, pause the parser // so we return control to the caller. if (connection_.state() != Network::Connection::State::Open) { http_parser_pause(&parser_, 1); } } else { deferred_end_stream_headers_ = true; } } return 0; } void ServerConnectionImpl::onMessageBegin() { if (!resetStreamCalled()) { ASSERT(!active_request_.has_value()); active_request_.emplace(*this, header_key_formatter_.get()); auto& active_request = active_request_.value(); active_request.request_decoder_ = &callbacks_.newStream(active_request.response_encoder_); // Check for pipelined request flood as we prepare to accept a new request. // Parse errors that happen prior to onMessageBegin result in stream termination, it is not // possible to overflow output buffers with early parse errors. doFloodProtectionChecks(); } } void ServerConnectionImpl::onUrl(const char* data, size_t length) { if (active_request_.has_value()) { active_request_.value().request_url_.append(data, length); } } void ServerConnectionImpl::onBody(const char* data, size_t length) { ASSERT(!deferred_end_stream_headers_); if (active_request_.has_value()) { ENVOY_CONN_LOG(trace, "body size={}", connection_, length); Buffer::OwnedImpl buffer(data, length); active_request_.value().request_decoder_->decodeData(buffer, false); } } void ServerConnectionImpl::onMessageComplete() { if (active_request_.has_value()) { auto& active_request = active_request_.value(); active_request.remote_complete_ = true; if (deferred_end_stream_headers_) { active_request.request_decoder_->decodeHeaders( std::move(absl::get<RequestHeaderMapPtr>(headers_or_trailers_)), true); deferred_end_stream_headers_ = false; } else if (processing_trailers_) { active_request.request_decoder_->decodeTrailers( std::move(absl::get<RequestTrailerMapPtr>(headers_or_trailers_))); } else { Buffer::OwnedImpl buffer; active_request.request_decoder_->decodeData(buffer, true); } // Reset to ensure no information from one requests persists to the next. headers_or_trailers_.emplace<RequestHeaderMapPtr>(nullptr); } // Always pause the parser so that the calling code can process 1 request at a time and apply // back pressure. However this means that the calling code needs to detect if there is more data // in the buffer and dispatch it again. http_parser_pause(&parser_, 1); } void ServerConnectionImpl::onResetStream(StreamResetReason reason) { active_request_.value().response_encoder_.runResetCallbacks(reason); active_request_.reset(); } void ServerConnectionImpl::sendProtocolError(absl::string_view details) { if (active_request_.has_value()) { active_request_.value().response_encoder_.setDetails(details); } // We do this here because we may get a protocol error before we have a logical stream. Higher // layers can only operate on streams, so there is no coherent way to allow them to send an error // "out of band." On one hand this is kind of a hack but on the other hand it normalizes HTTP/1.1 // to look more like HTTP/2 to higher layers. if (!active_request_.has_value() || !active_request_.value().response_encoder_.startedResponse()) { Buffer::OwnedImpl bad_request_response( absl::StrCat("HTTP/1.1 ", error_code_, " ", CodeUtility::toString(error_code_), "\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")); connection_.write(bad_request_response, false); } } void ServerConnectionImpl::onAboveHighWatermark() { if (active_request_.has_value()) { active_request_.value().response_encoder_.runHighWatermarkCallbacks(); } } void ServerConnectionImpl::onBelowLowWatermark() { if (active_request_.has_value()) { active_request_.value().response_encoder_.runLowWatermarkCallbacks(); } } void ServerConnectionImpl::releaseOutboundResponse( const Buffer::OwnedBufferFragmentImpl* fragment) { ASSERT(outbound_responses_ >= 1); --outbound_responses_; delete fragment; } ClientConnectionImpl::ClientConnectionImpl(Network::Connection& connection, Stats::Scope& stats, ConnectionCallbacks&, const Http1Settings& settings, const uint32_t max_response_headers_count) : ConnectionImpl(connection, stats, HTTP_RESPONSE, MAX_RESPONSE_HEADERS_KB, max_response_headers_count, formatter(settings), settings.enable_trailers_) {} bool ClientConnectionImpl::cannotHaveBody() { if ((pending_response_.has_value() && pending_response_.value().encoder_.headRequest()) || parser_.status_code == 204 || parser_.status_code == 304 || (parser_.status_code >= 200 && parser_.content_length == 0)) { return true; } else { return false; } } RequestEncoder& ClientConnectionImpl::newStream(ResponseDecoder& response_decoder) { if (resetStreamCalled()) { throw CodecClientException("cannot create new streams after calling reset"); } // If reads were disabled due to flow control, we expect reads to always be enabled again before // reusing this connection. This is done when the response is received. ASSERT(connection_.readEnabled()); ASSERT(!pending_response_.has_value()); pending_response_.emplace(*this, header_key_formatter_.get(), &response_decoder); return pending_response_.value().encoder_; } int ClientConnectionImpl::onHeadersComplete() { // Handle the case where the client is closing a kept alive connection (by sending a 408 // with a 'Connection: close' header). In this case we just let response flush out followed // by the remote close. if (!pending_response_.has_value() && !resetStreamCalled()) { throw PrematureResponseException(static_cast<Http::Code>(parser_.status_code)); } else if (pending_response_.has_value()) { auto& headers = absl::get<ResponseHeaderMapPtr>(headers_or_trailers_); ENVOY_CONN_LOG(trace, "Client: onHeadersComplete size={}", connection_, headers->size()); headers->setStatus(parser_.status_code); if (parser_.status_code == 100) { // http-parser treats 100 continue headers as their own complete response. // Swallow the spurious onMessageComplete and continue processing. ignore_message_complete_for_100_continue_ = true; pending_response_.value().decoder_->decode100ContinueHeaders(std::move(headers)); // Reset to ensure no information from the continue headers is used for the response headers // in case the callee does not move the headers out. headers_or_trailers_.emplace<ResponseHeaderMapPtr>(nullptr); } else if (cannotHaveBody()) { deferred_end_stream_headers_ = true; } else { pending_response_.value().decoder_->decodeHeaders(std::move(headers), false); } } // Here we deal with cases where the response cannot have a body, but http_parser does not deal // with it for us. return cannotHaveBody() ? 1 : 0; } void ClientConnectionImpl::onBody(const char* data, size_t length) { ASSERT(!deferred_end_stream_headers_); if (pending_response_.has_value()) { Buffer::OwnedImpl buffer; buffer.add(data, length); pending_response_.value().decoder_->decodeData(buffer, false); } } void ClientConnectionImpl::onMessageComplete() { ENVOY_CONN_LOG(trace, "message complete", connection_); if (ignore_message_complete_for_100_continue_) { ignore_message_complete_for_100_continue_ = false; return; } if (pending_response_.has_value()) { // After calling decodeData() with end stream set to true, we should no longer be able to reset. PendingResponse response = std::move(pending_response_.value()); pending_response_.reset(); // Streams are responsible for unwinding any outstanding readDisable(true) // calls done on the underlying connection as they are destroyed. As this is // the only place a HTTP/1 stream is destroyed where the Network::Connection is // reused, unwind any outstanding readDisable() calls here. Do this before we dispatch // end_stream in case the caller immediately reuses the connection. if (connection_.state() == Network::Connection::State::Open) { while (!connection_.readEnabled()) { connection_.readDisable(false); } } if (deferred_end_stream_headers_) { response.decoder_->decodeHeaders( std::move(absl::get<ResponseHeaderMapPtr>(headers_or_trailers_)), true); deferred_end_stream_headers_ = false; } else if (processing_trailers_) { response.decoder_->decodeTrailers( std::move(absl::get<ResponseTrailerMapPtr>(headers_or_trailers_))); } else { Buffer::OwnedImpl buffer; response.decoder_->decodeData(buffer, true); } // Reset to ensure no information from one requests persists to the next. headers_or_trailers_.emplace<ResponseHeaderMapPtr>(nullptr); } } void ClientConnectionImpl::onResetStream(StreamResetReason reason) { // Only raise reset if we did not already dispatch a complete response. if (pending_response_.has_value()) { pending_response_.value().encoder_.runResetCallbacks(reason); pending_response_.reset(); } } void ClientConnectionImpl::sendProtocolError(absl::string_view details) { if (pending_response_.has_value()) { pending_response_.value().encoder_.setDetails(details); } } void ClientConnectionImpl::onAboveHighWatermark() { // This should never happen without an active stream/request. pending_response_.value().encoder_.runHighWatermarkCallbacks(); } void ClientConnectionImpl::onBelowLowWatermark() { // This can get called without an active stream/request when upstream decides to do bad things // such as sending multiple responses to the same request, causing us to close the connection, but // in doing so go below low watermark. if (pending_response_.has_value()) { pending_response_.value().encoder_.runLowWatermarkCallbacks(); } } } // namespace Http1 } // namespace Http } // namespace Envoy
/* dasum.f -- translated by f2c (version 20010320). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include <math.h> double mndasum(unsigned int n, const double* dx, int incx) { /* System generated locals */ int i__1, i__2; double ret_val, d__1, d__2, d__3, d__4, d__5, d__6; /* Local variables */ int i__, m; double dtemp; int nincx, mp1; /* takes the sum of the absolute values. */ /* jack dongarra, linpack, 3/11/78. */ /* modified 3/93 to return if incx .le. 0. */ /* modified 12/3/93, array(1) declarations changed to array(*) */ /* Parameter adjustments */ --dx; /* Function Body */ ret_val = 0.; dtemp = 0.; if (n <= 0 || incx <= 0) { return ret_val; } if (incx == 1) { goto L20; } /* code for increment not equal to 1 */ nincx = n * incx; i__1 = nincx; i__2 = incx; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { dtemp += (d__1 = dx[i__], fabs(d__1)); /* L10: */ } ret_val = dtemp; return ret_val; /* code for increment equal to 1 */ /* clean-up loop */ L20: m = n % 6; if (m == 0) { goto L40; } i__2 = m; for (i__ = 1; i__ <= i__2; ++i__) { dtemp += (d__1 = dx[i__], fabs(d__1)); /* L30: */ } if (n < 6) { goto L60; } L40: mp1 = m + 1; i__2 = n; for (i__ = mp1; i__ <= i__2; i__ += 6) { dtemp = dtemp + (d__1 = dx[i__], fabs(d__1)) + (d__2 = dx[i__ + 1], fabs(d__2)) + (d__3 = dx[i__ + 2], fabs(d__3)) + (d__4 = dx[i__ + 3], fabs(d__4)) + (d__5 = dx[i__ + 4], fabs(d__5)) + (d__6 = dx[i__ + 5], fabs(d__6)); /* L50: */ } L60: ret_val = dtemp; return ret_val; } /* dasum_ */
#include <iostream> #include "book.h" #include "library.h" using namespace std; int main(){ const Book booky1("me", "A life worth lived", 1993); const Book booky2("you", "A life Part II", 1997); const Book booky3("us", "It's fucked up", 2020); Library lib(3); lib.addBook(booky1); lib.addBook(booky2); lib.printBooks(); return 0; }
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2020-2021 Intel Corporation. All Rights Reserved. #include "RealSenseID/FaceAuthenticator.h" #include <iostream> #include <stdio.h> class MyEnrollClbk : public RealSenseID::EnrollmentCallback { public: void OnResult(const RealSenseID::EnrollStatus status) override { std::cout << "Result " << status << std::endl; } void OnProgress(const RealSenseID::FacePose pose) override { std::cout << "OnProgress " << pose << std::endl; } void OnHint(const RealSenseID::EnrollStatus hint) override { std::cout << "Hint " << hint << std::endl; } void OnFaceDetected(const std::vector<RealSenseID::FaceRect>& faces, const unsigned int ts) override { for (auto& face : faces) { printf("** Detected face %u,%u %ux%u (timestamp %u)\n", face.x, face.y, face.w, face.h, ts); } } }; int main() { RealSenseID::FaceAuthenticator authenticator; #ifdef _WIN32 auto status = authenticator.Connect({"COM1"}); #elif LINUX auto status = authenticator.Connect({"/dev/ttyACM0"}); #endif if (status != RealSenseID::Status::Ok) { std::cout << "Failed connecting with status " << status << std::endl; return 1; } MyEnrollClbk enroll_clbk; authenticator.Enroll(enroll_clbk, "john"); }
// // Created by artem on 26.03.2022. // #include "ConvolutionOperation.h" #include <iostream> ConvolutionOperation::ConvolutionOperation() = default; std::vector<std::vector<Pixel> > ConvolutionOperation::ApplyConvolution(const std::vector<std::vector<Pixel>> &input) const { int image_height = static_cast<int> (input.size()); int image_width = static_cast<int> (input[0].size()); std::vector<std::vector<Pixel> > answer(image_height, std::vector<Pixel> (image_width, Pixel())); for (int height_i = 0; height_i < image_height; ++height_i) { for (int width_i = 0; width_i < image_width; ++width_i) { int scalar_product_red = 0; int scalar_product_green = 0; int scalar_product_blue = 0; for (int kernel_height_i = 0; kernel_height_i < kernel_height; ++kernel_height_i) { for (int kernel_width_i = 0; kernel_width_i < kernel_width; ++kernel_width_i) { int pixel_height = std::min(image_height - 1, std::max(0, height_i - kernel_height / 2 + kernel_height_i)); int pixel_width = std::min(image_width - 1, std::max(0, width_i - kernel_width / 2 + kernel_width_i)); int kernel_pixel = kernel_[kernel_height_i][kernel_width_i]; Pixel input_pixel = input[pixel_height][pixel_width]; scalar_product_red += kernel_pixel * input_pixel.red_; scalar_product_green += kernel_pixel * input_pixel.green_; scalar_product_blue += kernel_pixel * input_pixel.blue_; } } scalar_product_red = std::min(255, std::max(scalar_product_red, 0)); // clip scalar_product_red = static_cast<uint8_t>(scalar_product_red); scalar_product_green = std::min(255, std::max(scalar_product_green, 0)); // clip scalar_product_green = static_cast<uint8_t>(scalar_product_green); scalar_product_blue = std::min(255, std::max(scalar_product_blue, 0)); // clip scalar_product_blue = static_cast<uint8_t>(scalar_product_blue); answer[height_i][width_i] = Pixel(scalar_product_red, scalar_product_green, scalar_product_blue); } } return answer; }
/****************************************************************************** * * Project: OGR * Purpose: Implements OGRAVCE00DataSource class. * Author: Frank Warmerdam, warmerdam@pobox.com * James Flemer <jflemer@alum.rpi.edu> * ****************************************************************************** * Copyright (c) 2002, Frank Warmerdam <warmerdam@pobox.com> * Copyright (c) 2006, James Flemer <jflemer@alum.rpi.edu> * * 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 "ogr_avc.h" #include "cpl_conv.h" #include "cpl_string.h" CPL_CVSID("$Id: ogravce00datasource.cpp 8e5eeb35bf76390e3134a4ea7076dab7d478ea0e 2018-11-14 22:55:13 +0100 Even Rouault $") /************************************************************************/ /* OGRAVCE00DataSource() */ /************************************************************************/ OGRAVCE00DataSource::OGRAVCE00DataSource() : nLayers(0), pszName(nullptr), psE00(nullptr), papoLayers(nullptr) {} /************************************************************************/ /* ~OGRAVCE00DataSource() */ /************************************************************************/ OGRAVCE00DataSource::~OGRAVCE00DataSource() { if( psE00 ) { AVCE00ReadCloseE00( psE00 ); psE00 = nullptr; } CPLFree( pszName ); for( int i = 0; i < nLayers; i++ ) delete papoLayers[i]; CPLFree( papoLayers ); } /************************************************************************/ /* Open() */ /************************************************************************/ int OGRAVCE00DataSource::Open( const char * pszNewName, int bTestOpen ) { /* -------------------------------------------------------------------- */ /* Open the source file. Suppress error reporting if we are in */ /* TestOpen mode. */ /* -------------------------------------------------------------------- */ bool bCompressed = false; if( bTestOpen ) CPLPushErrorHandler( CPLQuietErrorHandler ); psE00 = AVCE00ReadOpenE00(pszNewName); if( CPLGetLastErrorNo() == CPLE_OpenFailed && strstr(CPLGetLastErrorMsg(), "compressed E00") != nullptr ) { bCompressed = true; } if( bTestOpen ) { CPLPopErrorHandler(); CPLErrorReset(); } if( psE00 == nullptr ) { if( bCompressed ) { CPLError(CE_Failure, CPLE_OpenFailed, "This looks like a compressed E00 file and cannot be " "processed directly. You may need to uncompress it " "first using the E00compr library or the e00conv " "program." ); } return FALSE; } pszName = CPLStrdup( pszNewName ); /* pszCoverageName = CPLStrdup( psE00->pszCoverName ); */ pszCoverageName = CPLStrdup( pszNewName ); /* -------------------------------------------------------------------- */ /* Create layers for the "interesting" sections of the coverage. */ /* -------------------------------------------------------------------- */ papoLayers = static_cast<OGRAVCE00Layer **>( CPLCalloc( sizeof(OGRAVCE00Layer *), psE00->numSections ) ); nLayers = 0; for( int iSection = 0; iSection < psE00->numSections; iSection++ ) { AVCE00Section *psSec = psE00->pasSections + iSection; switch( psSec->eType ) { case AVCFileARC: case AVCFilePAL: case AVCFileCNT: case AVCFileLAB: case AVCFileRPL: case AVCFileTXT: papoLayers[nLayers++] = new OGRAVCE00Layer( this, psSec ); break; case AVCFileTX6: break; case AVCFileTABLE: CheckAddTable(psSec); break; case AVCFilePRJ: { #if 0 poSRS = new OGRSpatialReference(); poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); AVCE00File *hFile = AVCE00ReadOpen( psE00->pszCoverPath, psSec->pszFilename, psE00->eCoverType, psSec->eType, psE00->psDBCSInfo); if( hFile && poSRS == NULL ) { char **papszPRJ = AVCE00ReadNextPrj( hFile ); poSRS = new OGRSpatialReference(); poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); if( poSRS->importFromESRI( papszPRJ ) != OGRERR_NONE ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to parse PRJ section, ignoring." ); delete poSRS; poSRS = NULL; } AVCE00ReadClose( hFile ); } #endif } break; default: ; } } return nLayers > 0; } int OGRAVCE00DataSource::CheckAddTable( AVCE00Section *psTblSection ) { int nCount = 0; for (int i = 0; i < nLayers; ++i) { if( papoLayers[i]->CheckSetupTable(psTblSection) ) ++nCount; } return nCount; } /************************************************************************/ /* TestCapability() */ /************************************************************************/ int OGRAVCE00DataSource::TestCapability( const char * /* pszCap */ ) { return FALSE; } /************************************************************************/ /* GetLayer() */ /************************************************************************/ OGRLayer *OGRAVCE00DataSource::GetLayer( int iLayer ) { if( iLayer < 0 || iLayer >= nLayers ) return nullptr; return papoLayers[iLayer]; } /************************************************************************/ /* GetSpatialRef() */ /************************************************************************/ OGRSpatialReference *OGRAVCE00DataSource::DSGetSpatialRef() { if (m_bSRSFetched) return poSRS; m_bSRSFetched = true; if (psE00 == nullptr) return nullptr; for( int iSection = 0; iSection < psE00->numSections; iSection++ ) { AVCE00Section *psSec = psE00->pasSections + iSection; if (psSec->eType == AVCFilePRJ ) { AVCE00ReadGotoSectionE00(psE00, psSec, 0); void* obj = AVCE00ReadNextObjectE00(psE00); if( psE00->hParseInfo->eFileType == AVCFilePRJ ) { char **pszPRJ = static_cast<char **>(obj); if( pszPRJ ) { poSRS = new OGRSpatialReference(); poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); if( poSRS->importFromESRI( pszPRJ ) != OGRERR_NONE ) { CPLError( CE_Warning, CPLE_AppDefined, "Failed to parse PRJ section, ignoring." ); delete poSRS; poSRS = nullptr; } } } break; } } return poSRS; }
#include "ShaderStorageBuffer.h" #include "GlobalDeviceObjects.h" bool ShaderStorageBuffer::Init(const std::shared_ptr<Device>& pDevice, const std::shared_ptr<ShaderStorageBuffer>& pSelf, uint32_t numBytes) { VkBufferCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; uint32_t minAlign = (uint32_t)GetPhysicalDevice()->GetPhysicalDeviceProperties().limits.minStorageBufferOffsetAlignment; uint32_t totalUniformBytes = numBytes / minAlign * minAlign + (numBytes % minAlign > 0 ? minAlign : 0); info.size = totalUniformBytes; if (!SharedBuffer::Init(pDevice, pSelf, info)) return false; // FIXME: add them back when necessary m_accessStages = VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | //VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | //VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | //VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; m_accessFlags = VK_ACCESS_SHADER_READ_BIT; return true; } std::shared_ptr<ShaderStorageBuffer> ShaderStorageBuffer::Create(const std::shared_ptr<Device>& pDevice, uint32_t numBytes) { std::shared_ptr<ShaderStorageBuffer> pSSBO = std::make_shared<ShaderStorageBuffer>(); if (pSSBO.get() && pSSBO->Init(pDevice, pSSBO, numBytes)) return pSSBO; return nullptr; } std::shared_ptr<BufferKey> ShaderStorageBuffer::AcquireBuffer(uint32_t numBytes) { return ShaderStorageBufferMgr()->AllocateBuffer(numBytes); }
// Boost.Geometry (aka GGL, Generic Geometry Library) // Unit Test // Copyright (c) 2014, Oracle and/or its affiliates. // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #ifndef BOOST_TEST_MODULE #define BOOST_TEST_MODULE test_point_iterator #endif #include <cstddef> #include <iostream> #include <string> #include <iterator> #include <algorithm> #include <boost/test/included/unit_test.hpp> #include <boost/assign/list_of.hpp> #include <boost/core/ignore_unused.hpp> #include <boost/tuple/tuple.hpp> #include <boost/geometry/core/point_type.hpp> #include <boost/geometry/multi/core/point_type.hpp> #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry/geometries/adapted/boost_tuple.hpp> #include <boost/geometry/multi/geometries/multi_geometries.hpp> #include <boost/geometry/multi/geometries/register/multi_point.hpp> #include <boost/geometry/algorithms/equals.hpp> #include <boost/geometry/algorithms/num_points.hpp> #include <boost/geometry/multi/algorithms/num_points.hpp> #include <boost/geometry/policies/compare.hpp> #include <boost/geometry/io/wkt/wkt.hpp> #include <boost/geometry/io/dsv/write.hpp> #include <boost/geometry/iterators/point_iterator.hpp> #include <boost/geometry/iterators/point_reverse_iterator.hpp> namespace bg = ::boost::geometry; namespace ba = ::boost::assign; typedef bg::model::point<double, 2, bg::cs::cartesian> point_type; typedef bg::model::point<double, 3, bg::cs::cartesian> point_type_3d; typedef bg::model::linestring<point_type> linestring_type; typedef bg::model::polygon<point_type, false, false> polygon_type; //ccw, open // multi geometries typedef bg::model::multi_point<point_type> multi_point_type; typedef bg::model::multi_point<point_type_3d> multi_point_type_3d; typedef bg::model::multi_linestring<linestring_type> multi_linestring_type; typedef bg::model::multi_polygon<polygon_type> multi_polygon_type; typedef boost::tuple<double, double> tuple_point_type; typedef boost::tuple<double, double, double> tuple_point_type_3d; typedef std::vector<tuple_point_type> tuple_multi_point_type; typedef std::vector<tuple_point_type_3d> tuple_multi_point_type_3d; BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian) BOOST_GEOMETRY_REGISTER_MULTI_POINT(tuple_multi_point_type) BOOST_GEOMETRY_REGISTER_MULTI_POINT(tuple_multi_point_type_3d) template <typename Geometry> inline Geometry from_wkt(std::string const& wkt) { Geometry geometry; boost::geometry::read_wkt(wkt, geometry); return geometry; } template <typename Iterator> inline std::ostream& print_point_range(std::ostream& os, Iterator first, Iterator beyond, std::string const& header) { os << header << "("; for (Iterator it = first; it != beyond; ++it) { os << " " << bg::dsv(*it); } os << " )"; return os; } struct equals { template <typename Iterator> static inline std::size_t number_of_elements(Iterator begin, Iterator end) { std::size_t size = std::distance(begin, end); std::size_t num_elems(0); for (Iterator it = begin; it != end; ++it) { ++num_elems; } BOOST_CHECK( size == num_elems ); num_elems = 0; for (Iterator it = end; it != begin; --it) { ++num_elems; } BOOST_CHECK( size == num_elems ); return num_elems; } template <typename Iterator1, typename Iterator2> static inline bool apply(Iterator1 begin1, Iterator1 end1, Iterator2 begin2, Iterator2 end2) { std::size_t num_points1 = number_of_elements(begin1, end1); std::size_t num_points2 = number_of_elements(begin2, end2); if ( num_points1 != num_points2 ) { return false; } Iterator1 it1 = begin1; Iterator2 it2 = begin2; for (; it1 != end1; ++it1, ++it2) { if ( !bg::equals(*it1, *it2) ) { return false; } } return true; } }; struct test_assignment { template <typename Iterator, typename ConstIterator, typename Value> static inline void apply(Iterator it, ConstIterator cit, Value const& value1, Value const& value2) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "== before assignment ==" << std::endl; std::cout << "value1: " << bg::wkt(value1) << std::endl; std::cout << "value2: " << bg::wkt(value2) << std::endl; std::cout << "*it : " << bg::wkt(*it) << std::endl; std::cout << "*cit : " << bg::wkt(*cit) << std::endl; #endif BOOST_CHECK( bg::equals(*it, value1) ); BOOST_CHECK( !bg::equals(*it, value2) ); BOOST_CHECK( bg::equals(*cit, value1) ); BOOST_CHECK( !bg::equals(*cit, value2) ); *it = value2; BOOST_CHECK( bg::equals(*it, value2) ); BOOST_CHECK( !bg::equals(*it, value1) ); BOOST_CHECK( bg::equals(*cit, value2) ); BOOST_CHECK( !bg::equals(*cit, value1) ); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "== after 1st assignment ==" << std::endl; std::cout << "value1: " << bg::wkt(value1) << std::endl; std::cout << "value2: " << bg::wkt(value2) << std::endl; std::cout << "*it : " << bg::wkt(*it) << std::endl; std::cout << "*cit : " << bg::wkt(*cit) << std::endl; #endif *it = value1; BOOST_CHECK( bg::equals(*it, value1) ); BOOST_CHECK( !bg::equals(*it, value2) ); BOOST_CHECK( bg::equals(*cit, value1) ); BOOST_CHECK( !bg::equals(*cit, value2) ); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "== after 2nd assignment ==" << std::endl; std::cout << "value1: " << bg::wkt(value1) << std::endl; std::cout << "value2: " << bg::wkt(value2) << std::endl; std::cout << "*it : " << bg::wkt(*it) << std::endl; std::cout << "*cit : " << bg::wkt(*cit) << std::endl; std::cout << std::endl; #endif } }; template <typename Geometry, typename PointRange> struct test_point_iterator_of_geometry { template <typename G> static inline void base_test(G& geometry, PointRange const& point_range, std::string const& header) { typedef bg::point_iterator<G> point_iterator; point_iterator begin = bg::points_begin(geometry); point_iterator end = bg::points_end(geometry); BOOST_CHECK( std::size_t(std::distance(begin, end)) == bg::num_points(geometry) ); BOOST_CHECK( equals::apply(begin, end, bg::points_begin(point_range), bg::points_end(point_range)) ); boost::ignore_unused(header); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << header << " geometry: " << bg::wkt(geometry) << std::endl; print_point_range(std::cout, begin, end, "point range: "); std::cout << std::endl; typedef bg::point_iterator<PointRange const> point_range_iterator; print_point_range(std::cout, bg::points_begin(point_range), bg::points_end(point_range), "expected point range: "); std::cout << std::endl; #endif } static inline void apply(Geometry geometry, PointRange const& point_range) { base_test<Geometry>(geometry, point_range, "non-const"); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; #endif base_test<Geometry const>(geometry, point_range, "const"); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl; #endif // testing construction of const and non-const iterator typedef bg::point_iterator<Geometry> point_iterator; typedef bg::point_iterator<Geometry const> const_point_iterator; point_iterator begin = bg::points_begin(geometry); point_iterator end = bg::points_end(geometry); const_point_iterator const_begin = bg::points_begin(geometry); const_point_iterator const_end = bg::points_end(geometry); // same for reverse iterator typedef bg::point_reverse_iterator<Geometry> point_reverse_iterator; typedef bg::point_reverse_iterator < Geometry const > const_point_reverse_iterator; point_reverse_iterator rbegin = bg::points_rbegin(geometry); point_reverse_iterator rend = bg::points_rend(geometry); const_point_reverse_iterator const_rbegin = bg::points_rbegin(geometry); const_point_reverse_iterator const_rend = bg::points_rend(geometry); // testing assignment of non-const to const iterator const_begin = begin; const_end = end; // testing assignment of non-const to const reverse_iterator const_rbegin = rbegin; const_rend = rend; // testing equality/inequality comparison BOOST_CHECK ( begin == const_begin ); BOOST_CHECK ( end == const_end ); if ( begin != end ) { BOOST_CHECK ( begin != const_end ); BOOST_CHECK ( const_begin != end ); } // testing equality/inequality comparison for reverse_iterator BOOST_CHECK ( rbegin == const_rbegin ); BOOST_CHECK ( rend == const_rend ); if ( rbegin != rend ) { BOOST_CHECK ( rbegin != const_rend ); BOOST_CHECK ( const_rbegin != rend ); } if ( begin != end ) { BOOST_CHECK( rbegin != rend ); point_reverse_iterator rlast(rend); --rlast; BOOST_CHECK( bg::equals(*begin, *rlast) ); point_iterator last(end); --last; BOOST_CHECK( bg::equals(*rbegin, *last) ); } // testing dereferencing/assignment if ( begin != end ) { typedef typename bg::point_type<Geometry>::type point; point p = *begin; point q = bg::make_zero<point>(); test_assignment::apply(begin, const_begin, p, q); *begin = q; test_assignment::apply(begin, const_begin, q, p); *begin = p; } // test with algorithms #ifdef BOOST_GEOMETRY_TEST_DEBUG print_point_range(std::cout, begin, end, "original:\n") << std::endl; print_point_range(std::cout, rbegin, rend, "reverse traversal:\n") << std::endl; std::cout << bg::wkt(geometry) << std::endl; std::cout << std::endl; #endif std::reverse(begin, end); #ifdef BOOST_GEOMETRY_TEST_DEBUG print_point_range(std::cout, begin, end, "reversed:\n") << std::endl; std::cout << bg::wkt(geometry) << std::endl; std::cout << std::endl; #endif std::reverse(begin, end); #ifdef BOOST_GEOMETRY_TEST_DEBUG print_point_range(std::cout, begin, end, "re-reversed:\n") << std::endl; std::cout << bg::wkt(geometry) << std::endl; std::cout << std::endl; std::cout << std::endl; #endif typedef typename std::iterator_traits < point_iterator >::value_type point; if ( const_begin != const_end ) { const_point_iterator pit_max = std::max_element(const_begin, const_end, bg::less<point>()); BOOST_CHECK( pit_max != const_end ); // to avoid warnings #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "max point: " << bg::dsv(*pit_max) << std::endl; #endif } #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl; std::cout << std::endl; std::cout << std::endl; #endif } }; //====================================================================== //====================================================================== BOOST_AUTO_TEST_CASE( test_linestring_point_iterator ) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "*** LINESTRING ***" << std::endl; #endif typedef tuple_multi_point_type TMP; typedef linestring_type L; typedef test_point_iterator_of_geometry<L, TMP> tester; tester::apply(from_wkt<L>("LINESTRING()"), TMP() ); tester::apply(from_wkt<L>("LINESTRING(3 3,4 4,5 5)"), ba::tuple_list_of(3,3)(4,4)(5,5) ); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl << std::endl; #endif } //====================================================================== //====================================================================== BOOST_AUTO_TEST_CASE( test_polygon_point_iterator ) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "*** POLYGON ***" << std::endl; #endif typedef tuple_multi_point_type TMP; typedef polygon_type P; typedef test_point_iterator_of_geometry<P, TMP> tester; tester::apply(from_wkt<P>("POLYGON()"), TMP() ); tester::apply(from_wkt<P>("POLYGON(())"), TMP() ); tester::apply(from_wkt<P>("POLYGON((1 1,9 1,9 9,1 9),(5 5,6 5,6 6,5 6))"), ba::tuple_list_of(1,1)(9,1)(9,9)(1,9)(5,5)(6,5)(6,6)(5,6) ); tester::apply(from_wkt<P>("POLYGON((3 3,4 4,5 5),(),(),(),(6 6,7 7,8 8),(),(),(9 9),())"), ba::tuple_list_of(3,3)(4,4)(5,5)(6,6)(7,7)(8,8)(9,9) ); tester::apply(from_wkt<P>("POLYGON((),(3 3,4 4,5 5),(),(),(6 6,7 7,8 8),(),(),(9 9),())"), ba::tuple_list_of(3,3)(4,4)(5,5)(6,6)(7,7)(8,8)(9,9) ); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl; #endif } //====================================================================== //====================================================================== BOOST_AUTO_TEST_CASE( test_multipoint_point_iterator ) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "*** MULTIPOINT ***" << std::endl; #endif typedef tuple_multi_point_type TMP; typedef multi_point_type MP; typedef test_point_iterator_of_geometry<MP, TMP> tester; tester::apply(from_wkt<MP>("MULTIPOINT()"), TMP() ); tester::apply(from_wkt<MP>("MULTIPOINT(3 3,4 4,5 5)"), ba::tuple_list_of(3,3)(4,4)(5,5) ); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl << std::endl; #endif } //====================================================================== //====================================================================== BOOST_AUTO_TEST_CASE( test_multipoint_3d_point_iterator ) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "*** MULTIPOINT 3D ***" << std::endl; #endif typedef tuple_multi_point_type_3d TMP; typedef multi_point_type_3d MP; typedef test_point_iterator_of_geometry<MP, TMP> tester; tester::apply(from_wkt<MP>("MULTIPOINT()"), TMP() ); tester::apply(from_wkt<MP>("MULTIPOINT(3 3 3,4 4 4,5 5 5)"), ba::tuple_list_of(3,3,3)(4,4,4)(5,5,5) ); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl << std::endl; #endif } //====================================================================== //====================================================================== BOOST_AUTO_TEST_CASE( test_multilinestring_point_iterator ) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "*** MULTILINESTRING ***" << std::endl; #endif typedef tuple_multi_point_type TMP; typedef multi_linestring_type ML; typedef test_point_iterator_of_geometry<ML, TMP> tester; tester::apply(from_wkt<ML>("MULTILINESTRING()"), TMP() ); tester::apply(from_wkt<ML>("MULTILINESTRING(())"), TMP() ); tester::apply(from_wkt<ML>("MULTILINESTRING((),(),())"), TMP() ); tester::apply(from_wkt<ML>("MULTILINESTRING((1 1,2 2,3 3),(3 3,4 4,5 5),(6 6))"), ba::tuple_list_of(1,1)(2,2)(3,3)(3,3)(4,4)(5,5)(6,6) ); tester::apply(from_wkt<ML>("MULTILINESTRING((),(),(1 1,2 2,3 3),(),(),(3 3,4 4,5 5),(),(6 6),(),(),())"), ba::tuple_list_of(1,1)(2,2)(3,3)(3,3)(4,4)(5,5)(6,6) ); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl; #endif } //====================================================================== //====================================================================== BOOST_AUTO_TEST_CASE( test_multipolygon_point_iterator ) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "*** MULTIPOLYGON ***" << std::endl; #endif typedef tuple_multi_point_type TMP; typedef multi_polygon_type MPL; typedef test_point_iterator_of_geometry<MPL, TMP> tester; tester::apply(from_wkt<MPL>("MULTIPOLYGON()"), TMP() ); tester::apply(from_wkt<MPL>("MULTIPOLYGON( () )"), TMP() ); tester::apply(from_wkt<MPL>("MULTIPOLYGON( (()) )"), TMP() ); tester::apply(from_wkt<MPL>("MULTIPOLYGON( ((),()) )"), TMP() ); tester::apply(from_wkt<MPL>("MULTIPOLYGON(((3 3,4 4,5 5),(6 6,7 7,8 8),(9 9)),((1 1,2 2,10 10),(11 11,12 12)))"), ba::tuple_list_of(3,3)(4,4)(5,5)(6,6)(7,7)(8,8)(9,9)\ (1,1)(2,2)(10,10)(11,11)(12,12) ); tester::apply(from_wkt<MPL>("MULTIPOLYGON(((3 3,4 4,5 5),(),(),(),(6 6,7 7,8 8),(),(),(9 9),()),((),(1 1,2 2,10 10),(),(),(),(11 11,12 12),(),(),(13 13),()))"), ba::tuple_list_of(3,3)(4,4)(5,5)(6,6)(7,7)(8,8)(9,9)\ (1,1)(2,2)(10,10)(11,11)(12,12)(13,13) ); tester::apply(from_wkt<MPL>("MULTIPOLYGON(((3 3,4 4,5 5),(),(),(),(6 6,7 7,8 8),(),(),(9 9),()),((),(1 1,2 2,10 10),(),(),(),(11 11,12 12),(),(),(13 13),()),((),(),()))"), ba::tuple_list_of(3,3)(4,4)(5,5)(6,6)(7,7)(8,8)(9,9)\ (1,1)(2,2)(10,10)(11,11)(12,12)(13,13) ); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl; #endif }
/****************************************************************************** ** Filename: fpoint.c ** Purpose: Abstract data type for a 2D point (floating point coords) ** Author: Dan Johnson ** History: Thu Apr 12 10:44:15 1990, DSJ, Created. ** ** (c) Copyright Hewlett-Packard Company, 1988. ** 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 Files and Type Defines ----------------------------------------------------------------------------*/ #include "const.h" #include "fpoint.h" #include <stdio.h> #include <math.h> /*---------------------------------------------------------------------------- Public Code ----------------------------------------------------------------------------*/ FLOAT32 DistanceBetween(FPOINT A, FPOINT B) { double xd = XDelta(A, B); double yd = YDelta(A, B); return sqrt(static_cast<double>(xd * xd + yd * yd)); } /** * Return the angle from Point1 to Point2 normalized to * lie in the range 0 to FullScale (where FullScale corresponds * to 2*pi or 360 degrees). * @param Point1 points to compute angle between * @param Point2 points to compute angle between * @param FullScale value to associate with 2*pi * @return none * @note Globals: none * @note Exceptions: none * @note History: Wed Mar 28 14:27:25 1990, DSJ, Created. */ FLOAT32 NormalizedAngleFrom(FPOINT *Point1, FPOINT *Point2, FLOAT32 FullScale) { FLOAT32 Angle; FLOAT32 NumRadsInCircle = 2.0 * PI; Angle = AngleFrom (*Point1, *Point2); if (Angle < 0.0) Angle += NumRadsInCircle; Angle *= FullScale / NumRadsInCircle; if (Angle < 0.0 || Angle >= FullScale) Angle = 0.0; return (Angle); }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/search/common/webservice_cache.h" #include <stddef.h> #include <stdint.h> #include "base/memory/ptr_util.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "content/public/browser/browser_context.h" namespace app_list { namespace { const unsigned int kWebserviceCacheMaxSize = 1000; const unsigned int kWebserviceCacheTimeLimitInMinutes = 1; const char kKeyResultTime[] = "time"; const char kKeyResult[] = "result"; const char kWebstoreQueryPrefix[] = "webstore:"; const char kPeopleQueryPrefix[] = "people:"; } // namespace WebserviceCache::WebserviceCache(content::BrowserContext* context) : cache_(Cache::NO_AUTO_EVICT), cache_loaded_(false) { const char kStoreDataFileName[] = "Webservice Search Cache"; const base::FilePath data_file = context->GetPath().AppendASCII(kStoreDataFileName); data_store_ = new DictionaryDataStore(data_file); data_store_->Load(base::Bind(&WebserviceCache::OnCacheLoaded, AsWeakPtr())); } WebserviceCache::~WebserviceCache() { } const CacheResult WebserviceCache::Get(QueryType type, const std::string& query) { std::string typed_query = PrependType(type, query); Cache::iterator iter = cache_.Get(typed_query); if (iter != cache_.end()) { if (base::Time::Now() - iter->second->time <= base::TimeDelta::FromMinutes(kWebserviceCacheTimeLimitInMinutes)) { return std::make_pair(FRESH, iter->second->result.get()); } else { return std::make_pair(STALE, iter->second->result.get()); } } return std::make_pair(STALE, static_cast<base::DictionaryValue*>(NULL)); } void WebserviceCache::Put(QueryType type, const std::string& query, std::unique_ptr<base::DictionaryValue> result) { if (result) { std::string typed_query = PrependType(type, query); std::unique_ptr<Payload> scoped_payload( new Payload(base::Time::Now(), std::move(result))); Payload* payload = scoped_payload.get(); cache_.Put(typed_query, std::move(scoped_payload)); // If the cache isn't loaded yet, we're fine with losing queries since // a 1000 entry cache should load really quickly so the chance of a user // already having typed a 3 character search before the cache has loaded is // very unlikely. if (cache_loaded_) { data_store_->cached_dict()->Set(typed_query, DictFromPayload(*payload)); data_store_->ScheduleWrite(); if (cache_.size() > kWebserviceCacheMaxSize) TrimCache(); } } } void WebserviceCache::OnCacheLoaded(std::unique_ptr<base::DictionaryValue>) { if (!data_store_->cached_dict()) return; std::vector<std::string> cleanup_keys; for (base::DictionaryValue::Iterator it(*data_store_->cached_dict()); !it.IsAtEnd(); it.Advance()) { const base::DictionaryValue* payload_dict; std::unique_ptr<Payload> payload(new Payload); if (!it.value().GetAsDictionary(&payload_dict) || !payload_dict || !PayloadFromDict(payload_dict, payload.get())) { // In case we don't have a valid payload associated with a given query, // clean up that query from our data store. cleanup_keys.push_back(it.key()); continue; } cache_.Put(it.key(), std::move(payload)); } if (!cleanup_keys.empty()) { for (size_t i = 0; i < cleanup_keys.size(); ++i) data_store_->cached_dict()->Remove(cleanup_keys[i], NULL); data_store_->ScheduleWrite(); } cache_loaded_ = true; } bool WebserviceCache::PayloadFromDict(const base::DictionaryValue* dict, Payload* payload) { std::string time_string; if (!dict->GetString(kKeyResultTime, &time_string)) return false; const base::DictionaryValue* result; if (!dict->GetDictionary(kKeyResult, &result)) return false; int64_t time_val; base::StringToInt64(time_string, &time_val); // The result dictionary will be owned by the cache, hence create a copy // instead of returning the original reference. The new dictionary will be // owned by our MRU cache. *payload = Payload(base::Time::FromInternalValue(time_val), base::WrapUnique(result->DeepCopy())); return true; } std::unique_ptr<base::DictionaryValue> WebserviceCache::DictFromPayload( const Payload& payload) { auto dict = base::MakeUnique<base::DictionaryValue>(); dict->SetString(kKeyResultTime, base::Int64ToString( payload.time.ToInternalValue())); // The payload will still keep ownership of it's result dict, hence put a // a copy of the result dictionary here. This dictionary will be owned by // data_store_->cached_dict(). dict->Set(kKeyResult, base::MakeUnique<base::Value>(*payload.result)); return dict; } void WebserviceCache::TrimCache() { for (Cache::size_type i = cache_.size(); i > kWebserviceCacheMaxSize; i--) { Cache::reverse_iterator rbegin = cache_.rbegin(); data_store_->cached_dict()->Remove(rbegin->first, NULL); cache_.Erase(rbegin); } data_store_->ScheduleWrite(); } std::string WebserviceCache::PrependType( QueryType type, const std::string& query) { switch (type) { case WEBSTORE: return kWebstoreQueryPrefix + query; case PEOPLE: return kPeopleQueryPrefix + query; default: return query; } } WebserviceCache::Payload::Payload(const base::Time& time, std::unique_ptr<base::DictionaryValue> result) : time(time), result(std::move(result)) {} WebserviceCache::Payload::Payload() = default; WebserviceCache::Payload::~Payload() = default; WebserviceCache::Payload& WebserviceCache::Payload::operator=(Payload&& other) { time = std::move(other.time); result = std::move(other.result); return *this; } } // namespace app_list
// (C) Copyright John Maddock 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/math/bindings/rr.hpp> #include "ntl_rr_digamma.hpp" #include <boost/math/special_functions/expint.hpp> #include <boost/math/constants/constants.hpp> #include <fstream> #include <boost/math/tools/test_data.hpp> using namespace boost::math::tools; struct expint_data_generator { boost::math::ntl::RR operator()(boost::math::ntl::RR a, boost::math::ntl::RR b) { unsigned n = boost::math::tools::real_cast<unsigned>(a); std::cout << n << " " << b << " "; boost::math::ntl::RR result = boost::math::expint(n, b); std::cout << result << std::endl; return result; } }; int main() { boost::math::ntl::RR::SetPrecision(1000); boost::math::ntl::RR::SetOutputPrecision(40); boost::math::expint(1, 0.06227754056453704833984375); std::cout << boost::math::expint(1, boost::math::ntl::RR(0.5)) << std::endl; parameter_info<boost::math::ntl::RR> arg1, arg2; test_data<boost::math::ntl::RR> data; std::cout << "Welcome.\n" "This program will generate spot tests for the expint function:\n" " expint(a, b)\n\n"; bool cont; std::string line; do{ get_user_parameter_info(arg1, "a"); get_user_parameter_info(arg2, "b"); data.insert(expint_data_generator(), arg1, arg2); std::cout << "Any more data [y/n]?"; std::getline(std::cin, line); boost::algorithm::trim(line); cont = (line == "y"); }while(cont); std::cout << "Enter name of test data file [default=expint_data.ipp]"; std::getline(std::cin, line); boost::algorithm::trim(line); if(line == "") line = "expint_data.ipp"; std::ofstream ofs(line.c_str()); write_code(ofs, data, "expint_data"); return 0; }
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common/backend_common_test.h" #include "common/py_func_graph_fetcher.h" #include "plugin/device/ascend/optimizer/ir_fusion/mul_addn_fusion.h" #include "debug/anf_ir_dump.h" namespace mindspore { namespace opt { class TestHWMulAddNFusion : public BackendCommon { public: TestHWMulAddNFusion() : get_py_fun_("gtest_input.pre_activate.mul_addn_fusion_test", true) {} ~TestHWMulAddNFusion() override = default; UT::PyFuncGraphFetcher get_py_fun_; }; TEST_F(TestHWMulAddNFusion, test_mul_addn_fusion) { FuncGraphPtr g = get_py_fun_.CallAndParseRet("test_mul_addn_fusion", "before"); std::vector<int64_t> shp{2, 2, 2, 2}; auto x_abstract = std::make_shared<abstract::AbstractTensor>(kFloat32, shp); AbstractBasePtrList args_spec_list({x_abstract, x_abstract}); auto fg = GetKernelGraph(g, args_spec_list); auto optimizer = std::make_shared<opt::GraphOptimizer>(); auto pm = std::make_shared<opt::PassManager>(); pm->AddPass(std::make_shared<opt::MulAddNFusion>()); optimizer->AddPassManager(pm); FuncGraphPtr new_graph = optimizer->Optimize(fg); FuncGraphPtr g_after = get_py_fun_.CallAndParseRet("test_mul_addn_fusion", "after"); EXPECT_TRUE(CheckEqualGraph(g_after, new_graph)); } TEST_F(TestHWMulAddNFusion, test_unmatch) { FuncGraphPtr g = get_py_fun_.CallAndParseRet("test_mul_addn_fusion", "unmatch"); std::vector<int64_t> shp{2, 2, 2, 2}; auto x_abstract = std::make_shared<abstract::AbstractTensor>(kFloat32, shp); AbstractBasePtrList args_spec_list({x_abstract, x_abstract, x_abstract}); auto fg = GetKernelGraph(g, args_spec_list); auto origin_fg = std::make_shared<session::KernelGraph>(*fg); auto optimizer = std::make_shared<opt::GraphOptimizer>(); auto pm = std::make_shared<opt::PassManager>(); pm->AddPass(std::make_shared<opt::MulAddNFusion>()); optimizer->AddPassManager(pm); FuncGraphPtr new_graph = optimizer->Optimize(fg); EXPECT_TRUE(CheckEqualGraph(origin_fg, new_graph)); } } // namespace opt } // namespace mindspore
#include <algorithm> #include <fstream> #include <regex> #include <unordered_map> #include "envoy/admin/v2alpha/memory.pb.h" #include "envoy/admin/v2alpha/server_info.pb.h" #include "envoy/json/json_object.h" #include "envoy/runtime/runtime.h" #include "envoy/stats/stats.h" #include "common/http/message_impl.h" #include "common/json/json_loader.h" #include "common/profiler/profiler.h" #include "common/protobuf/protobuf.h" #include "common/protobuf/utility.h" #include "common/stats/thread_local_store.h" #include "server/http/admin.h" #include "extensions/transport_sockets/tls/context_config_impl.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/logging.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::_; using testing::AllOf; using testing::Ge; using testing::HasSubstr; using testing::InSequence; using testing::Invoke; using testing::NiceMock; using testing::Property; using testing::Ref; using testing::Return; using testing::ReturnPointee; using testing::ReturnRef; namespace Envoy { namespace Server { class AdminStatsTest : public testing::TestWithParam<Network::Address::IpVersion> { public: AdminStatsTest() : alloc_(options_) { store_ = std::make_unique<Stats::ThreadLocalStoreImpl>(options_, alloc_); store_->addSink(sink_); } static std::string statsAsJsonHandler(std::map<std::string, uint64_t>& all_stats, const std::vector<Stats::ParentHistogramSharedPtr>& all_histograms, const bool used_only, const absl::optional<std::regex> regex = absl::nullopt) { return AdminImpl::statsAsJson(all_stats, all_histograms, used_only, regex, true /*pretty_print*/); } NiceMock<Event::MockDispatcher> main_thread_dispatcher_; NiceMock<ThreadLocal::MockInstance> tls_; Stats::StatsOptionsImpl options_; Stats::MockedTestAllocator alloc_; Stats::MockSink sink_; std::unique_ptr<Stats::ThreadLocalStoreImpl> store_; }; class AdminFilterTest : public testing::TestWithParam<Network::Address::IpVersion> { public: AdminFilterTest() : admin_(TestEnvironment::temporaryPath("envoy.prof"), server_), filter_(admin_), request_headers_{{":path", "/"}} { filter_.setDecoderFilterCallbacks(callbacks_); } NiceMock<MockInstance> server_; Stats::IsolatedStoreImpl listener_scope_; AdminImpl admin_; AdminFilter filter_; NiceMock<Http::MockStreamDecoderFilterCallbacks> callbacks_; Http::TestHeaderMapImpl request_headers_; }; INSTANTIATE_TEST_CASE_P(IpVersions, AdminStatsTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(AdminStatsTest, StatsAsJson) { InSequence s; store_->initializeThreading(main_thread_dispatcher_, tls_); Stats::Histogram& h1 = store_->histogram("h1"); Stats::Histogram& h2 = store_->histogram("h2"); EXPECT_CALL(sink_, onHistogramComplete(Ref(h1), 200)); h1.recordValue(200); EXPECT_CALL(sink_, onHistogramComplete(Ref(h2), 100)); h2.recordValue(100); store_->mergeHistograms([]() -> void {}); // Again record a new value in h1 so that it has both interval and cumulative values. // h2 should only have cumulative values. EXPECT_CALL(sink_, onHistogramComplete(Ref(h1), 100)); h1.recordValue(100); store_->mergeHistograms([]() -> void {}); EXPECT_CALL(alloc_, free(_)); std::map<std::string, uint64_t> all_stats; std::vector<Stats::ParentHistogramSharedPtr> histograms = store_->histograms(); std::sort(histograms.begin(), histograms.end(), [](const Stats::ParentHistogramSharedPtr& a, const Stats::ParentHistogramSharedPtr& b) -> bool { return a->name() < b->name(); }); std::string actual_json = statsAsJsonHandler(all_stats, histograms, false); const std::string expected_json = R"EOF({ "stats": [ { "histograms": { "supported_quantiles": [ 0.0, 25.0, 50.0, 75.0, 90.0, 95.0, 99.0, 99.5, 99.9, 100.0 ], "computed_quantiles": [ { "name": "h1", "values": [ { "interval": 100.0, "cumulative": 100.0 }, { "interval": 102.5, "cumulative": 105.0 }, { "interval": 105.0, "cumulative": 110.0 }, { "interval": 107.5, "cumulative": 205.0 }, { "interval": 109.0, "cumulative": 208.0 }, { "interval": 109.5, "cumulative": 209.0 }, { "interval": 109.9, "cumulative": 209.8 }, { "interval": 109.95, "cumulative": 209.9 }, { "interval": 109.99, "cumulative": 209.98 }, { "interval": 110.0, "cumulative": 210.0 } ] }, { "name": "h2", "values": [ { "interval": null, "cumulative": 100.0 }, { "interval": null, "cumulative": 102.5 }, { "interval": null, "cumulative": 105.0 }, { "interval": null, "cumulative": 107.5 }, { "interval": null, "cumulative": 109.0 }, { "interval": null, "cumulative": 109.5 }, { "interval": null, "cumulative": 109.9 }, { "interval": null, "cumulative": 109.95 }, { "interval": null, "cumulative": 109.99 }, { "interval": null, "cumulative": 110.0 } ] } ] } } ] })EOF"; EXPECT_EQ(expected_json, actual_json); store_->shutdownThreading(); } TEST_P(AdminStatsTest, UsedOnlyStatsAsJson) { InSequence s; store_->initializeThreading(main_thread_dispatcher_, tls_); Stats::Histogram& h1 = store_->histogram("h1"); Stats::Histogram& h2 = store_->histogram("h2"); EXPECT_EQ("h1", h1.name()); EXPECT_EQ("h2", h2.name()); EXPECT_CALL(sink_, onHistogramComplete(Ref(h1), 200)); h1.recordValue(200); store_->mergeHistograms([]() -> void {}); // Again record a new value in h1 so that it has both interval and cumulative values. // h2 should only have cumulative values. EXPECT_CALL(sink_, onHistogramComplete(Ref(h1), 100)); h1.recordValue(100); store_->mergeHistograms([]() -> void {}); EXPECT_CALL(alloc_, free(_)); std::map<std::string, uint64_t> all_stats; std::string actual_json = statsAsJsonHandler(all_stats, store_->histograms(), true); // Expected JSON should not have h2 values as it is not used. const std::string expected_json = R"EOF({ "stats": [ { "histograms": { "supported_quantiles": [ 0.0, 25.0, 50.0, 75.0, 90.0, 95.0, 99.0, 99.5, 99.9, 100.0 ], "computed_quantiles": [ { "name": "h1", "values": [ { "interval": 100.0, "cumulative": 100.0 }, { "interval": 102.5, "cumulative": 105.0 }, { "interval": 105.0, "cumulative": 110.0 }, { "interval": 107.5, "cumulative": 205.0 }, { "interval": 109.0, "cumulative": 208.0 }, { "interval": 109.5, "cumulative": 209.0 }, { "interval": 109.9, "cumulative": 209.8 }, { "interval": 109.95, "cumulative": 209.9 }, { "interval": 109.99, "cumulative": 209.98 }, { "interval": 110.0, "cumulative": 210.0 } ] } ] } } ] })EOF"; EXPECT_EQ(expected_json, actual_json); store_->shutdownThreading(); } TEST_P(AdminStatsTest, StatsAsJsonFilterString) { InSequence s; store_->initializeThreading(main_thread_dispatcher_, tls_); Stats::Histogram& h1 = store_->histogram("h1"); Stats::Histogram& h2 = store_->histogram("h2"); EXPECT_CALL(sink_, onHistogramComplete(Ref(h1), 200)); h1.recordValue(200); EXPECT_CALL(sink_, onHistogramComplete(Ref(h2), 100)); h2.recordValue(100); store_->mergeHistograms([]() -> void {}); // Again record a new value in h1 so that it has both interval and cumulative values. // h2 should only have cumulative values. EXPECT_CALL(sink_, onHistogramComplete(Ref(h1), 100)); h1.recordValue(100); store_->mergeHistograms([]() -> void {}); EXPECT_CALL(alloc_, free(_)); std::map<std::string, uint64_t> all_stats; std::string actual_json = statsAsJsonHandler(all_stats, store_->histograms(), false, absl::optional<std::regex>{std::regex("[a-z]1")}); // Because this is a filter case, we don't expect to see any stats except for those containing // "h1" in their name. const std::string expected_json = R"EOF({ "stats": [ { "histograms": { "supported_quantiles": [ 0.0, 25.0, 50.0, 75.0, 90.0, 95.0, 99.0, 99.5, 99.9, 100.0 ], "computed_quantiles": [ { "name": "h1", "values": [ { "interval": 100.0, "cumulative": 100.0 }, { "interval": 102.5, "cumulative": 105.0 }, { "interval": 105.0, "cumulative": 110.0 }, { "interval": 107.5, "cumulative": 205.0 }, { "interval": 109.0, "cumulative": 208.0 }, { "interval": 109.5, "cumulative": 209.0 }, { "interval": 109.9, "cumulative": 209.8 }, { "interval": 109.95, "cumulative": 209.9 }, { "interval": 109.99, "cumulative": 209.98 }, { "interval": 110.0, "cumulative": 210.0 } ] } ] } } ] })EOF"; EXPECT_EQ(expected_json, actual_json); store_->shutdownThreading(); } TEST_P(AdminStatsTest, UsedOnlyStatsAsJsonFilterString) { InSequence s; store_->initializeThreading(main_thread_dispatcher_, tls_); Stats::Histogram& h1 = store_->histogram("h1_matches"); // Will match, be used, and print Stats::Histogram& h2 = store_->histogram("h2_matches"); // Will match but not be used Stats::Histogram& h3 = store_->histogram("h3_not"); // Will be used but not match EXPECT_EQ("h1_matches", h1.name()); EXPECT_EQ("h2_matches", h2.name()); EXPECT_EQ("h3_not", h3.name()); EXPECT_CALL(sink_, onHistogramComplete(Ref(h1), 200)); h1.recordValue(200); EXPECT_CALL(sink_, onHistogramComplete(Ref(h3), 200)); h3.recordValue(200); store_->mergeHistograms([]() -> void {}); // Again record a new value in h1 and h3 so that they have both interval and cumulative values. // h2 should only have cumulative values. EXPECT_CALL(sink_, onHistogramComplete(Ref(h1), 100)); h1.recordValue(100); EXPECT_CALL(sink_, onHistogramComplete(Ref(h3), 100)); h3.recordValue(100); store_->mergeHistograms([]() -> void {}); EXPECT_CALL(alloc_, free(_)); std::map<std::string, uint64_t> all_stats; std::string actual_json = statsAsJsonHandler(all_stats, store_->histograms(), true, absl::optional<std::regex>{std::regex("h[12]")}); // Expected JSON should not have h2 values as it is not used, and should not have h3 values as // they are used but do not match. const std::string expected_json = R"EOF({ "stats": [ { "histograms": { "supported_quantiles": [ 0.0, 25.0, 50.0, 75.0, 90.0, 95.0, 99.0, 99.5, 99.9, 100.0 ], "computed_quantiles": [ { "name": "h1_matches", "values": [ { "interval": 100.0, "cumulative": 100.0 }, { "interval": 102.5, "cumulative": 105.0 }, { "interval": 105.0, "cumulative": 110.0 }, { "interval": 107.5, "cumulative": 205.0 }, { "interval": 109.0, "cumulative": 208.0 }, { "interval": 109.5, "cumulative": 209.0 }, { "interval": 109.9, "cumulative": 209.8 }, { "interval": 109.95, "cumulative": 209.9 }, { "interval": 109.99, "cumulative": 209.98 }, { "interval": 110.0, "cumulative": 210.0 } ] } ] } } ] })EOF"; EXPECT_EQ(expected_json, actual_json); store_->shutdownThreading(); } INSTANTIATE_TEST_CASE_P(IpVersions, AdminFilterTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(AdminFilterTest, HeaderOnly) { EXPECT_CALL(callbacks_, encodeHeaders_(_, false)); EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, filter_.decodeHeaders(request_headers_, true)); } TEST_P(AdminFilterTest, Body) { InSequence s; EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, filter_.decodeHeaders(request_headers_, false)); Buffer::OwnedImpl data("hello"); EXPECT_CALL(callbacks_, addDecodedData(_, false)); EXPECT_CALL(callbacks_, encodeHeaders_(_, false)); EXPECT_EQ(Http::FilterDataStatus::StopIterationNoBuffer, filter_.decodeData(data, true)); } TEST_P(AdminFilterTest, Trailers) { InSequence s; EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, filter_.decodeHeaders(request_headers_, false)); Buffer::OwnedImpl data("hello"); EXPECT_CALL(callbacks_, addDecodedData(_, false)); EXPECT_EQ(Http::FilterDataStatus::StopIterationNoBuffer, filter_.decodeData(data, false)); EXPECT_CALL(callbacks_, decodingBuffer()); filter_.getRequestBody(); EXPECT_CALL(callbacks_, encodeHeaders_(_, false)); EXPECT_EQ(Http::FilterTrailersStatus::StopIteration, filter_.decodeTrailers(request_headers_)); } class AdminInstanceTest : public testing::TestWithParam<Network::Address::IpVersion> { public: AdminInstanceTest() : address_out_path_(TestEnvironment::temporaryPath("admin.address")), cpu_profile_path_(TestEnvironment::temporaryPath("envoy.prof")), admin_(cpu_profile_path_, server_), request_headers_{{":path", "/"}}, admin_filter_(admin_) { admin_.startHttpListener("/dev/null", address_out_path_, Network::Test::getCanonicalLoopbackAddress(GetParam()), listener_scope_.createScope("listener.admin.")); EXPECT_EQ(std::chrono::milliseconds(100), admin_.drainTimeout()); admin_.tracingStats().random_sampling_.inc(); EXPECT_TRUE(admin_.setCurrentClientCertDetails().empty()); } Http::Code runCallback(absl::string_view path_and_query, Http::HeaderMap& response_headers, Buffer::Instance& response, absl::string_view method) { request_headers_.insertMethod().value(method.data(), method.size()); admin_filter_.decodeHeaders(request_headers_, false); return admin_.runCallback(path_and_query, response_headers, response, admin_filter_); } Http::Code getCallback(absl::string_view path_and_query, Http::HeaderMap& response_headers, Buffer::Instance& response) { return runCallback(path_and_query, response_headers, response, Http::Headers::get().MethodValues.Get); } Http::Code postCallback(absl::string_view path_and_query, Http::HeaderMap& response_headers, Buffer::Instance& response) { return runCallback(path_and_query, response_headers, response, Http::Headers::get().MethodValues.Post); } std::string address_out_path_; std::string cpu_profile_path_; NiceMock<MockInstance> server_; Stats::IsolatedStoreImpl listener_scope_; AdminImpl admin_; Http::TestHeaderMapImpl request_headers_; Server::AdminFilter admin_filter_; }; INSTANTIATE_TEST_CASE_P(IpVersions, AdminInstanceTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(AdminInstanceTest, AdminProfiler) { Buffer::OwnedImpl data; Http::HeaderMapImpl header_map; // Can only get code coverage of AdminImpl::handlerCpuProfiler stopProfiler with // a real profiler linked in (successful call to startProfiler). #ifdef PROFILER_AVAILABLE EXPECT_EQ(Http::Code::OK, postCallback("/cpuprofiler?enable=y", header_map, data)); EXPECT_TRUE(Profiler::Cpu::profilerEnabled()); #else EXPECT_EQ(Http::Code::InternalServerError, postCallback("/cpuprofiler?enable=y", header_map, data)); EXPECT_FALSE(Profiler::Cpu::profilerEnabled()); #endif EXPECT_EQ(Http::Code::OK, postCallback("/cpuprofiler?enable=n", header_map, data)); EXPECT_FALSE(Profiler::Cpu::profilerEnabled()); } TEST_P(AdminInstanceTest, MutatesErrorWithGet) { Buffer::OwnedImpl data; Http::HeaderMapImpl header_map; const std::string path("/healthcheck/fail"); // TODO(jmarantz): the call to getCallback should be made to fail, but as an interim we will // just issue a warning, so that scripts using curl GET comamnds to mutate state can be fixed. EXPECT_LOG_CONTAINS("error", "admin path \"" + path + "\" mutates state, method=GET rather than POST", EXPECT_EQ(Http::Code::BadRequest, getCallback(path, header_map, data))); } TEST_P(AdminInstanceTest, AdminBadProfiler) { Buffer::OwnedImpl data; AdminImpl admin_bad_profile_path(TestEnvironment::temporaryPath("some/unlikely/bad/path.prof"), server_); Http::HeaderMapImpl header_map; const absl::string_view post = Http::Headers::get().MethodValues.Post; request_headers_.insertMethod().value(post.data(), post.size()); admin_filter_.decodeHeaders(request_headers_, false); EXPECT_NO_LOGS(EXPECT_EQ(Http::Code::InternalServerError, admin_bad_profile_path.runCallback("/cpuprofiler?enable=y", header_map, data, admin_filter_))); EXPECT_FALSE(Profiler::Cpu::profilerEnabled()); } TEST_P(AdminInstanceTest, WriteAddressToFile) { std::ifstream address_file(address_out_path_); std::string address_from_file; std::getline(address_file, address_from_file); EXPECT_EQ(admin_.socket().localAddress()->asString(), address_from_file); } TEST_P(AdminInstanceTest, AdminBadAddressOutPath) { std::string bad_path = TestEnvironment::temporaryPath("some/unlikely/bad/path/admin.address"); AdminImpl admin_bad_address_out_path(cpu_profile_path_, server_); EXPECT_LOG_CONTAINS( "critical", "cannot open admin address output file " + bad_path + " for writing.", admin_bad_address_out_path.startHttpListener( "/dev/null", bad_path, Network::Test::getCanonicalLoopbackAddress(GetParam()), listener_scope_.createScope("listener.admin."))); EXPECT_FALSE(std::ifstream(bad_path)); } TEST_P(AdminInstanceTest, CustomHandler) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; // Test removable handler. EXPECT_NO_LOGS(EXPECT_TRUE(admin_.addHandler("/foo/bar", "hello", callback, true, false))); Http::HeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); // Test that removable handler gets removed. EXPECT_TRUE(admin_.removeHandler("/foo/bar")); EXPECT_EQ(Http::Code::NotFound, getCallback("/foo/bar", header_map, response)); EXPECT_FALSE(admin_.removeHandler("/foo/bar")); // Add non removable handler. EXPECT_TRUE(admin_.addHandler("/foo/bar", "hello", callback, false, false)); EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); // Add again and make sure it is not there twice. EXPECT_FALSE(admin_.addHandler("/foo/bar", "hello", callback, false, false)); // Try to remove non removable handler, and make sure it is not removed. EXPECT_FALSE(admin_.removeHandler("/foo/bar")); EXPECT_EQ(Http::Code::Accepted, getCallback("/foo/bar", header_map, response)); } TEST_P(AdminInstanceTest, RejectHandlerWithXss) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; EXPECT_LOG_CONTAINS("error", "filter \"/foo<script>alert('hi')</script>\" contains invalid character '<'", EXPECT_FALSE(admin_.addHandler("/foo<script>alert('hi')</script>", "hello", callback, true, false))); } TEST_P(AdminInstanceTest, RejectHandlerWithEmbeddedQuery) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; EXPECT_LOG_CONTAINS("error", "filter \"/bar?queryShouldNotBeInPrefix\" contains invalid character '?'", EXPECT_FALSE(admin_.addHandler("/bar?queryShouldNotBeInPrefix", "hello", callback, true, false))); } TEST_P(AdminInstanceTest, EscapeHelpTextWithPunctuation) { auto callback = [](absl::string_view, Http::HeaderMap&, Buffer::Instance&, AdminStream&) -> Http::Code { return Http::Code::Accepted; }; // It's OK to have help text with HTML characters in it, but when we render the home // page they need to be escaped. const std::string planets = "jupiter>saturn>mars"; EXPECT_TRUE(admin_.addHandler("/planets", planets, callback, true, false)); Http::HeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::OK, getCallback("/", header_map, response)); Http::HeaderString& content_type = header_map.ContentType()->value(); EXPECT_THAT(std::string(content_type.getStringView()), testing::HasSubstr("text/html")); EXPECT_EQ(-1, response.search(planets.data(), planets.size(), 0)); const std::string escaped_planets = "jupiter&gt;saturn&gt;mars"; EXPECT_NE(-1, response.search(escaped_planets.data(), escaped_planets.size(), 0)); } TEST_P(AdminInstanceTest, HelpUsesFormForMutations) { Http::HeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::OK, getCallback("/", header_map, response)); const std::string logging_action = "<form action='logging' method='post'"; const std::string stats_href = "<a href='stats'"; EXPECT_NE(-1, response.search(logging_action.data(), logging_action.size(), 0)); EXPECT_NE(-1, response.search(stats_href.data(), stats_href.size(), 0)); } TEST_P(AdminInstanceTest, ConfigDump) { Buffer::OwnedImpl response; Http::HeaderMapImpl header_map; auto entry = admin_.getConfigTracker().add("foo", [] { auto msg = std::make_unique<ProtobufWkt::StringValue>(); msg->set_value("bar"); return msg; }); const std::string expected_json = R"EOF({ "configs": [ { "@type": "type.googleapis.com/google.protobuf.StringValue", "value": "bar" } ] } )EOF"; EXPECT_EQ(Http::Code::OK, getCallback("/config_dump", header_map, response)); std::string output = response.toString(); EXPECT_EQ(expected_json, output); } TEST_P(AdminInstanceTest, ConfigDumpMaintainsOrder) { // Add configs in random order and validate config_dump dumps in the order. auto bootstrap_entry = admin_.getConfigTracker().add("bootstrap", [] { auto msg = std::make_unique<ProtobufWkt::StringValue>(); msg->set_value("bootstrap_config"); return msg; }); auto route_entry = admin_.getConfigTracker().add("routes", [] { auto msg = std::make_unique<ProtobufWkt::StringValue>(); msg->set_value("routes_config"); return msg; }); auto listener_entry = admin_.getConfigTracker().add("listeners", [] { auto msg = std::make_unique<ProtobufWkt::StringValue>(); msg->set_value("listeners_config"); return msg; }); auto cluster_entry = admin_.getConfigTracker().add("clusters", [] { auto msg = std::make_unique<ProtobufWkt::StringValue>(); msg->set_value("clusters_config"); return msg; }); const std::string expected_json = R"EOF({ "configs": [ { "@type": "type.googleapis.com/google.protobuf.StringValue", "value": "bootstrap_config" }, { "@type": "type.googleapis.com/google.protobuf.StringValue", "value": "clusters_config" }, { "@type": "type.googleapis.com/google.protobuf.StringValue", "value": "listeners_config" }, { "@type": "type.googleapis.com/google.protobuf.StringValue", "value": "routes_config" } ] } )EOF"; // Run it multiple times and validate that order is preserved. for (size_t i = 0; i < 5; i++) { Buffer::OwnedImpl response; Http::HeaderMapImpl header_map; EXPECT_EQ(Http::Code::OK, getCallback("/config_dump", header_map, response)); const std::string output = response.toString(); EXPECT_EQ(expected_json, output); } } TEST_P(AdminInstanceTest, Memory) { Http::HeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::OK, getCallback("/memory", header_map, response)); const std::string output_json = response.toString(); envoy::admin::v2alpha::Memory output_proto; MessageUtil::loadFromJson(output_json, output_proto); EXPECT_THAT(output_proto, AllOf(Property(&envoy::admin::v2alpha::Memory::allocated, Ge(0)), Property(&envoy::admin::v2alpha::Memory::heap_size, Ge(0)), Property(&envoy::admin::v2alpha::Memory::pageheap_unmapped, Ge(0)), Property(&envoy::admin::v2alpha::Memory::pageheap_free, Ge(0)), Property(&envoy::admin::v2alpha::Memory::total_thread_cache, Ge(0)))); } TEST_P(AdminInstanceTest, ContextThatReturnsNullCertDetails) { Http::HeaderMapImpl header_map; Buffer::OwnedImpl response; // Setup a context that returns null cert details. testing::NiceMock<Server::Configuration::MockTransportSocketFactoryContext> factory_context; Json::ObjectSharedPtr loader = TestEnvironment::jsonLoadFromString("{}"); Extensions::TransportSockets::Tls::ClientContextConfigImpl cfg(*loader, factory_context); Stats::IsolatedStoreImpl store; Envoy::Ssl::ClientContextSharedPtr client_ctx( server_.sslContextManager().createSslClientContext(store, cfg)); const std::string expected_empty_json = R"EOF({ "certificates": [ { "ca_cert": [], "cert_chain": [] } ] } )EOF"; // Validate that cert details are null and /certs handles it correctly. EXPECT_EQ(nullptr, client_ctx->getCaCertInformation()); EXPECT_TRUE(client_ctx->getCertChainInformation().empty()); EXPECT_EQ(Http::Code::OK, getCallback("/certs", header_map, response)); EXPECT_EQ(expected_empty_json, response.toString()); } TEST_P(AdminInstanceTest, Runtime) { Http::HeaderMapImpl header_map; Buffer::OwnedImpl response; Runtime::MockSnapshot snapshot; Runtime::MockLoader loader; auto layer1 = std::make_unique<NiceMock<Runtime::MockOverrideLayer>>(); auto layer2 = std::make_unique<NiceMock<Runtime::MockOverrideLayer>>(); std::unordered_map<std::string, Runtime::Snapshot::Entry> entries2{ {"string_key", {"override", {}, {}}}, {"extra_key", {"bar", {}, {}}}}; std::unordered_map<std::string, Runtime::Snapshot::Entry> entries1{ {"string_key", {"foo", {}, {}}}, {"int_key", {"1", 1, {}}}, {"other_key", {"bar", {}, {}}}}; ON_CALL(*layer1, name()).WillByDefault(testing::ReturnRefOfCopy(std::string{"layer1"})); ON_CALL(*layer1, values()).WillByDefault(testing::ReturnRef(entries1)); ON_CALL(*layer2, name()).WillByDefault(testing::ReturnRefOfCopy(std::string{"layer2"})); ON_CALL(*layer2, values()).WillByDefault(testing::ReturnRef(entries2)); std::vector<Runtime::Snapshot::OverrideLayerConstPtr> layers; layers.push_back(std::move(layer1)); layers.push_back(std::move(layer2)); EXPECT_CALL(snapshot, getLayers()).WillRepeatedly(testing::ReturnRef(layers)); const std::string expected_json = R"EOF({ "layers": [ "layer1", "layer2" ], "entries": { "extra_key": { "layer_values": [ "", "bar" ], "final_value": "bar" }, "int_key": { "layer_values": [ "1", "" ], "final_value": "1" }, "other_key": { "layer_values": [ "bar", "" ], "final_value": "bar" }, "string_key": { "layer_values": [ "foo", "override" ], "final_value": "override" } } })EOF"; EXPECT_CALL(loader, snapshot()).WillRepeatedly(testing::ReturnPointee(&snapshot)); EXPECT_CALL(server_, runtime()).WillRepeatedly(testing::ReturnPointee(&loader)); EXPECT_EQ(Http::Code::OK, getCallback("/runtime", header_map, response)); EXPECT_EQ(expected_json, response.toString()); } TEST_P(AdminInstanceTest, RuntimeModify) { Http::HeaderMapImpl header_map; Buffer::OwnedImpl response; Runtime::MockLoader loader; EXPECT_CALL(server_, runtime()).WillRepeatedly(testing::ReturnPointee(&loader)); std::unordered_map<std::string, std::string> overrides; overrides["foo"] = "bar"; overrides["x"] = "42"; overrides["nothing"] = ""; EXPECT_CALL(loader, mergeValues(overrides)).Times(1); EXPECT_EQ(Http::Code::OK, postCallback("/runtime_modify?foo=bar&x=42&nothing=", header_map, response)); EXPECT_EQ("OK\n", response.toString()); } TEST_P(AdminInstanceTest, RuntimeModifyNoArguments) { Http::HeaderMapImpl header_map; Buffer::OwnedImpl response; EXPECT_EQ(Http::Code::BadRequest, postCallback("/runtime_modify", header_map, response)); EXPECT_TRUE(absl::StartsWith(response.toString(), "usage:")); } TEST_P(AdminInstanceTest, TracingStatsDisabled) { const std::string& name = admin_.tracingStats().service_forced_.name(); for (Stats::CounterSharedPtr counter : server_.stats().counters()) { EXPECT_NE(counter->name(), name) << "Unexpected tracing stat found in server stats: " << name; } } TEST_P(AdminInstanceTest, ClustersJson) { Upstream::ClusterManager::ClusterInfoMap cluster_map; ON_CALL(server_.cluster_manager_, clusters()).WillByDefault(ReturnPointee(&cluster_map)); NiceMock<Upstream::MockCluster> cluster; cluster_map.emplace(cluster.info_->name_, cluster); NiceMock<Upstream::Outlier::MockDetector> outlier_detector; ON_CALL(Const(cluster), outlierDetector()).WillByDefault(Return(&outlier_detector)); ON_CALL(outlier_detector, successRateEjectionThreshold()).WillByDefault(Return(6.0)); ON_CALL(*cluster.info_, addedViaApi()).WillByDefault(Return(true)); Upstream::MockHostSet* host_set = cluster.priority_set_.getMockHostSet(0); auto host = std::make_shared<NiceMock<Upstream::MockHost>>(); envoy::api::v2::core::Locality locality; locality.set_region("test_region"); locality.set_zone("test_zone"); locality.set_sub_zone("test_sub_zone"); ON_CALL(*host, locality()).WillByDefault(ReturnRef(locality)); host_set->hosts_.emplace_back(host); Network::Address::InstanceConstSharedPtr address = Network::Utility::resolveUrl("tcp://1.2.3.4:80"); ON_CALL(*host, address()).WillByDefault(Return(address)); // Add stats in random order and validate that they come in order. Stats::IsolatedStoreImpl store; store.counter("test_counter").add(10); store.counter("rest_counter").add(10); store.counter("arest_counter").add(5); store.gauge("test_gauge").set(11); store.gauge("atest_gauge").set(10); ON_CALL(*host, gauges()).WillByDefault(Invoke([&store]() { return store.gauges(); })); ON_CALL(*host, counters()).WillByDefault(Invoke([&store]() { return store.counters(); })); ON_CALL(*host, healthFlagGet(Upstream::Host::HealthFlag::FAILED_ACTIVE_HC)) .WillByDefault(Return(true)); ON_CALL(*host, healthFlagGet(Upstream::Host::HealthFlag::FAILED_OUTLIER_CHECK)) .WillByDefault(Return(true)); ON_CALL(*host, healthFlagGet(Upstream::Host::HealthFlag::FAILED_EDS_HEALTH)) .WillByDefault(Return(false)); ON_CALL(*host, healthFlagGet(Upstream::Host::HealthFlag::DEGRADED_ACTIVE_HC)) .WillByDefault(Return(true)); ON_CALL(host->outlier_detector_, successRate()).WillByDefault(Return(43.2)); ON_CALL(*host, weight()).WillByDefault(Return(5)); Buffer::OwnedImpl response; Http::HeaderMapImpl header_map; EXPECT_EQ(Http::Code::OK, getCallback("/clusters?format=json", header_map, response)); std::string output_json = response.toString(); envoy::admin::v2alpha::Clusters output_proto; MessageUtil::loadFromJson(output_json, output_proto); const std::string expected_json = R"EOF({ "cluster_statuses": [ { "name": "fake_cluster", "success_rate_ejection_threshold": { "value": 6 }, "added_via_api": true, "host_statuses": [ { "address": { "socket_address": { "protocol": "TCP", "address": "1.2.3.4", "port_value": 80 } }, "stats": [ { "name": "arest_counter", "value": "5", "type": "COUNTER" }, { "name": "rest_counter", "value": "10", "type": "COUNTER" }, { "name": "test_counter", "value": "10", "type": "COUNTER" }, { "name": "atest_gauge", "value": "10", "type": "GAUGE" }, { "name": "test_gauge", "value": "11", "type": "GAUGE" }, ], "health_status": { "eds_health_status": "HEALTHY", "failed_active_health_check": true, "failed_outlier_check": true, "failed_active_degraded_check": true }, "success_rate": { "value": 43.2 }, "weight": 5 } ] } ] } )EOF"; envoy::admin::v2alpha::Clusters expected_proto; MessageUtil::loadFromJson(expected_json, expected_proto); // Ensure the protos created from each JSON are equivalent. EXPECT_THAT(output_proto, ProtoEq(expected_proto)); // Ensure that the normal text format is used by default. EXPECT_EQ(Http::Code::OK, getCallback("/clusters", header_map, response)); std::string text_output = response.toString(); envoy::admin::v2alpha::Clusters failed_conversion_proto; EXPECT_THROW(MessageUtil::loadFromJson(text_output, failed_conversion_proto), EnvoyException); } TEST_P(AdminInstanceTest, GetRequest) { EXPECT_CALL(server_.options_, toCommandLineOptions()).WillRepeatedly(Invoke([] { Server::CommandLineOptionsPtr command_line_options = std::make_unique<envoy::admin::v2alpha::CommandLineOptions>(); command_line_options->set_restart_epoch(2); command_line_options->set_service_cluster("cluster"); return command_line_options; })); NiceMock<Init::MockManager> initManager; ON_CALL(server_, initManager()).WillByDefault(ReturnRef(initManager)); { Http::HeaderMapImpl response_headers; std::string body; ON_CALL(initManager, state()).WillByDefault(Return(Init::Manager::State::Initialized)); EXPECT_EQ(Http::Code::OK, admin_.request("/server_info", "GET", response_headers, body)); envoy::admin::v2alpha::ServerInfo server_info_proto; EXPECT_THAT(std::string(response_headers.ContentType()->value().getStringView()), HasSubstr("application/json")); // We only test that it parses as the proto and that some fields are correct, since // values such as timestamps + Envoy version are tricky to test for. MessageUtil::loadFromJson(body, server_info_proto); EXPECT_EQ(server_info_proto.state(), envoy::admin::v2alpha::ServerInfo::LIVE); EXPECT_EQ(server_info_proto.command_line_options().restart_epoch(), 2); EXPECT_EQ(server_info_proto.command_line_options().service_cluster(), "cluster"); } { Http::HeaderMapImpl response_headers; std::string body; ON_CALL(initManager, state()).WillByDefault(Return(Init::Manager::State::NotInitialized)); EXPECT_EQ(Http::Code::OK, admin_.request("/server_info", "GET", response_headers, body)); envoy::admin::v2alpha::ServerInfo server_info_proto; EXPECT_THAT(std::string(response_headers.ContentType()->value().getStringView()), HasSubstr("application/json")); // We only test that it parses as the proto and that some fields are correct, since // values such as timestamps + Envoy version are tricky to test for. MessageUtil::loadFromJson(body, server_info_proto); EXPECT_EQ(server_info_proto.state(), envoy::admin::v2alpha::ServerInfo::PRE_INITIALIZING); EXPECT_EQ(server_info_proto.command_line_options().restart_epoch(), 2); EXPECT_EQ(server_info_proto.command_line_options().service_cluster(), "cluster"); } Http::HeaderMapImpl response_headers; std::string body; ON_CALL(initManager, state()).WillByDefault(Return(Init::Manager::State::Initializing)); EXPECT_EQ(Http::Code::OK, admin_.request("/server_info", "GET", response_headers, body)); envoy::admin::v2alpha::ServerInfo server_info_proto; EXPECT_THAT(std::string(response_headers.ContentType()->value().getStringView()), HasSubstr("application/json")); // We only test that it parses as the proto and that some fields are correct, since // values such as timestamps + Envoy version are tricky to test for. MessageUtil::loadFromJson(body, server_info_proto); EXPECT_EQ(server_info_proto.state(), envoy::admin::v2alpha::ServerInfo::INITIALIZING); EXPECT_EQ(server_info_proto.command_line_options().restart_epoch(), 2); EXPECT_EQ(server_info_proto.command_line_options().service_cluster(), "cluster"); } TEST_P(AdminInstanceTest, GetRequestJson) { Http::HeaderMapImpl response_headers; std::string body; EXPECT_EQ(Http::Code::OK, admin_.request("/stats?format=json", "GET", response_headers, body)); EXPECT_THAT(body, HasSubstr("{\"stats\":[")); EXPECT_THAT(std::string(response_headers.ContentType()->value().getStringView()), HasSubstr("application/json")); } TEST_P(AdminInstanceTest, PostRequest) { Http::HeaderMapImpl response_headers; std::string body; EXPECT_NO_LOGS(EXPECT_EQ(Http::Code::OK, admin_.request("/healthcheck/fail", "POST", response_headers, body))); EXPECT_EQ(body, "OK\n"); EXPECT_THAT(std::string(response_headers.ContentType()->value().getStringView()), HasSubstr("text/plain")); } class PrometheusStatsFormatterTest : public testing::Test { protected: PrometheusStatsFormatterTest() /*: alloc_(stats_options_)*/ {} void addCounter(const std::string& name, std::vector<Stats::Tag> cluster_tags) { std::string tname = std::string(name); counters_.push_back(alloc_.makeCounter(name, std::move(tname), std::move(cluster_tags))); } void addGauge(const std::string& name, std::vector<Stats::Tag> cluster_tags) { std::string tname = std::string(name); gauges_.push_back(alloc_.makeGauge(name, std::move(tname), std::move(cluster_tags))); } Stats::StatsOptionsImpl stats_options_; Stats::HeapStatDataAllocator alloc_; std::vector<Stats::CounterSharedPtr> counters_; std::vector<Stats::GaugeSharedPtr> gauges_; }; TEST_F(PrometheusStatsFormatterTest, MetricName) { std::string raw = "vulture.eats-liver"; std::string expected = "envoy_vulture_eats_liver"; auto actual = PrometheusStatsFormatter::metricName(raw); EXPECT_EQ(expected, actual); } TEST_F(PrometheusStatsFormatterTest, SanitizeMetricName) { std::string raw = "An.artist.plays-violin@019street"; std::string expected = "envoy_An_artist_plays_violin_019street"; auto actual = PrometheusStatsFormatter::metricName(raw); EXPECT_EQ(expected, actual); } TEST_F(PrometheusStatsFormatterTest, SanitizeMetricNameDigitFirst) { std::string raw = "3.artists.play-violin@019street"; std::string expected = "envoy_3_artists_play_violin_019street"; auto actual = PrometheusStatsFormatter::metricName(raw); EXPECT_EQ(expected, actual); } TEST_F(PrometheusStatsFormatterTest, FormattedTags) { std::vector<Stats::Tag> tags; Stats::Tag tag1 = {"a.tag-name", "a.tag-value"}; Stats::Tag tag2 = {"another_tag_name", "another_tag-value"}; tags.push_back(tag1); tags.push_back(tag2); std::string expected = "a_tag_name=\"a.tag-value\",another_tag_name=\"another_tag-value\""; auto actual = PrometheusStatsFormatter::formattedTags(tags); EXPECT_EQ(expected, actual); } TEST_F(PrometheusStatsFormatterTest, MetricNameCollison) { // Create two counters and two gauges with each pair having the same name, // but having different tag names and values. //`statsAsPrometheus()` should return two implying it found two unique stat names addCounter("cluster.test_cluster_1.upstream_cx_total", {{"a.tag-name", "a.tag-value"}}); addCounter("cluster.test_cluster_1.upstream_cx_total", {{"another_tag_name", "another_tag-value"}}); addGauge("cluster.test_cluster_2.upstream_cx_total", {{"another_tag_name_3", "another_tag_3-value"}}); addGauge("cluster.test_cluster_2.upstream_cx_total", {{"another_tag_name_4", "another_tag_4-value"}}); Buffer::OwnedImpl response; EXPECT_EQ(2UL, PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, response)); } TEST_F(PrometheusStatsFormatterTest, UniqueMetricName) { // Create two counters and two gauges, all with unique names. // statsAsPrometheus() should return four implying it found // four unique stat names. addCounter("cluster.test_cluster_1.upstream_cx_total", {{"a.tag-name", "a.tag-value"}}); addCounter("cluster.test_cluster_2.upstream_cx_total", {{"another_tag_name", "another_tag-value"}}); addGauge("cluster.test_cluster_3.upstream_cx_total", {{"another_tag_name_3", "another_tag_3-value"}}); addGauge("cluster.test_cluster_4.upstream_cx_total", {{"another_tag_name_4", "another_tag_4-value"}}); Buffer::OwnedImpl response; EXPECT_EQ(4UL, PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, response)); } } // namespace Server } // namespace Envoy
#include "json.h" #include "standard-release/semver/semver.h" #include <filesystem> #include <fstream> #include <iostream> #include <regex> #include <sstream> #include <system_error> using namespace StandardRelease; static const std::string JSON_FIELD = "\"version\": \"([^\"]+)\""; struct StandardRelease::JsonFilePrivate { std::string contents; size_t len; size_t pos; }; JsonFile::JsonFile() : ISource() , d(new JsonFilePrivate) {}; bool JsonFile::readFile(const std::string &fileName) { std::ifstream in(fileName, std::ios::in | std::ios::binary); std::ostringstream contents; std::smatch match; SemVer version; if (!in) { setError(Error(Error::PathNotFound, fileName)); return false; } contents << in.rdbuf(); in.close(); const std::string &content = contents.str(); bool ret = std::regex_search(content, match, std::regex(JSON_FIELD)); if (match.empty() || !ret) { setError(Error::VersionInvalid); return false; } const std::string &vstr = match[1]; ret = version.parse(vstr); if (!ret) { setError(Error::VersionInvalid); return false; } d->contents = content; setFilename(fileName); setVersion(version); return true; } bool JsonFile::save() { std::string contents = d->contents; std::ofstream outfile(filename(), std::ofstream::out); if (!outfile) { setError(Error(Error::PathNotFound, filename())); return false; } const std::string vstr = "\"version\": \"" + version().str() + "\""; contents = std::regex_replace(contents, std::regex(JSON_FIELD), vstr, std::regex_constants::format_first_only); outfile << contents; outfile.close(); return true; } std::vector<std::string> JsonFile::filenames() const { return { "package.json" }; } #if 1 bool JsonFile::detect(const std::string &dirname) { std::error_code err; const bool ret = std::filesystem::exists(dirname, err); if (!ret) { setError(Error(Error::PathNotFound, dirname)); return false; } for (auto filename : filenames()) { std::filesystem::path path(dirname); path /= filename; const bool ret = std::filesystem::exists(path, err); if (ret) { return readFile(path.string()); } } return false; } #endif
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // #ifndef TIME_ATTRIBUTE_KIND_HXX #define TIME_ATTRIBUTE_KIND_HXX #ifndef XSD_CXX11 #define XSD_CXX11 #endif #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif // Begin prologue. // // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 4000000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> #include <xsd/cxx/xml/dom/serialization-header.hxx> #include <xsd/cxx/tree/serialization.hxx> #include <xsd/cxx/tree/serialization/byte.hxx> #include <xsd/cxx/tree/serialization/unsigned-byte.hxx> #include <xsd/cxx/tree/serialization/short.hxx> #include <xsd/cxx/tree/serialization/unsigned-short.hxx> #include <xsd/cxx/tree/serialization/int.hxx> #include <xsd/cxx/tree/serialization/unsigned-int.hxx> #include <xsd/cxx/tree/serialization/long.hxx> #include <xsd/cxx/tree/serialization/unsigned-long.hxx> #include <xsd/cxx/tree/serialization/boolean.hxx> #include <xsd/cxx/tree/serialization/float.hxx> #include <xsd/cxx/tree/serialization/double.hxx> #include <xsd/cxx/tree/serialization/decimal.hxx> #include <xsd/cxx/tree/std-ostream-operators.hxx> namespace xml_schema { // anyType and anySimpleType. // typedef ::xsd::cxx::tree::type type; typedef ::xsd::cxx::tree::simple_type< char, type > simple_type; typedef ::xsd::cxx::tree::type container; // 8-bit // typedef signed char byte; typedef unsigned char unsigned_byte; // 16-bit // typedef short short_; typedef unsigned short unsigned_short; // 32-bit // typedef int int_; typedef unsigned int unsigned_int; // 64-bit // typedef long long long_; typedef unsigned long long unsigned_long; // Supposed to be arbitrary-length integral types. // typedef long long integer; typedef long long non_positive_integer; typedef unsigned long long non_negative_integer; typedef unsigned long long positive_integer; typedef long long negative_integer; // Boolean. // typedef bool boolean; // Floating-point types. // typedef float float_; typedef double double_; typedef double decimal; // String types. // typedef ::xsd::cxx::tree::string< char, simple_type > string; typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string; typedef ::xsd::cxx::tree::token< char, normalized_string > token; typedef ::xsd::cxx::tree::name< char, token > name; typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken; typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens; typedef ::xsd::cxx::tree::ncname< char, name > ncname; typedef ::xsd::cxx::tree::language< char, token > language; // ID/IDREF. // typedef ::xsd::cxx::tree::id< char, ncname > id; typedef ::xsd::cxx::tree::idref< char, ncname, type > idref; typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs; // URI. // typedef ::xsd::cxx::tree::uri< char, simple_type > uri; // Qualified name. // typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname; // Binary. // typedef ::xsd::cxx::tree::buffer< char > buffer; typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary; typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary; // Date/time. // typedef ::xsd::cxx::tree::time_zone time_zone; typedef ::xsd::cxx::tree::date< char, simple_type > date; typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time; typedef ::xsd::cxx::tree::duration< char, simple_type > duration; typedef ::xsd::cxx::tree::gday< char, simple_type > gday; typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth; typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day; typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear; typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month; typedef ::xsd::cxx::tree::time< char, simple_type > time; // Entity. // typedef ::xsd::cxx::tree::entity< char, ncname > entity; typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities; typedef ::xsd::cxx::tree::content_order content_order; // Namespace information and list stream. Used in // serialization functions. // typedef ::xsd::cxx::xml::dom::namespace_info< char > namespace_info; typedef ::xsd::cxx::xml::dom::namespace_infomap< char > namespace_infomap; typedef ::xsd::cxx::tree::list_stream< char > list_stream; typedef ::xsd::cxx::tree::as_double< double_ > as_double; typedef ::xsd::cxx::tree::as_decimal< decimal > as_decimal; typedef ::xsd::cxx::tree::facet facet; // Flags and properties. // typedef ::xsd::cxx::tree::flags flags; typedef ::xsd::cxx::tree::properties< char > properties; // Parsing/serialization diagnostics. // typedef ::xsd::cxx::tree::severity severity; typedef ::xsd::cxx::tree::error< char > error; typedef ::xsd::cxx::tree::diagnostics< char > diagnostics; // Exceptions. // typedef ::xsd::cxx::tree::exception< char > exception; typedef ::xsd::cxx::tree::bounds< char > bounds; typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id; typedef ::xsd::cxx::tree::parsing< char > parsing; typedef ::xsd::cxx::tree::expected_element< char > expected_element; typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element; typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute; typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator; typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content; typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping; typedef ::xsd::cxx::tree::no_type_info< char > no_type_info; typedef ::xsd::cxx::tree::not_derived< char > not_derived; typedef ::xsd::cxx::tree::serialization< char > serialization; // Error handler callback interface. // typedef ::xsd::cxx::xml::error_handler< char > error_handler; // DOM interaction. // namespace dom { // Automatic pointer for DOMDocument. // using ::xsd::cxx::xml::dom::unique_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA // DOM user data key for back pointers to tree nodes. // const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace espi { class TimeAttributeKind; } #include <memory> // ::std::unique_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <utility> // std::move #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> namespace espi { class TimeAttributeKind: public ::xml_schema::string { public: TimeAttributeKind (const char* v); TimeAttributeKind (const ::std::string& v); TimeAttributeKind (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); TimeAttributeKind (const ::xercesc::DOMAttr& a, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); TimeAttributeKind (const ::std::string& s, const ::xercesc::DOMElement* e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); TimeAttributeKind (const TimeAttributeKind& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); virtual TimeAttributeKind* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; }; } #include <iosfwd> namespace espi { ::std::ostream& operator<< (::std::ostream&, const TimeAttributeKind&); } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace espi { } #include <iosfwd> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/framework/XMLFormatter.hpp> #include <xsd/cxx/xml/dom/auto-ptr.hxx> namespace espi { void operator<< (::xercesc::DOMElement&, const TimeAttributeKind&); void operator<< (::xercesc::DOMAttr&, const TimeAttributeKind&); void operator<< (::xml_schema::list_stream&, const TimeAttributeKind&); } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // TIME_ATTRIBUTE_KIND_HXX
#include "Ht.h" #include "PersTest00.h" void CPersTest00::PersTest00() { if (PR2_htValid) { switch (PR2_htInst) { case TEST00_ENTRY: { HtContinue(TEST00_WR); break; } case TEST00_WR: { GW2_test00_0_src_v0_data.write_addr(8, 14); GW2_test00_0_src_v0_data = ((uint32_t)0x0005bedda4786260LL); P2_test00_0_src_v0_data_RdAddr1 = (ht_uint4)8; P2_test00_0_src_v0_data_RdAddr2 = (ht_uint4)14; HtContinue(TEST00_ST0); break; } case TEST00_ST0: { if (WriteMemBusy()) { HtRetry(); break; } WriteMem_uint32_t(PR2_memAddr + 0, GR2_test00_0_src_v0_data); WriteMemPause(TEST00_LD0); break; } case TEST00_LD0: { if (ReadMemBusy()) { HtRetry(); break; } ReadMem_test00_0_dst_v7_data(PR2_memAddr + 0, 0, 0, 1); P2_test00_0_dst_s0_data_RdAddr1 = (ht_uint2)0; ReadMemPause(TEST00_CHK); break; } case TEST00_CHK: { if ((uint32_t)PR2_test00_0_dst_s0_data[0].test00_0_dst_s1_data.test00_0_dst_v7_data != ((uint32_t)0x0005bedda4786260LL)) { HtAssert(0, 0); } HtContinue(TEST00_RTN); break; } case TEST00_RTN: { if (SendReturnBusy_test00()) { HtRetry(); break; } SendReturn_test00(); break; } default: assert(0); } } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "agent/cgroups_mgr.h" #include "common/config.h" #include "common/logging.h" #include "gen_cpp/BackendService.h" #include "gen_cpp/HeartbeatService_types.h" #include "gen_cpp/TPaloBrokerService.h" #include "olap/page_cache.h" #include "olap/segment_loader.h" #include "olap/storage_engine.h" #include "runtime/broker_mgr.h" #include "runtime/bufferpool/buffer_pool.h" #include "runtime/bufferpool/reservation_tracker.h" #include "runtime/cache/result_cache.h" #include "runtime/client_cache.h" #include "runtime/data_stream_mgr.h" #include "runtime/disk_io_mgr.h" #include "runtime/etl_job_mgr.h" #include "runtime/exec_env.h" #include "runtime/external_scan_context_mgr.h" #include "runtime/fold_constant_executor.h" #include "runtime/fragment_mgr.h" #include "runtime/heartbeat_flags.h" #include "runtime/load_channel_mgr.h" #include "runtime/load_path_mgr.h" #include "runtime/mem_tracker.h" #include "runtime/mem_tracker_task_pool.h" #include "runtime/result_buffer_mgr.h" #include "runtime/result_queue_mgr.h" #include "runtime/routine_load/routine_load_task_executor.h" #include "runtime/small_file_mgr.h" #include "runtime/stream_load/load_stream_mgr.h" #include "runtime/stream_load/stream_load_executor.h" #include "runtime/thread_resource_mgr.h" #include "runtime/tmp_file_mgr.h" #include "util/bfd_parser.h" #include "util/brpc_client_cache.h" #include "util/doris_metrics.h" #include "util/mem_info.h" #include "util/metrics.h" #include "util/parse_util.h" #include "util/pretty_printer.h" #include "util/priority_thread_pool.hpp" #include "util/priority_work_stealing_thread_pool.hpp" #include "vec/runtime/vdata_stream_mgr.h" namespace doris { DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(scanner_thread_pool_queue_size, MetricUnit::NOUNIT); DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(etl_thread_pool_queue_size, MetricUnit::NOUNIT); DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(send_batch_thread_pool_thread_num, MetricUnit::NOUNIT); DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(send_batch_thread_pool_queue_size, MetricUnit::NOUNIT); DEFINE_GAUGE_METRIC_PROTOTYPE_5ARG(query_mem_consumption, MetricUnit::BYTES, "", mem_consumption, Labels({{"type", "query"}})); DEFINE_GAUGE_METRIC_PROTOTYPE_5ARG(load_mem_consumption, MetricUnit::BYTES, "", mem_consumption, Labels({{"type", "load"}})); Status ExecEnv::init(ExecEnv* env, const std::vector<StorePath>& store_paths) { return env->_init(store_paths); } Status ExecEnv::_init(const std::vector<StorePath>& store_paths) { //Only init once before be destroyed if (_is_init) { return Status::OK(); } _store_paths = store_paths; // path_name => path_index for (int i = 0; i < store_paths.size(); i++) { _store_path_map[store_paths[i].path] = i; } _external_scan_context_mgr = new ExternalScanContextMgr(this); _stream_mgr = new DataStreamMgr(); _vstream_mgr = new doris::vectorized::VDataStreamMgr(); _result_mgr = new ResultBufferMgr(); _result_queue_mgr = new ResultQueueMgr(); _backend_client_cache = new BackendServiceClientCache(config::max_client_cache_size_per_host); _frontend_client_cache = new FrontendServiceClientCache(config::max_client_cache_size_per_host); _broker_client_cache = new BrokerServiceClientCache(config::max_client_cache_size_per_host); _task_pool_mem_tracker_registry.reset(new MemTrackerTaskPool()); _thread_mgr = new ThreadResourceMgr(); if (config::doris_enable_scanner_thread_pool_per_disk && config::doris_scanner_thread_pool_thread_num >= store_paths.size() && store_paths.size() > 0) { _scan_thread_pool = new PriorityWorkStealingThreadPool( config::doris_scanner_thread_pool_thread_num, store_paths.size(), config::doris_scanner_thread_pool_queue_size); LOG(INFO) << "scan thread pool use PriorityWorkStealingThreadPool"; } else { _scan_thread_pool = new PriorityThreadPool(config::doris_scanner_thread_pool_thread_num, config::doris_scanner_thread_pool_queue_size); LOG(INFO) << "scan thread pool use PriorityThreadPool"; } ThreadPoolBuilder("LimitedScanThreadPool") .set_min_threads(1) .set_max_threads(config::doris_scanner_thread_pool_thread_num) .set_max_queue_size(config::doris_scanner_thread_pool_queue_size) .build(&_limited_scan_thread_pool); ThreadPoolBuilder("SendBatchThreadPool") .set_min_threads(1) .set_max_threads(config::send_batch_thread_pool_thread_num) .set_max_queue_size(config::send_batch_thread_pool_queue_size) .build(&_send_batch_thread_pool); _etl_thread_pool = new PriorityThreadPool(config::etl_thread_pool_size, config::etl_thread_pool_queue_size); _cgroups_mgr = new CgroupsMgr(this, config::doris_cgroups); _fragment_mgr = new FragmentMgr(this); _result_cache = new ResultCache(config::query_cache_max_size_mb, config::query_cache_elasticity_size_mb); _master_info = new TMasterInfo(); _etl_job_mgr = new EtlJobMgr(this); _load_path_mgr = new LoadPathMgr(this); _disk_io_mgr = new DiskIoMgr(); _tmp_file_mgr = new TmpFileMgr(this); _bfd_parser = BfdParser::create(); _broker_mgr = new BrokerMgr(this); _load_channel_mgr = new LoadChannelMgr(); _load_stream_mgr = new LoadStreamMgr(); _internal_client_cache = new BrpcClientCache<PBackendService_Stub>(); _function_client_cache = new BrpcClientCache<PFunctionService_Stub>(); _stream_load_executor = new StreamLoadExecutor(this); _routine_load_task_executor = new RoutineLoadTaskExecutor(this); _small_file_mgr = new SmallFileMgr(this, config::small_file_dir); _backend_client_cache->init_metrics("backend"); _frontend_client_cache->init_metrics("frontend"); _broker_client_cache->init_metrics("broker"); _result_mgr->init(); _cgroups_mgr->init_cgroups(); _etl_job_mgr->init(); Status status = _load_path_mgr->init(); if (!status.ok()) { LOG(ERROR) << "load path mgr init failed." << status.get_error_msg(); exit(-1); } _broker_mgr->init(); _small_file_mgr->init(); _init_mem_tracker(); RETURN_IF_ERROR(_load_channel_mgr->init(MemTracker::get_process_tracker()->limit())); _heartbeat_flags = new HeartbeatFlags(); _register_metrics(); _is_init = true; return Status::OK(); } Status ExecEnv::_init_mem_tracker() { // 1. init global memory limit. int64_t global_memory_limit_bytes = 0; bool is_percent = false; std::stringstream ss; global_memory_limit_bytes = ParseUtil::parse_mem_spec(config::mem_limit, -1, MemInfo::physical_mem(), &is_percent); if (global_memory_limit_bytes <= 0) { ss << "Failed to parse mem limit from '" + config::mem_limit + "'."; return Status::InternalError(ss.str()); } if (global_memory_limit_bytes > MemInfo::physical_mem()) { LOG(WARNING) << "Memory limit " << PrettyPrinter::print(global_memory_limit_bytes, TUnit::BYTES) << " exceeds physical memory of " << PrettyPrinter::print(MemInfo::physical_mem(), TUnit::BYTES) << ". Using physical memory instead"; global_memory_limit_bytes = MemInfo::physical_mem(); } MemTracker::get_process_tracker()->set_limit(global_memory_limit_bytes); _query_pool_mem_tracker = MemTracker::create_tracker(global_memory_limit_bytes, "QueryPool", MemTracker::get_process_tracker(), MemTrackerLevel::OVERVIEW); REGISTER_HOOK_METRIC(query_mem_consumption, [this]() { return _query_pool_mem_tracker->consumption(); }); _load_pool_mem_tracker = MemTracker::create_tracker(global_memory_limit_bytes, "LoadPool", MemTracker::get_process_tracker(), MemTrackerLevel::OVERVIEW); REGISTER_HOOK_METRIC(load_mem_consumption, [this]() { return _load_pool_mem_tracker->consumption(); }); LOG(INFO) << "Using global memory limit: " << PrettyPrinter::print(global_memory_limit_bytes, TUnit::BYTES) << ", origin config value: " << config::mem_limit; // 2. init buffer pool if (!BitUtil::IsPowerOf2(config::min_buffer_size)) { ss << "Config min_buffer_size must be a power-of-two: " << config::min_buffer_size; return Status::InternalError(ss.str()); } int64_t buffer_pool_limit = ParseUtil::parse_mem_spec(config::buffer_pool_limit, global_memory_limit_bytes, MemInfo::physical_mem(), &is_percent); if (buffer_pool_limit <= 0) { ss << "Invalid config buffer_pool_limit value, must be a percentage or " "positive bytes value or percentage: " << config::buffer_pool_limit; return Status::InternalError(ss.str()); } buffer_pool_limit = BitUtil::RoundDown(buffer_pool_limit, config::min_buffer_size); while (!is_percent && buffer_pool_limit > global_memory_limit_bytes / 2) { // If buffer_pool_limit is not a percentage, and the value exceeds 50% of the total memory limit, // it is forced to be reduced to less than 50% of the total memory limit. // This is to ensure compatibility. In principle, buffer_pool_limit should be set as a percentage. buffer_pool_limit = buffer_pool_limit / 2; } int64_t clean_pages_limit = ParseUtil::parse_mem_spec(config::buffer_pool_clean_pages_limit, buffer_pool_limit, MemInfo::physical_mem(), &is_percent); if (clean_pages_limit <= 0) { ss << "Invalid buffer_pool_clean_pages_limit value, must be a percentage or " "positive bytes value or percentage: " << config::buffer_pool_clean_pages_limit; return Status::InternalError(ss.str()); } while (!is_percent && clean_pages_limit > buffer_pool_limit / 2) { // Reason same as buffer_pool_limit clean_pages_limit = clean_pages_limit / 2; } _init_buffer_pool(config::min_buffer_size, buffer_pool_limit, clean_pages_limit); LOG(INFO) << "Buffer pool memory limit: " << PrettyPrinter::print(buffer_pool_limit, TUnit::BYTES) << ", origin config value: " << config::buffer_pool_limit << ". clean pages limit: " << PrettyPrinter::print(clean_pages_limit, TUnit::BYTES) << ", origin config value: " << config::buffer_pool_clean_pages_limit; // 3. init storage page cache int64_t storage_cache_limit = ParseUtil::parse_mem_spec(config::storage_page_cache_limit, global_memory_limit_bytes, MemInfo::physical_mem(), &is_percent); while (!is_percent && storage_cache_limit > global_memory_limit_bytes / 2) { // Reason same as buffer_pool_limit storage_cache_limit = storage_cache_limit / 2; } int32_t index_page_cache_percentage = config::index_page_cache_percentage; StoragePageCache::create_global_cache(storage_cache_limit, index_page_cache_percentage); LOG(INFO) << "Storage page cache memory limit: " << PrettyPrinter::print(storage_cache_limit, TUnit::BYTES) << ", origin config value: " << config::storage_page_cache_limit; SegmentLoader::create_global_instance(config::segment_cache_capacity); // 4. init other managers RETURN_IF_ERROR(_disk_io_mgr->init(global_memory_limit_bytes)); RETURN_IF_ERROR(_tmp_file_mgr->init()); // TODO(zc): The current memory usage configuration is a bit confusing, // we need to sort out the use of memory return Status::OK(); } void ExecEnv::_init_buffer_pool(int64_t min_page_size, int64_t capacity, int64_t clean_pages_limit) { DCHECK(_buffer_pool == nullptr); _buffer_pool = new BufferPool(min_page_size, capacity, clean_pages_limit); _buffer_reservation = new ReservationTracker(); _buffer_reservation->InitRootTracker(nullptr, capacity); } void ExecEnv::_register_metrics() { REGISTER_HOOK_METRIC(scanner_thread_pool_queue_size, [this]() { return _scan_thread_pool->get_queue_size(); }); REGISTER_HOOK_METRIC(etl_thread_pool_queue_size, [this]() { return _etl_thread_pool->get_queue_size(); }); REGISTER_HOOK_METRIC(send_batch_thread_pool_thread_num, [this]() { return _send_batch_thread_pool->num_threads(); }); REGISTER_HOOK_METRIC(send_batch_thread_pool_queue_size, [this]() { return _send_batch_thread_pool->get_queue_size(); }); } void ExecEnv::_deregister_metrics() { DEREGISTER_HOOK_METRIC(scanner_thread_pool_queue_size); DEREGISTER_HOOK_METRIC(etl_thread_pool_queue_size); DEREGISTER_HOOK_METRIC(send_batch_thread_pool_thread_num); DEREGISTER_HOOK_METRIC(send_batch_thread_pool_queue_size); } void ExecEnv::_destroy() { //Only destroy once after init if (!_is_init) { return; } _deregister_metrics(); SAFE_DELETE(_internal_client_cache); SAFE_DELETE(_function_client_cache); SAFE_DELETE(_load_stream_mgr); SAFE_DELETE(_load_channel_mgr); SAFE_DELETE(_broker_mgr); SAFE_DELETE(_bfd_parser); SAFE_DELETE(_tmp_file_mgr); SAFE_DELETE(_disk_io_mgr); SAFE_DELETE(_load_path_mgr); SAFE_DELETE(_etl_job_mgr); SAFE_DELETE(_master_info); SAFE_DELETE(_fragment_mgr); SAFE_DELETE(_cgroups_mgr); SAFE_DELETE(_etl_thread_pool); SAFE_DELETE(_scan_thread_pool); SAFE_DELETE(_thread_mgr); SAFE_DELETE(_broker_client_cache); SAFE_DELETE(_frontend_client_cache); SAFE_DELETE(_backend_client_cache); SAFE_DELETE(_result_mgr); SAFE_DELETE(_result_queue_mgr); SAFE_DELETE(_stream_mgr); SAFE_DELETE(_stream_load_executor); SAFE_DELETE(_routine_load_task_executor); SAFE_DELETE(_external_scan_context_mgr); SAFE_DELETE(_heartbeat_flags); DEREGISTER_HOOK_METRIC(query_mem_consumption); DEREGISTER_HOOK_METRIC(load_mem_consumption); _is_init = false; } void ExecEnv::destroy(ExecEnv* env) { env->_destroy(); } } // namespace doris
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * 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. */ /* * $Id: PTXPlatformUtils.cpp 191054 2005-06-17 02:56:35Z jberry $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- // Change by Sumit (sumitc): No difference (presently) between this // and the Solaris implementation, so we will use that instead. #include "../Solaris/SolarisPlatformUtils.cpp" XERCES_CPP_NAMESPACE_BEGIN XERCES_CPP_NAMESPACE_END
#ifdef USE_OPENCV #include <opencv2/core/core.hpp> #endif // USE_OPENCV #include "caffe/common.hpp" #include "caffe/layer.hpp" #include "caffe/util/benchmark.hpp" #include "caffe/util/io.hpp" #include "caffe/layers/cpm_data_layer.hpp" namespace caffe { template <typename Dtype> CPMDataLayer<Dtype>::CPMDataLayer(const LayerParameter& param) : BasePrefetchingDataLayer<Dtype>(param), reader_(param) { } template <typename Dtype> CPMDataLayer<Dtype>::~CPMDataLayer() { this->StopInternalThread(); } template <typename Dtype> void CPMDataLayer<Dtype>::DataLayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { this->data_transformer_.reset( new DataTransformerCPM<Dtype>(this->transform_param_, this->phase_)); this->data_transformer_->InitRand(); // Read a data point, and use it to initialize the top blob. Datum& datum = *(reader_.full().peek()); LOG(INFO) << datum.height() << " " << datum.width() << " " << datum.channels(); bool force_color = this->layer_param_.data_param().force_encoded_color(); if ((force_color && DecodeDatum(&datum, true)) || DecodeDatumNative(&datum)) { LOG(INFO) << "Decoding Datum"; } // image const int crop_size = this->layer_param_.transform_param().crop_size(); const int batch_size = this->layer_param_.data_param().batch_size(); if (crop_size > 0) { top[0]->Reshape(batch_size, datum.channels(), crop_size, crop_size); for (int i = 0; i < this->PREFETCH_COUNT; ++i) { this->prefetch_[i].data_.Reshape(batch_size, datum.channels(), crop_size, crop_size); } this->transformed_data_.Reshape(1, datum.channels(), crop_size, crop_size); } else { const int height = this->phase_ != TRAIN ? datum.height() : this->layer_param_.transform_param().crop_size_y(); const int width = this->phase_ != TRAIN ? datum.width() : this->layer_param_.transform_param().crop_size_x(); LOG(INFO) << "PREFETCH_COUNT is " << this->PREFETCH_COUNT; LOG(INFO) << "height, width" << height<< width; top[0]->Reshape(batch_size, datum.channels(), height, width); for (int i = 0; i < this->PREFETCH_COUNT; ++i) { this->prefetch_[i].data_.Reshape(batch_size, datum.channels(), height, width); } this->transformed_data_.Reshape(1, 4, height, width); } LOG(INFO) << "output data size: " << top[0]->num() << "," << top[0]->channels() << "," << top[0]->height() << "," << top[0]->width(); LOG(INFO) << "output data size: " << this->prefetch_[1].data_.num() << "," << this->prefetch_[1].data_.channels() << "," << this->prefetch_[1].data_.height() << "," << this->prefetch_[1].data_.width(); // label if (this->output_labels_) { const int stride = this->layer_param_.transform_param().stride(); const int height = this->phase_ != TRAIN ? datum.height() : this->layer_param_.transform_param().crop_size_y(); const int width = this->phase_ != TRAIN ? datum.width() : this->layer_param_.transform_param().crop_size_x(); int num_parts = this->layer_param_.transform_param().num_parts(); top[1]->Reshape(batch_size, 2*(num_parts+1), height/stride, width/stride); for (int i = 0; i < this->PREFETCH_COUNT; ++i) { this->prefetch_[i].label_.Reshape(batch_size, 2*(num_parts+1), height/stride, width/stride); } this->transformed_label_.Reshape(1, 2*(num_parts+1), height/stride, width/stride); } } // This function is called on prefetch thread template<typename Dtype> void CPMDataLayer<Dtype>::load_batch(Batch<Dtype>* batch) { CPUTimer batch_timer; batch_timer.Start(); double deque_time = 0; double decod_time = 0; double trans_time = 0; static int cnt = 0; CPUTimer timer; CHECK(batch->data_.count()); CHECK(this->transformed_data_.count()); // Reshape on single input batches for inputs of varying dimension. const int batch_size = this->layer_param_.data_param().batch_size(); const int crop_size = this->layer_param_.transform_param().crop_size(); bool force_color = this->layer_param_.data_param().force_encoded_color(); if (batch_size == 1 && crop_size == 0) { Datum& datum = *(reader_.full().peek()); if (datum.encoded()) { if (force_color) { DecodeDatum(&datum, true); } else { DecodeDatumNative(&datum); } } batch->data_.Reshape(1, datum.channels(), datum.height(), datum.width()); this->transformed_data_.Reshape(1, datum.channels(), datum.height(), datum.width()); } Dtype* top_data = batch->data_.mutable_cpu_data(); Dtype* top_label = NULL; // suppress warnings about uninitialized variables if (this->output_labels_) { top_label = batch->label_.mutable_cpu_data(); } for (int item_id = 0; item_id < batch_size; ++item_id) { // get a blob timer.Start(); Datum& datum = *(reader_.full().pop("Waiting for data")); deque_time += timer.MicroSeconds(); timer.Start(); cv::Mat cv_img; if (datum.encoded()) { if (force_color) { cv_img = DecodeDatumToCVMat(datum, true); } else { cv_img = DecodeDatumToCVMatNative(datum); } if (cv_img.channels() != this->transformed_data_.channels()) { LOG(WARNING) << "Your dataset contains encoded images with mixed " << "channel sizes. Consider adding a 'force_color' flag to the " << "model definition, or rebuild your dataset using " << "convert_imageset."; } } decod_time += timer.MicroSeconds(); // Apply data transformations (mirror, scale, crop...) timer.Start(); const int offset_data = batch->data_.offset(item_id); const int offset_label = batch->label_.offset(item_id); this->transformed_data_.set_cpu_data(top_data + offset_data); this->transformed_label_.set_cpu_data(top_label + offset_label); DataTransformerCPM<Dtype>* data_transformer = (DataTransformerCPM<Dtype> *) this->data_transformer_.operator->(); if (datum.encoded()) { //LOG(INFO) << "datum.encoded true"; data_transformer->Transform(cv_img, &(this->transformed_data_)); } else { //LOG(INFO) << "datum.encoded false: " << cnt; data_transformer->Transform_nv(datum, &(this->transformed_data_), &(this->transformed_label_), cnt); ++cnt; } trans_time += timer.MicroSeconds(); reader_.free().push(&datum); } batch_timer.Stop(); #ifdef BENCHMARK_DATA LOG(INFO) << "Prefetch batch: " << batch_timer.MilliSeconds() << " ms."; LOG(INFO) << " Dequeue time: " << deque_time / 1000 << " ms."; LOG(INFO) << " Decode time: " << decod_time / 1000 << " ms."; LOG(INFO) << "Transform time: " << trans_time / 1000 << " ms."; #endif } INSTANTIATE_CLASS(CPMDataLayer); REGISTER_LAYER_CLASS(CPMData); } // namespace caffe
#include "stdafx.h" #include "actor.h" #include "Actor_Flags.h" #include "inventory.h" #include "xrserver_objects_alife_monsters.h" #include "xrServer.h" #include "CameraLook.h" #include "CameraFirstEye.h" #include "ActorEffector.h" #include "PHWorld.h" #include "level.h" #include "xr_level_controller.h" #include "game_cl_base.h" #include "infoportion.h" #include "alife_registry_wrappers.h" #include "..\Include/xrRender/Kinematics.h" #include "..\Include/xrRender/KinematicsAnimated.h" #include "client_spawn_manager.h" #include "hit.h" #include "PHDestroyable.h" #include "CharacterPhysicsSupport.h" #include "Grenade.h" #include "WeaponMagazined.h" #include "CustomOutfit.h" #include "actor_anim_defs.h" #include "map_manager.h" #include "HUDManager.h" #include "ui/UIArtefactPanel.h" #include "ui/UIMainIngameWnd.h" #include "gamepersistent.h" #include "game_object_space.h" #include "GameTaskManager.h" #include "game_base_kill_type.h" #include "holder_custom.h" #include "actor_memory.h" #include "actor_statistic_mgr.h" #include "characterphysicssupport.h" #include "game_cl_base_weapon_usage_statistic.h" #include "clsid_game.h" #include "alife_simulator_header.h" #include "actorcondition.h" #include "UIGameSP.h" #include "ui/UIPDAWnd.h" #include "ui/UIEncyclopediaWnd.h" #include "ui/UIDiaryWnd.h" #ifdef DEBUG # include "debug_renderer.h" #endif CActor* g_actor = NULL; CActor* Actor() { // KRodin: Эта функция теперь вызывается из многих новых каллбеков, // и вполне может быть вызвана, когда актора ещё нет. // Т.ч. вылетать не будем в этом случае. //VERIFY (g_actor); return g_actor; }; BOOL CActor::net_Spawn (CSE_Abstract* DC) { m_holder_id = ALife::_OBJECT_ID(-1); m_feel_touch_characters = 0; m_snd_noise = 0.0f; m_sndShockEffector = NULL; /* m_followers = NULL;*/ if (m_pPhysicsShell) { m_pPhysicsShell->Deactivate(); xr_delete(m_pPhysicsShell); }; //force actor to be local on server client CSE_Abstract *e = (CSE_Abstract*)(DC); CSE_ALifeCreatureActor *E = smart_cast<CSE_ALifeCreatureActor*>(e); if (OnServer()) { E->s_flags.set(M_SPAWN_OBJECT_LOCAL, TRUE); } if( TRUE == E->s_flags.test(M_SPAWN_OBJECT_LOCAL) && TRUE == E->s_flags.is(M_SPAWN_OBJECT_ASPLAYER)) g_actor = this; VERIFY(m_pActorEffector == NULL); m_pActorEffector = xr_new<CActorCameraManager>(); // motions m_bAnimTorsoPlayed = false; m_current_legs_blend = 0; m_current_jump_blend = 0; m_current_legs.invalidate (); m_current_torso.invalidate (); m_current_head.invalidate (); //------------------------------------- // инициализация реестров, используемых актером encyclopedia_registry->registry().init(ID()); game_news_registry->registry().init(ID()); { auto& news = game_news_registry->registry().objects(); if ( news.size() > NewsToShow() ) { u32 s = news.size(); news.erase( news.begin(), news.begin() + ( news.size() - NewsToShow() ) ); Msg( "[%s]: purge %u news items, %u left", __FUNCTION__, s - news.size(), news.size() ); } } if ( HUD().GetUI() ) { CUIGameSP* pGameSP = smart_cast<CUIGameSP*>( HUD().GetUI()->UIGame() ); if ( pGameSP ) pGameSP->PdaMenu->UIEncyclopediaWnd->FillEncyclopedia(); pGameSP->PdaMenu->UIDiaryWnd->FillNews(); } if (!CInventoryOwner::net_Spawn(DC)) return FALSE; if (!inherited::net_Spawn(DC)) return FALSE; CSE_ALifeTraderAbstract *pTA = smart_cast<CSE_ALifeTraderAbstract*>(e); set_money (pTA->m_dwMoney, false); ROS()->force_mode (IRender_ObjectSpecific::TRACE_ALL); m_pPhysics_support->in_NetSpawn (e); character_physics_support()->movement()->ActivateBox( m_loaded_ph_box_id ); if(E->m_holderID!=u16(-1)) { character_physics_support()->movement()->DestroyCharacter(); } if(m_bOutBorder)character_physics_support()->movement()->setOutBorder(); r_torso_tgt_roll = 0; r_model_yaw = E->o_torso.yaw; r_torso.yaw = E->o_torso.yaw; r_torso.pitch = E->o_torso.pitch; r_torso.roll = 0.0f;//E->o_Angle.z; unaffected_r_torso.yaw = r_torso.yaw; unaffected_r_torso.pitch= r_torso.pitch; unaffected_r_torso.roll = r_torso.roll; // KRodin: это, мне кажется, лишнее. //if( psActorFlags.test(AF_PSP) ) // cam_Set(eacLookAt); //else cam_Set(eacFirstEye); cam_Active()->Set (-E->o_torso.yaw,E->o_torso.pitch,0);//E->o_Angle.z); // *** movement state - respawn mstate_wishful = 0; if ( m_loaded_ph_box_id == 1 || m_loaded_ph_box_id == 3 ) mstate_real = mcCrouch; else if ( m_loaded_ph_box_id == 2 || m_loaded_ph_box_id == 4 ) mstate_real = mcCrouch|mcAccel; else mstate_real = 0; mstate_old = mstate_real; m_bJumpKeyPressed = FALSE; NET_SavedAccel.set (0,0,0); setEnabled (E->s_flags.is(M_SPAWN_OBJECT_LOCAL)); Engine.Sheduler.Register (this,TRUE); hit_slowmo = 0.f; OnChangeVisual(); processing_activate(); #ifdef DEBUG LastPosS.clear(); LastPosH.clear(); LastPosL.clear(); #endif //* // if (OnServer())// && E->s_flags.is(M_SPAWN_OBJECT_LOCAL)) /* if (OnClient()) { if (!pStatGraph) { static g_Y = 0; pStatGraph = xr_new<CStatGraph>(); pStatGraph->SetRect(0, g_Y, Device.dwWidth, 100, 0xff000000, 0xff000000); g_Y += 110; if (g_Y > 700) g_Y = 100; pStatGraph->SetGrid(0, 0.0f, 10, 1.0f, 0xff808080, 0xffffffff); pStatGraph->SetMinMax(0, 10, 300); pStatGraph->SetStyle(CStatGraph::stBar); pStatGraph->AppendSubGraph(CStatGraph::stCurve); pStatGraph->AppendSubGraph(CStatGraph::stCurve); } } */ SetDefaultVisualOutfit(cNameVisual()); smart_cast<IKinematics*>(Visual())->CalculateBones(); //-------------------------------------------------------------- inventory().SetPrevActiveSlot(NO_ACTIVE_SLOT); //------------------------------------- if (!g_Alive()) { mstate_wishful &= ~mcAnyMove; mstate_real &= ~mcAnyMove; IKinematicsAnimated* K= smart_cast<IKinematicsAnimated*>(Visual()); K->PlayCycle("death_init"); //остановить звук тяжелого дыхания m_HeavyBreathSnd.stop(); } auto callback = fastdelegate::MakeDelegate(this, &CActor::on_requested_spawn); m_holder_id = E->m_holderID; if (E->m_holderID != ALife::_OBJECT_ID(-1)) Level().client_spawn_manager().add(E->m_holderID,ID(),callback); //F //------------------------------------------------------------- m_iLastHitterID = u16(-1); m_iLastHittingWeaponID = u16(-1); m_s16LastHittedElement = -1; m_bWasHitted = false; Level().MapManager().AddMapLocation("actor_location",ID()); Level().MapManager().AddMapLocation("actor_location_p",ID()); m_game_task_manager = xr_new<CGameTaskManager>(); GameTaskManager().initialize(ID()); m_statistic_manager = xr_new<CActorStatisticMgr>(); spatial.type |=STYPE_REACTTOSOUND; psHUD_Flags.set(HUD_WEAPON_RT,TRUE); if (Level().IsDemoPlay() && OnClient()) { setLocal(FALSE); }; return TRUE; } void CActor::net_Destroy () { inherited::net_Destroy (); if (m_holder_id != ALife::_OBJECT_ID(-1)) Level().client_spawn_manager().remove (m_holder_id,ID()); delete_data (m_game_task_manager); delete_data (m_statistic_manager); Level().MapManager ().RemoveMapLocationByObjectID(ID()); #pragma todo("Dima to MadMax : do not comment inventory owner net_Destroy!!!") CInventoryOwner::net_Destroy(); cam_UnsetLadder(); character_physics_support()->movement()->DestroyCharacter(); if(m_pPhysicsShell) { m_pPhysicsShell->Deactivate(); xr_delete<CPhysicsShell>(m_pPhysicsShell); }; m_pPhysics_support->in_NetDestroy (); xr_delete (m_sndShockEffector); xr_delete (pStatGraph); xr_delete (m_pActorEffector); pCamBobbing = NULL; #ifdef DEBUG LastPosS.clear(); LastPosH.clear(); LastPosL.clear(); #endif processing_deactivate(); m_holder=NULL; m_holderID=u16(-1); SetDefaultVisualOutfit(NULL); if(g_actor == this) g_actor= NULL; Engine.Sheduler.Unregister (this); } void CActor::net_Relcase (CObject* O) { VERIFY(O); CGameObject* GO = smart_cast<CGameObject*>(O); if(GO&&m_pObjectWeLookingAt==GO){ m_pObjectWeLookingAt=NULL; } CHolderCustom* HC=smart_cast<CHolderCustom*>(GO); if(HC&&HC==m_pVehicleWeLookingAt){ m_pVehicleWeLookingAt=NULL; } if(HC&&HC==m_holder) { m_holder->detach_Actor(); m_holder=NULL; } inherited::net_Relcase (O); memory().remove_links(O); m_pPhysics_support->in_NetRelcase(O); conditions().net_Relcase( O ); } BOOL CActor::net_Relevant () // relevant for export to server { if (OnServer()) { return getSVU() | getLocal(); } else { return Local() & g_Alive(); }; }; void CActor::SetCallbacks() { IKinematics* V = smart_cast<IKinematics*>(Visual()); VERIFY (V); u16 spine0_bone = V->LL_BoneID("bip01_spine"); u16 spine1_bone = V->LL_BoneID("bip01_spine1"); u16 shoulder_bone = V->LL_BoneID("bip01_spine2"); u16 head_bone = V->LL_BoneID("bip01_head"); V->LL_GetBoneInstance(u16(spine0_bone)).set_callback (bctCustom,Spin0Callback,this); V->LL_GetBoneInstance(u16(spine1_bone)).set_callback (bctCustom,Spin1Callback,this); V->LL_GetBoneInstance(u16(shoulder_bone)).set_callback (bctCustom,ShoulderCallback,this); V->LL_GetBoneInstance(u16(head_bone)).set_callback (bctCustom,HeadCallback,this); } void CActor::ResetCallbacks() { IKinematics* V = smart_cast<IKinematics*>(Visual()); VERIFY (V); u16 spine0_bone = V->LL_BoneID("bip01_spine"); u16 spine1_bone = V->LL_BoneID("bip01_spine1"); u16 shoulder_bone = V->LL_BoneID("bip01_spine2"); u16 head_bone = V->LL_BoneID("bip01_head"); V->LL_GetBoneInstance(u16(spine0_bone)).reset_callback (); V->LL_GetBoneInstance(u16(spine1_bone)).reset_callback (); V->LL_GetBoneInstance(u16(shoulder_bone)).reset_callback(); V->LL_GetBoneInstance(u16(head_bone)).reset_callback (); } void CActor::OnChangeVisual() { /// inherited::OnChangeVisual(); { CPhysicsShell* tmp_shell=PPhysicsShell(); PPhysicsShell()=NULL; inherited::OnChangeVisual(); PPhysicsShell()=tmp_shell; tmp_shell=NULL; } IKinematicsAnimated* V = smart_cast<IKinematicsAnimated*>(Visual()); if (V){ SetCallbacks (); m_anims->Create (V); m_vehicle_anims->Create (V); CDamageManager::reload(*cNameSect(),"damage",pSettings); //------------------------------------------------------------------------------- m_head = smart_cast<IKinematics*>(Visual())->LL_BoneID("bip01_head"); m_r_hand = smart_cast<IKinematics*>(Visual())->LL_BoneID(pSettings->r_string(*cNameSect(),"weapon_bone0")); m_l_finger1 = smart_cast<IKinematics*>(Visual())->LL_BoneID(pSettings->r_string(*cNameSect(),"weapon_bone1")); m_r_finger2 = smart_cast<IKinematics*>(Visual())->LL_BoneID(pSettings->r_string(*cNameSect(),"weapon_bone2")); //------------------------------------------------------------------------------- m_neck = smart_cast<IKinematics*>(Visual())->LL_BoneID("bip01_neck"); m_l_clavicle = smart_cast<IKinematics*>(Visual())->LL_BoneID("bip01_l_clavicle"); m_r_clavicle = smart_cast<IKinematics*>(Visual())->LL_BoneID("bip01_r_clavicle"); m_spine2 = smart_cast<IKinematics*>(Visual())->LL_BoneID("bip01_spine2"); m_spine1 = smart_cast<IKinematics*>(Visual())->LL_BoneID("bip01_spine1"); m_spine = smart_cast<IKinematics*>(Visual())->LL_BoneID("bip01_spine"); //------------------------------------------------------------------------------- reattach_items(); //------------------------------------------------------------------------------- m_pPhysics_support->in_ChangeVisual(); //------------------------------------------------------------------------------- SetCallbacks (); //------------------------------------------------------------------------------- m_current_head.invalidate (); m_current_legs.invalidate (); m_current_torso.invalidate (); m_current_legs_blend = NULL; m_current_torso_blend = NULL; m_current_jump_blend = NULL; CStepManager::reload(*cNameSect()); } }; void CActor::ChangeVisual ( shared_str NewVisual ) { if (!NewVisual.size()) return; if (cNameVisual().size() ) { if (cNameVisual() == NewVisual) return; } cNameVisual_set(NewVisual); g_SetAnimation (mstate_real); Visual()->dcast_PKinematics()->CalculateBones_Invalidate(); Visual()->dcast_PKinematics()->CalculateBones(); }; void CActor::save(NET_Packet &output_packet) { inherited::save(output_packet); CInventoryOwner::save(output_packet); output_packet.w_u8(u8(m_bOutBorder)); output_packet.w_u8( u8( character_physics_support()->movement()->BoxID() ) ); } void CActor::load(IReader &input_packet) { inherited::load(input_packet); CInventoryOwner::load(input_packet); m_bOutBorder=!!(input_packet.r_u8()); if ( ai().get_alife()->header().version() > 5 ) m_loaded_ph_box_id = input_packet.r_u8(); } #ifdef DEBUG extern Flags32 dbg_net_Draw_Flags; void dbg_draw_piramid (Fvector pos, Fvector dir, float size, float xdir, u32 color) { Fvector p0, p1, p2, p3, p4; p0.set(size, size, 0.0f); p1.set(-size, size, 0.0f); p2.set(-size, -size, 0.0f); p3.set(size, -size, 0.0f); p4.set(0, 0, size*4); bool Double = false; Fmatrix t; t.identity(); if (_valid(dir) && dir.square_magnitude()>0.01f) { t.k.normalize (dir); Fvector::generate_orthonormal_basis(t.k, t.j, t.i); } else { t.rotateY(xdir); Double = true; } t.c.set(pos); // Level().debug_renderer().draw_line(t, p0, p1, color); // Level().debug_renderer().draw_line(t, p1, p2, color); // Level().debug_renderer().draw_line(t, p2, p3, color); // Level().debug_renderer().draw_line(t, p3, p0, color); // Level().debug_renderer().draw_line(t, p0, p4, color); // Level().debug_renderer().draw_line(t, p1, p4, color); // Level().debug_renderer().draw_line(t, p2, p4, color); // Level().debug_renderer().draw_line(t, p3, p4, color); if (!Double) { RCache.dbg_DrawTRI(t, p0, p1, p4, color); RCache.dbg_DrawTRI(t, p1, p2, p4, color); RCache.dbg_DrawTRI(t, p2, p3, p4, color); RCache.dbg_DrawTRI(t, p3, p0, p4, color); } else { // Fmatrix scale; // scale.scale(0.8f, 0.8f, 0.8f); // t.mulA_44(scale); // t.c.set(pos); Level().debug_renderer().draw_line(t, p0, p1, color); Level().debug_renderer().draw_line(t, p1, p2, color); Level().debug_renderer().draw_line(t, p2, p3, color); Level().debug_renderer().draw_line(t, p3, p0, color); Level().debug_renderer().draw_line(t, p0, p4, color); Level().debug_renderer().draw_line(t, p1, p4, color); Level().debug_renderer().draw_line(t, p2, p4, color); Level().debug_renderer().draw_line(t, p3, p4, color); }; }; #endif void CActor::net_Save(NET_Packet& P) { #ifdef DEBUG u32 pos; Msg ("Actor net_Save"); pos = P.w_tell(); inherited::net_Save (P); Msg ("inherited::net_Save() : %d",P.w_tell() - pos); pos = P.w_tell(); m_pPhysics_support->in_NetSave(P); P.w_u16(m_holderID); Msg ("m_pPhysics_support->in_NetSave() : %d",P.w_tell() - pos); #else inherited::net_Save (P); m_pPhysics_support->in_NetSave(P); P.w_u16(m_holderID); #endif } BOOL CActor::net_SaveRelevant() { return TRUE; } void CActor::SetHitInfo (CObject* who, CObject* weapon, s16 element, Fvector Pos, Fvector Dir) { m_iLastHitterID = (who!= NULL) ? who->ID() : u16(-1); m_iLastHittingWeaponID = (weapon != NULL) ? weapon->ID() : u16(-1); m_s16LastHittedElement = element; m_fLastHealth = GetfHealth(); m_bWasHitted = true; m_vLastHitDir = Dir; m_vLastHitPos = Pos; }; bool CActor::InventoryAllowSprint () { PIItem pActiveItem = inventory().ActiveItem(); if (pActiveItem && !pActiveItem->IsSprintAllowed()) { return false; }; PIItem pOutfitItem = inventory().ItemFromSlot(OUTFIT_SLOT); if (pOutfitItem && !pOutfitItem->IsSprintAllowed()) { return false; } return true; }; BOOL CActor::BonePassBullet (int boneID) { return inherited::BonePassBullet(boneID); } void CActor::On_B_NotCurrentEntity () { inventory().Items_SetCurrentEntityHud(false); } void CActor::net_Export (CSE_Abstract* E ) { CSE_ALifeCreatureAbstract* creature = smart_cast<CSE_ALifeCreatureAbstract*>( E ); creature->fHealth = GetfHealth(); creature->timestamp = Level().timeServer(); creature->flags = 0; creature->o_Position = Position(); creature->o_model = angle_normalize( r_model_yaw ); creature->o_torso.yaw = angle_normalize( unaffected_r_torso.yaw ); creature->o_torso.pitch = angle_normalize( unaffected_r_torso.pitch ); creature->o_torso.roll = angle_normalize( unaffected_r_torso.roll ); creature->s_team = u8( g_Team() ); creature->s_squad = u8( g_Squad() ); creature->s_group = u8( g_Group() ); CSE_ALifeCreatureActor* actor = smart_cast<CSE_ALifeCreatureActor*>( E ); actor->mstate = (u16)( mstate_real & 0x0000ffff ); actor->accel = NET_SavedAccel; actor->velocity = character_physics_support()->movement()->GetVelocity(); actor->fRadiation = g_Radiation(); actor->weapon = u8( inventory().GetActiveSlot() ); ///////////////////////////////////////////////// actor->m_u16NumItems = 0; };
#include <bits/stdc++.h> using namespace std; void addEdge(vector<int> adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } void displayGraph(vector<int> adj[], int v) { for (int i = 0; i < v; i++) { for (auto &&j : adj[i]) cout << j << " "; cout << endl; } } vector<int> shortestPath(vector<int> adj[], int v, int start) { vector<int> dist(v,INT32_MAX); bool visited[v + 1]{}; queue<int> q; q.push(start); visited[start] = true; dist[0] = 0; while (!q.empty()) { int u = q.front(); q.pop(); for (auto &&i : adj[u]) { if (visited[i] == false) { visited[i] = true; q.push(i); dist[i] = dist[u] + 1; } } } return dist; } int main() { vector<int> adj[4]; addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 2, 3); displayGraph(adj, 4); vector<int> v=shortestPath(adj,4,0); for (auto &&i : v) cout<<i<<" "; return 0; }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/policy/external_data/cloud_external_data_manager_base_test_util.h" #include <utility> #include "base/callback.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_writer.h" #include "base/memory/weak_ptr.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "chrome/common/chrome_paths.h" #include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/cloud/cloud_policy_core.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" #include "crypto/sha2.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace policy { namespace { // Keys for 'DictionaryValue' objects const char kUrlKey[] = "url"; const char kHashKey[] = "hash"; } // namespace namespace test { void ExternalDataFetchCallback(std::unique_ptr<std::string>* data_destination, base::FilePath* file_path_destination, base::OnceClosure done_callback, std::unique_ptr<std::string> data, const base::FilePath& file_path) { *data_destination = std::move(data); *file_path_destination = file_path; std::move(done_callback).Run(); } std::unique_ptr<base::DictionaryValue> ConstructExternalDataReference( const std::string& url, const std::string& data) { const std::string hash = crypto::SHA256HashString(data); std::unique_ptr<base::DictionaryValue> metadata(new base::DictionaryValue); metadata->SetKey(kUrlKey, base::Value(url)); metadata->SetKey(kHashKey, base::Value(base::HexEncode(hash.c_str(), hash.size()))); return metadata; } std::string ConstructExternalDataPolicy( const net::test_server::EmbeddedTestServer& test_server, const std::string& external_data_path) { std::string url = test_server.GetURL(std::string("/") + external_data_path).spec(); std::string external_data; base::FilePath test_data_dir; EXPECT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir)); { base::ScopedAllowBlockingForTesting allow_blocking; EXPECT_TRUE(base::ReadFileToString( test_data_dir.AppendASCII(external_data_path), &external_data)); } std::string policy; EXPECT_TRUE(base::JSONWriter::Write( *ConstructExternalDataReference(url, external_data), &policy)); return policy; } } // namespace test } // namespace policy
// Copyright 2021 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 "components/history_clusters/core/noisy_cluster_finalizer.h" #include "components/history_clusters/core/on_device_clustering_features.h" #include "components/history_clusters/core/on_device_clustering_util.h" namespace history_clusters { NoisyClusterFinalizer::NoisyClusterFinalizer() = default; NoisyClusterFinalizer::~NoisyClusterFinalizer() = default; void NoisyClusterFinalizer::FinalizeCluster(history::Cluster& cluster) { size_t interesting_visit_cnt = 0; for (const auto& visit : cluster.visits) { if (visit.engagement_score < features::NoisyClusterVisitEngagementThreshold()) { interesting_visit_cnt += 1; } if (interesting_visit_cnt >= features::NumberInterestingVisitsFilterThreshold()) { return; } } // If we check all the visits in the cluster and all have high engagement // scores, then its probably not interesting so we can hide it. cluster.should_show_on_prominent_ui_surfaces = false; } } // namespace history_clusters
// // Created by danie on 23/12/2020. // #include <iostream> #include <cstring> #include "compito.h" using namespace std; ToDoList::ToDoList() { p0 = 0; } void ToDoList::aggiungi(const char *description, unsigned int priority) { if (description == NULL || priority < 1 || strlen(description) > MAX_DIM_DESC) return; compito *p = 0, *q; for (q = p0; q != NULL && q->priority <= priority; q = q->nextCompito) { p = q; } compito *temp = new compito; temp->priority = priority; strcpy(temp->desc, description); temp->isDone = false; temp->nextCompito = q; //Aggiunta in testa if (q == p0) p0 = temp; else p->nextCompito = temp; } ostream &operator<<(ostream &os, const ToDoList &tdl) { compito *p; for (p = tdl.p0; p != NULL; p = p->nextCompito) { if (p->isDone) os << "V "; else os << " "; os << p->priority << " - " << p->desc << endl; } return os; } ToDoList::~ToDoList() { compito *p, *q; for (p = p0; p != NULL;) { q = p; p = p->nextCompito; delete q; } } ToDoList &ToDoList::operator+=(const ToDoList &tdl) { if (&tdl == this) return *this; compito *z; compito *p, *q; // Selezione di ogni task di tdl for (z = tdl.p0; z != NULL; z = z->nextCompito) aggiungi(z->desc, z->priority); return *this; } void ToDoList::fai(const char *descr) { if (descr == NULL || strlen(descr) > MAX_DIM_DESC) return; compito *p; for (p = p0; p != NULL; p = p->nextCompito) { if ((strcmp(p->desc, descr) == 0) && !(p->isDone)) { p->isDone = true; break; } } } void ToDoList::cancella_fatti() { compito *p, *q, *r; for(p = p0; p != NULL; p = p->nextCompito){ if(p->isDone){ if(p == p0){ // estrazione in testa r = p0->nextCompito; delete p0; p0 = r; } else{ // estrazione in mezzo o in fondo r = p->nextCompito; delete p; q->nextCompito = r; p=q; } } q = p; } }
#include "gtest/gtest.h" #include "z5/s3/handle.hxx" namespace z5 { // fixture for the handle test class HandleTest : public ::testing::Test { protected: HandleTest(){} ~HandleTest(){ } void SetUp() { } void TearDown() { } }; TEST_F(HandleTest, TestFile) { // Make a file z5::s3::handle::File f; f.create(); } TEST_F(HandleTest, TestGroup) { // Make a file z5::s3::handle::File f; // Make a group z5::s3::handle::Group g(f, "group"); g.create(); // Make a sub-group z5::s3::handle::Group g1(g, "sub"); g1.create(); } TEST_F(HandleTest, TestDataset) { // Make a file z5::s3::handle::File f; // Make a dataset z5::s3::handle::Dataset ds(f, "ds"); ds.create(); // Make a group z5::s3::handle::Group g(f, "group"); // Make a dataset z5::s3::handle::Dataset ds1(g, "ds"); ds1.create(); } }
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <future> #include "behavior/ov_infer_request/cancellation.hpp" #include "openvino/runtime/exception.hpp" namespace ov { namespace test { namespace behavior { std::string OVInferRequestCancellationTests::getTestCaseName(const testing::TestParamInfo<InferRequestParams>& obj) { return OVInferRequestTests::getTestCaseName(obj); } TEST_P(OVInferRequestCancellationTests, canCancelAsyncRequest) { runtime::InferRequest req; OV_ASSERT_NO_THROW(req = execNet.create_infer_request()); OV_ASSERT_NO_THROW(req.start_async()); OV_ASSERT_NO_THROW(req.cancel()); try { req.wait(); } catch (const ov::runtime::Cancelled&) { SUCCEED(); } } TEST_P(OVInferRequestCancellationTests, CanResetAfterCancelAsyncRequest) { runtime::InferRequest req; OV_ASSERT_NO_THROW(req = execNet.create_infer_request()); OV_ASSERT_NO_THROW(req.start_async()); OV_ASSERT_NO_THROW(req.cancel()); try { req.wait(); } catch (const ov::runtime::Cancelled&) { SUCCEED(); } OV_ASSERT_NO_THROW(req.start_async()); OV_ASSERT_NO_THROW(req.wait()); } TEST_P(OVInferRequestCancellationTests, canCancelBeforeAsyncRequest) { runtime::InferRequest req; OV_ASSERT_NO_THROW(req = execNet.create_infer_request()); OV_ASSERT_NO_THROW(req.cancel()); } TEST_P(OVInferRequestCancellationTests, canCancelInferRequest) { runtime::InferRequest req; OV_ASSERT_NO_THROW(req = execNet.create_infer_request()); auto infer = std::async(std::launch::async, [&req]{req.infer();}); while (!req.wait_for({})) { } OV_ASSERT_NO_THROW(req.cancel()); try { infer.get(); } catch (const ov::runtime::Cancelled&) { SUCCEED(); } } } // namespace behavior } // namespace test } // namespace ov
#include <stdio.h> int main(int argc, const char *argv[]) { printf("hello world\n"); return 0; }
// Copyright 2015 MongoDB 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 <bsoncxx/document/value.hpp> #include <bsoncxx/document/view.hpp> #include <bsoncxx/private/libbson.hh> #include <bsoncxx/config/private/prelude.hh> namespace bsoncxx { BSONCXX_INLINE_NAMESPACE_BEGIN namespace helpers { inline document::view view_from_bson_t(const bson_t* bson) { return {::bson_get_data(bson), bson->len}; } inline document::value value_from_bson_t(const bson_t* bson) { return document::value{view_from_bson_t(bson)}; } } // namespace helpers BSONCXX_INLINE_NAMESPACE_END } // namespace bsoncxx #include <bsoncxx/config/private/postlude.hh>
// NewFileDlg.cpp #include "stdafx.h" #include "resource.h" #include "NewFileDlg.h" /* static */ bool CNewFileDlg::m_bBraille2 = true; /* static */ int CNewFileDlg::m_nExt = 0; LRESULT CNewFileDlg::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { CenterWindow(); // Set some default info. // Give the file a temporary name. Filename is not used but I set just in case. m_strName = _T("temp"); m_strExt.LoadString(IDS_SKIPPER_EXT); m_strName += m_strExt.Right(4); m_nExt = 0; // Set the default directory. CString str; //str.LoadString(IDS_MY_DOCUMENTS); //m_strDirectory = _T('\\') + str + _T('\\'); // Make the static text a child of the window. //CStatic ctrlAsk; //ctrlAsk.Attach(GetDlgItem(IDC_ASK_GRADE_TWO)); //CButton ctrlYes; //ctrlYes.Attach(GetDlgItem(IDYES)); //ctrlYes.SetFocus(); return 0; } LRESULT CNewFileDlg::OnYes(WORD wNotifyCode, WORD wID, HWND hWndCtrl, BOOL& bHandled) { m_bBraille2 = true; EndDialog(IDOK); return 0; } LRESULT CNewFileDlg::OnNo(WORD wNotifyCode, WORD wID, HWND hWndCtrl, BOOL& bHandled) { m_bBraille2 = false; EndDialog(IDOK); return 0; } LRESULT CNewFileDlg::OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtrl, BOOL& bHandled) { EndDialog(IDCANCEL); return 0; }
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/cognito-sync/model/DeleteDatasetResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CognitoSync::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DeleteDatasetResult::DeleteDatasetResult() { } DeleteDatasetResult::DeleteDatasetResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } DeleteDatasetResult& DeleteDatasetResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("Dataset")) { m_dataset = jsonValue.GetObject("Dataset"); } return *this; }
#include "LearnOpenGL_GLFW/Sen_06_TrianglesGLFW.h" #include "LearnOpenGL_GLFW/Sen_07_TextureGLFW.h" #include "LearnOpenGL_GLFW/Sen_09_ModelViewProjection.h" #include "LearnOpenGL_GLFW/Sen_10_Camera.h" //#include "LearnOpenGL_GLFW/Sen_21_AssimpMeshModel.h" #include "LearnOpenGL_GLFW/Sen_22_DepthTest.h" #include "LearnOpenGL_GLFW/Sen_23_StencilObjectOutline.h" #include "LearnOpenGL_GLFW/Sen_24_BlendingTest.h" #include "LearnOpenGL_GLFW/Sen_26_PostProcessing.h" #include "LearnOpenGL_GLFW/Sen_262_RearMirror.h" #include "LearnOpenGL_GLFW/Sen_263_DebugRearMirror.h" #include "LearnOpenGL_GLFW/Sen_30_GeometryShow.h" //#include "LearnOpenGL_GLFW/Sen_303_NanoSuitExplode.h" //#include "LearnOpenGL_GLFW/Sen_430_DebugOutput.h" #include "LearnOpenGL_GLFW/Sen_431_LineTextRendering.h" #include "Sinks/BreakOut/Sen_47_BlendSprite.h" #include "Sinks/BreakOut/Sen_BreakOut.h" #include "Sinks/TeapotExplosion/Sen_TeapotExplosion.h" int main(int argc, char *argv[]) { Sen_BreakOut widget; widget.ShowWidget(); return 1; }
/** * DeepDetect * Copyright (c) 2014-2015 Emmanuel Benazera * Author: Emmanuel Benazera <beniz@droidnik.fr> * * This file is part of deepdetect. * * deepdetect is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * deepdetect 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 deepdetect. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DD_FILEOPS_H #define DD_FILEOPS_H #include <fstream> #include <unordered_set> #include <sys/stat.h> #include <stdio.h> #if defined(WIN32) #include <boost/filesystem.hpp> #else #include <dirent.h> #include <unistd.h> #include <archive.h> #include <archive_entry.h> #endif namespace dd { class fileops { public: #if defined(WIN32) static bool create_dir(const std::string &dirName, int mode) { assert(false); return false; } static bool file_exists(const std::string &fname) { boost::filesystem::path p(fname); return boost::filesystem::exists(p); } static bool file_exists(const std::string &fname, bool &directory) { boost::filesystem::path p(fname); directory = boost::filesystem::is_directory(p); return boost::filesystem::exists(p); } static bool is_db(const std::string &fname) { const std::vector<std::string> db_exts = { ".lmdb" }; // add more here for (auto e : db_exts) if (fname.find(e) != std::string::npos) return true; return false; } static long int file_last_modif(const std::string &fname) { boost::filesystem::path p(fname); return boost::filesystem::last_write_time(p); } static int list_directory(const std::string &repo, const bool &files, const bool &dirs, const bool &sub_files, std::unordered_set<std::string> &lfiles) { boost::filesystem::path p(repo); if (!boost::filesystem::is_directory(p)) return 1; boost::filesystem::directory_iterator dir_iter(p); boost::filesystem::directory_iterator end_iter; for (; dir_iter != end_iter; ++dir_iter) { if ((dirs && boost::filesystem::is_directory(dir_iter->status())) || (files && boost::filesystem::is_regular_file(dir_iter->status())) || ((dirs||files) && boost::filesystem::is_symlink(dir_iter->status()))) lfiles.insert(dir_iter->path().string()); if (sub_files && (boost::filesystem::is_directory(dir_iter->status()) || boost::filesystem::is_symlink(dir_iter->status()))) list_directory(dir_iter->path().string(), files, dirs, sub_files, lfiles); } return 0; } static int clear_directory(const std::string &repo) { assert(false); return -1; } static int remove_dir(const std::string &d) { assert(false); return -1; } static int uncompress(const std::string &fc, const std::string &repo) { assert(false); return -1; } #else static bool create_dir(const std::string &dirName, mode_t mode) { std::string s = dirName; size_t pre=0,pos; std::string dir; int mdret = 0; if(s[s.size()-1]!='/'){ // force trailing / so we can handle everything in loop s+='/'; } while((pos=s.find_first_of('/',pre))!=std::string::npos){ dir=s.substr(0,pos++); pre=pos; if(dir.size()==0) continue; // if leading / first time is 0 length if((mdret=mkdir(dir.c_str(),mode)) && errno!=EEXIST){ return mdret; } } return mdret; } static bool file_exists(const std::string &fname) { struct stat bstat; return (stat(fname.c_str(),&bstat)==0); } static bool dir_exists(const std::string &fname) { bool dir; bool exists = file_exists(fname, dir); return exists && dir; } static bool file_exists(const std::string &fname, bool &directory) { struct stat bstat; int r = stat(fname.c_str(),&bstat); if (r != 0) { directory = false; return false; } if (S_ISDIR(bstat.st_mode)) directory = true; else directory = false; return r == 0; } static bool is_db(const std::string &fname) { const std::vector<std::string> db_exts = {".lmdb"}; // add more here for (auto e: db_exts) if (fname.find(e) != std::string::npos) return true; return false; } static long int file_last_modif(const std::string &fname) { struct stat bstat; if (stat(fname.c_str(),&bstat)==0) return bstat.st_mtim.tv_sec; else return -1; } static int list_directory(const std::string &repo, const bool &files, const bool &dirs, const bool &sub_files, std::unordered_set<std::string> &lfiles) { DIR *dir; struct dirent *ent; if ((dir = opendir(repo.c_str())) != NULL) { while ((ent = readdir(dir)) != NULL) { if ((files && (ent->d_type == DT_REG || ent->d_type == DT_LNK)) || (dirs && (ent->d_type == DT_DIR || ent->d_type == DT_LNK) && ent->d_name[0] != '.')) lfiles.insert(std::string(repo) + "/" + std::string(ent->d_name)); if (sub_files && (ent->d_type == DT_DIR || ent->d_type == DT_LNK) && ent->d_name[0] != '.') list_directory(std::string(repo) + "/" + std::string(ent->d_name),files,dirs,sub_files,lfiles); } closedir(dir); return 0; } else { return 1; } } // remove everything, including first level directories within directory static int clear_directory(const std::string &repo) { int err = 0; DIR *dir; struct dirent *ent; if ((dir = opendir(repo.c_str())) != NULL) { while ((ent = readdir(dir)) != NULL) { if (ent->d_type == DT_DIR && ent->d_name[0] == '.') continue; else { std::string f = std::string(repo) + "/" + std::string(ent->d_name); if (ent->d_type == DT_DIR) { int errdf = remove_directory_files(f,std::vector<std::string>()); int errd = rmdir(f.c_str()); err += errdf + errd; } else err += remove(f.c_str()); } } closedir(dir); return err; } else { return 1; } } // empty extensions means a wildcard static int remove_directory_files(const std::string &repo, const std::vector<std::string> &extensions) { int err = 0; DIR *dir; struct dirent *ent; if ((dir = opendir(repo.c_str())) != NULL) { while ((ent = readdir(dir)) != NULL) { std::string lf = std::string(ent->d_name); if (ent->d_type == DT_DIR && ent->d_name[0] == '.') continue; if (extensions.empty()) { std::string f = std::string(repo) + "/" + lf; err += remove(f.c_str()); } else { for (std::string s : extensions) if (lf.find(s) != std::string::npos) { std::string f = std::string(repo) + "/" + lf; err += remove(f.c_str()); break; } } } closedir(dir); return err; } else { return 1; } } static int copy_file(const std::string &fin, const std::string &fout) { std::ifstream src(fin,std::ios::binary); if (!src.is_open()) return 1; std::ofstream dst(fout,std::ios::binary); if (!dst.is_open()) return 2; dst << src.rdbuf(); src.close(); dst.close(); return 0; } static int remove_file(const std::string &repo, const std::string &f) { std::string fn = repo + "/" + f; if (remove(fn.c_str())) return -1; // error. return 0; } static int remove_dir(const std::string &d) { if (remove(d.c_str())) return -1; // error. return 0; } static int copy_uncompressed_data(struct archive *ar, struct archive *aw) { int r; const void *buff; size_t size; int64_t offset; for (;;) { r = archive_read_data_block(ar, &buff, &size, &offset); if (r == ARCHIVE_EOF) return (ARCHIVE_OK); if (r < ARCHIVE_OK) return (r); r = archive_write_data_block(aw, buff, size, offset); if (r < ARCHIVE_OK) { std::cerr << "archive error: " << archive_error_string(aw) << std::endl; return r; } } } static int uncompress(const std::string &fc, const std::string &repo) { struct archive *a; struct archive *ext; struct archive_entry *entry; int flags; int r; flags = ARCHIVE_EXTRACT_TIME; //flags |= ARCHIVE_EXTRACT_PERM; //flags |= ARCHIVE_EXTRACT_ACL; flags |= ARCHIVE_EXTRACT_FFLAGS; a = archive_read_new(); archive_read_support_format_all(a); archive_read_support_filter_all(a); ext = archive_write_disk_new(); archive_write_disk_set_options(ext, flags); archive_write_disk_set_standard_lookup(ext); if ((r = archive_read_open_filename(a, fc.c_str(), 10240))) // 10240 is block_size return r; for (;;) { r = archive_read_next_header(a, &entry); if (r == ARCHIVE_EOF) break; if (r < ARCHIVE_OK) std::cerr << "archive error: " << archive_error_string(a) << std::endl; if (r < ARCHIVE_WARN) { std::cerr << "archive error, aborting\n"; return 1; } const char * compressed_head = archive_entry_pathname(entry); const std::string full_outpath = repo + "/" + compressed_head; archive_entry_set_pathname(entry,full_outpath.c_str()); r = archive_write_header(ext, entry); if (r < ARCHIVE_OK) std::cerr << "archive error: " << archive_error_string(ext) << std::endl; else if (archive_entry_size(entry) > 0) { r = copy_uncompressed_data(a, ext); if (r < ARCHIVE_OK) std::cerr << "error writing uncompressed data: " << archive_error_string(ext) << std::endl; if (r < ARCHIVE_WARN) { std::cerr << "archive error, aborting\n"; return 2; } } r = archive_write_finish_entry(ext); if (r < ARCHIVE_OK) std::cerr << "error finishing uncompressed data entry: " << archive_error_string(ext) << std::endl; if (r < ARCHIVE_WARN) { std::cerr << "archive error, aborting\n"; return 3; } } archive_read_close(a); archive_read_free(a); archive_write_close(ext); archive_write_free(ext); return 0; } #endif }; } #endif
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** \file * \ingroup freestyle */ #include "BPy_BezierCurveShader.h" #include "../../stroke/BasicStrokeShaders.h" #ifdef __cplusplus extern "C" { #endif /////////////////////////////////////////////////////////////////////////////////////////// //------------------------INSTANCE METHODS ---------------------------------- static char BezierCurveShader___doc__[] = "Class hierarchy: :class:`freestyle.types.StrokeShader` > :class:`BezierCurveShader`\n" "\n" "[Geometry shader]\n" "\n" ".. method:: __init__(error=4.0)\n" "\n" " Builds a BezierCurveShader object.\n" "\n" " :arg error: The error we're allowing for the approximation. This\n" " error is the max distance allowed between the new curve and the\n" " original geometry.\n" " :type error: float\n" "\n" ".. method:: shade(stroke)\n" "\n" " Transforms the stroke backbone geometry so that it corresponds to a\n" " Bezier Curve approximation of the original backbone geometry.\n" "\n" " :arg stroke: A Stroke object.\n" " :type stroke: :class:`freestyle.types.Stroke`\n"; static int BezierCurveShader___init__(BPy_BezierCurveShader *self, PyObject *args, PyObject *kwds) { static const char *kwlist[] = {"error", NULL}; float f = 4.0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|f", (char **)kwlist, &f)) return -1; self->py_ss.ss = new StrokeShaders::BezierCurveShader(f); return 0; } /*-----------------------BPy_BezierCurveShader type definition ------------------------------*/ PyTypeObject BezierCurveShader_Type = { PyVarObject_HEAD_INIT(NULL, 0) "BezierCurveShader", /* tp_name */ sizeof(BPy_BezierCurveShader), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ BezierCurveShader___doc__, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &StrokeShader_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)BezierCurveShader___init__, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; /////////////////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus } #endif
#include "ros/ros.h" #include "geometry_msgs/Twist.h" #include "std_msgs/String.h" #include <sstream> #include <iostream> #include <string.h> using namespace std; // Topic messages callback void chatterCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("[Listener] I heard: [%s]\n", msg->data.c_str()); ros::NodeHandle n; ros::Publisher pub = n.advertise<geometry_msgs::Twist>("/cmd_vel", 1000); geometry_msgs::Twist vel; vel.linear.x = double(1.0); vel.angular.z = double(1.0); pub.publish(vel); //ROS_INFO_STREAM("Filtered velocities:"<<" linear="<<msg.linear.x<<" angular="<<msg.angular.z); } int main(int argc, char **argv) { ros::init(argc, argv, "lf_controller"); ros::NodeHandle node; ros::Subscriber sub = node.subscribe("/lineSensor", 1000, chatterCallback); ros::spin(); return 0; }
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Unit tests for alert system #include "alert.h" #include "chain.h" #include "chainparams.h" #include "clientversion.h" #include "data/alertTests.raw.h" #include "serialize.h" #include "streams.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_strength.h" #include <fstream> #include <boost/filesystem/operations.hpp> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> // // Sign a CAlert and serialize it // bool SignAndSave(CAlert &alert) { // Sign if(!alert.Sign()) { printf("SignAndSave() : could not sign alert:\n%s", alert.ToString().c_str()); return false; } std::string strFilePath = "src/test/data/alertTests.raw"; // open output file and associate it with CAutoFile FILE *file = fopen(strFilePath.c_str(), "ab+"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s: Failed to open file %s", __func__, strFilePath); try { fileout << alert; } catch (std::exception &e) { return error("%s: Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); return true; } // // alertTests contains 8 alerts, generated with this code // void GenerateAlertTests() { CAlert alert; alert.nRelayUntil = 60; alert.nExpiration = 24 * 60 * 60; alert.nID = 1; alert.nCancel = 0; // cancels previous messages up to this ID number alert.nMinVer = 0; // These versions are protocol versions alert.nMaxVer = 999001; alert.nPriority = 1; alert.strComment = "Alert comment"; alert.strStatusBar = "Alert 1"; SignAndSave(alert); alert.setSubVer.insert(std::string("/Satoshi:0.1.0/")); alert.strStatusBar = "Alert 1 for Satoshi 0.1.0"; SignAndSave(alert); alert.setSubVer.insert(std::string("/Satoshi:0.2.0/")); alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0"; SignAndSave(alert); alert.setSubVer.clear(); ++alert.nID; alert.nCancel = 1; alert.nPriority = 100; alert.strStatusBar = "Alert 2, cancels 1"; SignAndSave(alert); alert.nExpiration += 60; ++alert.nID; SignAndSave(alert); ++alert.nID; alert.nMinVer = 11; alert.nMaxVer = 22; SignAndSave(alert); ++alert.nID; alert.strStatusBar = "Alert 2 for Satoshi 0.1.0"; alert.setSubVer.insert(std::string("/Satoshi:0.1.0/")); SignAndSave(alert); ++alert.nID; alert.nMinVer = 0; alert.nMaxVer = 999999; alert.strStatusBar = "Evil Alert'; /bin/ls; echo '"; alert.setSubVer.clear(); SignAndSave(alert); } struct ReadAlerts : public TestingSetup { ReadAlerts() { std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests)); CDataStream stream(vch, SER_DISK, CLIENT_VERSION); try { while (!stream.eof()) { CAlert alert; stream >> alert; alerts.push_back(alert); } } catch (const std::exception&) { } } ~ReadAlerts() { } static std::vector<std::string> read_lines(boost::filesystem::path filepath) { std::vector<std::string> result; std::ifstream f(filepath.string().c_str()); std::string line; while (std::getline(f,line)) result.push_back(line); return result; } std::vector<CAlert> alerts; }; BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts) // Steps to generate alert tests: // - update alerts in GenerateAlertTests() (optional) // - enable code below (#if 1) // - replace "fffffffffffffffffffffffffffffffffffffffffffffffffff" with the actual MAINNET privkey // - recompile and run "/path/to/test_strength -t Alert_test" // // NOTE: make sure to disable code and remove alert privkey when you're done! // #if 0 BOOST_AUTO_TEST_CASE(GenerateAlerts) { SoftSetArg("-alertkey", "fffffffffffffffffffffffffffffffffffffffffffffffffff"); GenerateAlertTests(); } #endif BOOST_AUTO_TEST_CASE(AlertApplies) { SetMockTime(11); const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey(); BOOST_FOREACH(const CAlert& alert, alerts) { BOOST_CHECK(alert.CheckSignature(alertKey)); } BOOST_CHECK(alerts.size() >= 3); // Matches: BOOST_CHECK(alerts[0].AppliesTo(1, "")); BOOST_CHECK(alerts[0].AppliesTo(999001, "")); BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/")); BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/")); BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/")); // Don't match: BOOST_CHECK(!alerts[0].AppliesTo(-1, "")); BOOST_CHECK(!alerts[0].AppliesTo(999002, "")); BOOST_CHECK(!alerts[1].AppliesTo(1, "")); BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0")); BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0")); BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/")); BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/")); BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/")); SetMockTime(0); } BOOST_AUTO_TEST_CASE(AlertNotify) { SetMockTime(11); const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey(); boost::filesystem::path temp = GetTempPath() / boost::filesystem::unique_path("alertnotify-%%%%.txt"); mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string(); BOOST_FOREACH(CAlert alert, alerts) alert.ProcessAlert(alertKey, false); std::vector<std::string> r = read_lines(temp); BOOST_CHECK_EQUAL(r.size(), 4u); // Windows built-in echo semantics are different than posixy shells. Quotes and // whitespace are printed literally. #ifndef WIN32 BOOST_CHECK_EQUAL(r[0], "Alert 1"); BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1"); BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1"); BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed #else BOOST_CHECK_EQUAL(r[0], "'Alert 1' "); BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' "); BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' "); BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' "); #endif boost::filesystem::remove(temp); SetMockTime(0); } BOOST_AUTO_TEST_SUITE_END()
/* The Internet Filter Version 3 Kernel Version 3 Source Code Written By Jeff Koftinoff <jeffk@internetfilter.com> Copyright (c) 1995-2005 By Turner and Sons Productions, Inc. http://www.internetfilter.com/ ALL RIGHTS RESERVED. */ #ifndef IF3_WORLD_HPP #define IF3_WORLD_HPP #ifndef IF3_WORLD_PRECOMPILED_HPP #include "if3_world_precompiled.hpp" #endif #endif
// // // /// @brief Calculates the trace of the current rank two array if it /// is square and was previously initialized either by construction /// or the array::create() member function. Otherwise returns zero. // /// @return A numerical data with the same type of the array. // data_type trace() { data_type trace(0.0); if(is_square()) { for(INIT_ITER(i, 1); i <= data_length(); ++i) { trace += data[offset(i, i)]; } } return trace; };
#include <iostream> extern "C" { #include "bar.h" #include "zingo.h" } int main() { if( bar() == 42*42 ) std::cout << "ok" << std::endl; else std::cout << "failed" << std::endl; if( zingo() == 41*42 ) std::cout << "ok" << std::endl; else std::cout << "failed" << std::endl; }
#include <CoreLib/UString.h> #include <cassert> using namespace JxCoreLib; void TestString() { string s("a word 一个字"); assert(StringUtil::Length(s) == 10); u8char c = StringUtil::CharAt(s, 9); assert(c == u8char{ "字" }); StringIndexMapping mapping(s, 2); // use cache u8char c2 = StringUtil::CharAt(s, 9, mapping); assert(c2 == u8char{ "字" }); u8char nc("个"); nc.ToString(); assert(nc.ToString() == string("个")); string str_concat = StringUtil::Concat("123", "ab", string("ba")); assert(str_concat == "123abba"); string newstr = StringUtil::Replace(str_concat, "ab", "a"); assert(newstr == "123aba"); }
//C- -*- C++ -*- //C- ------------------------------------------------------------------- //C- DjVuLibre-3.5 //C- Copyright (c) 2002 Leon Bottou and Yann Le Cun. //C- Copyright (c) 2001 AT&T //C- //C- This software is subject to, and may be distributed under, the //C- GNU General Public License, either Version 2 of the license, //C- or (at your option) any later version. The license should have //C- accompanied the software or you may obtain a copy of the license //C- from the Free Software Foundation at http://www.fsf.org . //C- //C- This program is distributed in the hope that it will be useful, //C- but WITHOUT ANY WARRANTY; without even the implied warranty of //C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //C- GNU General Public License for more details. //C- //C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library from //C- Lizardtech Software. Lizardtech Software has authorized us to //C- replace the original DjVu(r) Reference Library notice by the following //C- text (see doc/lizard2002.djvu and doc/lizardtech2007.djvu): //C- //C- ------------------------------------------------------------------ //C- | DjVu (r) Reference Library (v. 3.5) //C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved. //C- | The DjVu Reference Library is protected by U.S. Pat. No. //C- | 6,058,214 and patents pending. //C- | //C- | This software is subject to, and may be distributed under, the //C- | GNU General Public License, either Version 2 of the license, //C- | or (at your option) any later version. The license should have //C- | accompanied the software or you may obtain a copy of the license //C- | from the Free Software Foundation at http://www.fsf.org . //C- | //C- | The computer code originally released by LizardTech under this //C- | license and unmodified by other parties is deemed "the LIZARDTECH //C- | ORIGINAL CODE." Subject to any third party intellectual property //C- | claims, LizardTech grants recipient a worldwide, royalty-free, //C- | non-exclusive license to make, use, sell, or otherwise dispose of //C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the //C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU //C- | General Public License. This grant only confers the right to //C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to //C- | the extent such infringement is reasonably necessary to enable //C- | recipient to make, have made, practice, sell, or otherwise dispose //C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to //C- | any greater extent that may be necessary to utilize further //C- | modifications or combinations. //C- | //C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY //C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED //C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF //C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. //C- +------------------------------------------------------------------ #ifdef HAVE_CONFIG_H # include "config.h" #endif #if NEED_GNUG_PRAGMAS # pragma implementation #endif // From: Leon Bottou, 1/31/2002 // Almost equal to my initial code. #include "ZPCodec.h" #include "ByteStream.h" #include "GException.h" #include <stddef.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <stdio.h> #ifdef HAVE_NAMESPACES namespace DJVU { # ifdef NOT_DEFINED // Just to fool emacs c++ mode } #endif #endif //////////////////////////////////////////////////////////////// // CODER SPECIFICATION //////////////////////////////////////////////////////////////// #ifndef ZPCODER #ifndef ZCODER #define ZPCODER #endif #endif #ifdef ZCODER // The ZCODER option is provided for documentation purposes only. The ZCODER // might come dangerously close to U.S. patent 5059976 (Mitsubishi). This is // why we always use the ZPCODER, although it usually produces 1% larger files. #warning "The ZCODER may infringe non-LizardTech patent(s)." #warning "You should use the ZPCODER instead." #endif //////////////////////////////////////////////////////////////// // ZP CODER DEFAULT ADAPTATION TABLE //////////////////////////////////////////////////////////////// // See ZPCodec::ZPCodec to see how this // default table is modified when not // using the DjVu compatibility mode. static ZPCodec::Table default_ztable[256] = { #ifdef ZPCODER /* This table has been designed for the ZPCoder * by running the following command in file 'zptable.sn': * (fast-crude (steady-mat 0.0035 0.0002) 260))) */ { 0x8000, 0x0000, 84, 145 }, /* 000: p=0.500000 ( 0, 0) */ { 0x8000, 0x0000, 3, 4 }, /* 001: p=0.500000 ( 0, 0) */ { 0x8000, 0x0000, 4, 3 }, /* 002: p=0.500000 ( 0, 0) */ { 0x6bbd, 0x10a5, 5, 1 }, /* 003: p=0.465226 ( 0, 0) */ { 0x6bbd, 0x10a5, 6, 2 }, /* 004: p=0.465226 ( 0, 0) */ { 0x5d45, 0x1f28, 7, 3 }, /* 005: p=0.430708 ( 0, 0) */ { 0x5d45, 0x1f28, 8, 4 }, /* 006: p=0.430708 ( 0, 0) */ { 0x51b9, 0x2bd3, 9, 5 }, /* 007: p=0.396718 ( 0, 0) */ { 0x51b9, 0x2bd3, 10, 6 }, /* 008: p=0.396718 ( 0, 0) */ { 0x4813, 0x36e3, 11, 7 }, /* 009: p=0.363535 ( 0, 0) */ { 0x4813, 0x36e3, 12, 8 }, /* 010: p=0.363535 ( 0, 0) */ { 0x3fd5, 0x408c, 13, 9 }, /* 011: p=0.331418 ( 0, 0) */ { 0x3fd5, 0x408c, 14, 10 }, /* 012: p=0.331418 ( 0, 0) */ { 0x38b1, 0x48fd, 15, 11 }, /* 013: p=0.300585 ( 0, 0) */ { 0x38b1, 0x48fd, 16, 12 }, /* 014: p=0.300585 ( 0, 0) */ { 0x3275, 0x505d, 17, 13 }, /* 015: p=0.271213 ( 0, 0) */ { 0x3275, 0x505d, 18, 14 }, /* 016: p=0.271213 ( 0, 0) */ { 0x2cfd, 0x56d0, 19, 15 }, /* 017: p=0.243438 ( 0, 0) */ { 0x2cfd, 0x56d0, 20, 16 }, /* 018: p=0.243438 ( 0, 0) */ { 0x2825, 0x5c71, 21, 17 }, /* 019: p=0.217391 ( 0, 0) */ { 0x2825, 0x5c71, 22, 18 }, /* 020: p=0.217391 ( 0, 0) */ { 0x23ab, 0x615b, 23, 19 }, /* 021: p=0.193150 ( 0, 0) */ { 0x23ab, 0x615b, 24, 20 }, /* 022: p=0.193150 ( 0, 0) */ { 0x1f87, 0x65a5, 25, 21 }, /* 023: p=0.170728 ( 0, 0) */ { 0x1f87, 0x65a5, 26, 22 }, /* 024: p=0.170728 ( 0, 0) */ { 0x1bbb, 0x6962, 27, 23 }, /* 025: p=0.150158 ( 0, 0) */ { 0x1bbb, 0x6962, 28, 24 }, /* 026: p=0.150158 ( 0, 0) */ { 0x1845, 0x6ca2, 29, 25 }, /* 027: p=0.131418 ( 0, 0) */ { 0x1845, 0x6ca2, 30, 26 }, /* 028: p=0.131418 ( 0, 0) */ { 0x1523, 0x6f74, 31, 27 }, /* 029: p=0.114460 ( 0, 0) */ { 0x1523, 0x6f74, 32, 28 }, /* 030: p=0.114460 ( 0, 0) */ { 0x1253, 0x71e6, 33, 29 }, /* 031: p=0.099230 ( 0, 0) */ { 0x1253, 0x71e6, 34, 30 }, /* 032: p=0.099230 ( 0, 0) */ { 0x0fcf, 0x7404, 35, 31 }, /* 033: p=0.085611 ( 0, 0) */ { 0x0fcf, 0x7404, 36, 32 }, /* 034: p=0.085611 ( 0, 0) */ { 0x0d95, 0x75d6, 37, 33 }, /* 035: p=0.073550 ( 0, 0) */ { 0x0d95, 0x75d6, 38, 34 }, /* 036: p=0.073550 ( 0, 0) */ { 0x0b9d, 0x7768, 39, 35 }, /* 037: p=0.062888 ( 0, 0) */ { 0x0b9d, 0x7768, 40, 36 }, /* 038: p=0.062888 ( 0, 0) */ { 0x09e3, 0x78c2, 41, 37 }, /* 039: p=0.053539 ( 0, 0) */ { 0x09e3, 0x78c2, 42, 38 }, /* 040: p=0.053539 ( 0, 0) */ { 0x0861, 0x79ea, 43, 39 }, /* 041: p=0.045365 ( 0, 0) */ { 0x0861, 0x79ea, 44, 40 }, /* 042: p=0.045365 ( 0, 0) */ { 0x0711, 0x7ae7, 45, 41 }, /* 043: p=0.038272 ( 0, 0) */ { 0x0711, 0x7ae7, 46, 42 }, /* 044: p=0.038272 ( 0, 0) */ { 0x05f1, 0x7bbe, 47, 43 }, /* 045: p=0.032174 ( 0, 0) */ { 0x05f1, 0x7bbe, 48, 44 }, /* 046: p=0.032174 ( 0, 0) */ { 0x04f9, 0x7c75, 49, 45 }, /* 047: p=0.026928 ( 0, 0) */ { 0x04f9, 0x7c75, 50, 46 }, /* 048: p=0.026928 ( 0, 0) */ { 0x0425, 0x7d0f, 51, 47 }, /* 049: p=0.022444 ( 0, 0) */ { 0x0425, 0x7d0f, 52, 48 }, /* 050: p=0.022444 ( 0, 0) */ { 0x0371, 0x7d91, 53, 49 }, /* 051: p=0.018636 ( 0, 0) */ { 0x0371, 0x7d91, 54, 50 }, /* 052: p=0.018636 ( 0, 0) */ { 0x02d9, 0x7dfe, 55, 51 }, /* 053: p=0.015421 ( 0, 0) */ { 0x02d9, 0x7dfe, 56, 52 }, /* 054: p=0.015421 ( 0, 0) */ { 0x0259, 0x7e5a, 57, 53 }, /* 055: p=0.012713 ( 0, 0) */ { 0x0259, 0x7e5a, 58, 54 }, /* 056: p=0.012713 ( 0, 0) */ { 0x01ed, 0x7ea6, 59, 55 }, /* 057: p=0.010419 ( 0, 0) */ { 0x01ed, 0x7ea6, 60, 56 }, /* 058: p=0.010419 ( 0, 0) */ { 0x0193, 0x7ee6, 61, 57 }, /* 059: p=0.008525 ( 0, 0) */ { 0x0193, 0x7ee6, 62, 58 }, /* 060: p=0.008525 ( 0, 0) */ { 0x0149, 0x7f1a, 63, 59 }, /* 061: p=0.006959 ( 0, 0) */ { 0x0149, 0x7f1a, 64, 60 }, /* 062: p=0.006959 ( 0, 0) */ { 0x010b, 0x7f45, 65, 61 }, /* 063: p=0.005648 ( 0, 0) */ { 0x010b, 0x7f45, 66, 62 }, /* 064: p=0.005648 ( 0, 0) */ { 0x00d5, 0x7f6b, 67, 63 }, /* 065: p=0.004506 ( 0, 0) */ { 0x00d5, 0x7f6b, 68, 64 }, /* 066: p=0.004506 ( 0, 0) */ { 0x00a5, 0x7f8d, 69, 65 }, /* 067: p=0.003480 ( 0, 0) */ { 0x00a5, 0x7f8d, 70, 66 }, /* 068: p=0.003480 ( 0, 0) */ { 0x007b, 0x7faa, 71, 67 }, /* 069: p=0.002602 ( 0, 0) */ { 0x007b, 0x7faa, 72, 68 }, /* 070: p=0.002602 ( 0, 0) */ { 0x0057, 0x7fc3, 73, 69 }, /* 071: p=0.001843 ( 0, 0) */ { 0x0057, 0x7fc3, 74, 70 }, /* 072: p=0.001843 ( 0, 0) */ { 0x003b, 0x7fd7, 75, 71 }, /* 073: p=0.001248 ( 0, 0) */ { 0x003b, 0x7fd7, 76, 72 }, /* 074: p=0.001248 ( 0, 0) */ { 0x0023, 0x7fe7, 77, 73 }, /* 075: p=0.000749 ( 0, 0) */ { 0x0023, 0x7fe7, 78, 74 }, /* 076: p=0.000749 ( 0, 0) */ { 0x0013, 0x7ff2, 79, 75 }, /* 077: p=0.000402 ( 0, 0) */ { 0x0013, 0x7ff2, 80, 76 }, /* 078: p=0.000402 ( 0, 0) */ { 0x0007, 0x7ffa, 81, 77 }, /* 079: p=0.000153 ( 0, 0) */ { 0x0007, 0x7ffa, 82, 78 }, /* 080: p=0.000153 ( 0, 0) */ { 0x0001, 0x7fff, 81, 79 }, /* 081: p=0.000027 ( 0, 0) */ { 0x0001, 0x7fff, 82, 80 }, /* 082: p=0.000027 ( 0, 0) */ { 0x5695, 0x0000, 9, 85 }, /* 083: p=0.411764 ( 2, 3) */ { 0x24ee, 0x0000, 86, 226 }, /* 084: p=0.199988 ( 1, 0) */ { 0x8000, 0x0000, 5, 6 }, /* 085: p=0.500000 ( 3, 3) */ { 0x0d30, 0x0000, 88, 176 }, /* 086: p=0.071422 ( 4, 0) */ { 0x481a, 0x0000, 89, 143 }, /* 087: p=0.363634 ( 1, 2) */ { 0x0481, 0x0000, 90, 138 }, /* 088: p=0.024388 ( 13, 0) */ { 0x3579, 0x0000, 91, 141 }, /* 089: p=0.285711 ( 1, 3) */ { 0x017a, 0x0000, 92, 112 }, /* 090: p=0.007999 ( 41, 0) */ { 0x24ef, 0x0000, 93, 135 }, /* 091: p=0.199997 ( 1, 5) */ { 0x007b, 0x0000, 94, 104 }, /* 092: p=0.002611 ( 127, 0) */ { 0x1978, 0x0000, 95, 133 }, /* 093: p=0.137929 ( 1, 8) */ { 0x0028, 0x0000, 96, 100 }, /* 094: p=0.000849 ( 392, 0) */ { 0x10ca, 0x0000, 97, 129 }, /* 095: p=0.090907 ( 1, 13) */ { 0x000d, 0x0000, 82, 98 }, /* 096: p=0.000276 ( 1208, 0) */ { 0x0b5d, 0x0000, 99, 127 }, /* 097: p=0.061537 ( 1, 20) */ { 0x0034, 0x0000, 76, 72 }, /* 098: p=0.001102 ( 1208, 1) */ { 0x078a, 0x0000, 101, 125 }, /* 099: p=0.040815 ( 1, 31) */ { 0x00a0, 0x0000, 70, 102 }, /* 100: p=0.003387 ( 392, 1) */ { 0x050f, 0x0000, 103, 123 }, /* 101: p=0.027397 ( 1, 47) */ { 0x0117, 0x0000, 66, 60 }, /* 102: p=0.005912 ( 392, 2) */ { 0x0358, 0x0000, 105, 121 }, /* 103: p=0.018099 ( 1, 72) */ { 0x01ea, 0x0000, 106, 110 }, /* 104: p=0.010362 ( 127, 1) */ { 0x0234, 0x0000, 107, 119 }, /* 105: p=0.011940 ( 1, 110) */ { 0x0144, 0x0000, 66, 108 }, /* 106: p=0.006849 ( 193, 1) */ { 0x0173, 0x0000, 109, 117 }, /* 107: p=0.007858 ( 1, 168) */ { 0x0234, 0x0000, 60, 54 }, /* 108: p=0.011925 ( 193, 2) */ { 0x00f5, 0x0000, 111, 115 }, /* 109: p=0.005175 ( 1, 256) */ { 0x0353, 0x0000, 56, 48 }, /* 110: p=0.017995 ( 127, 2) */ { 0x00a1, 0x0000, 69, 113 }, /* 111: p=0.003413 ( 1, 389) */ { 0x05c5, 0x0000, 114, 134 }, /* 112: p=0.031249 ( 41, 1) */ { 0x011a, 0x0000, 65, 59 }, /* 113: p=0.005957 ( 2, 389) */ { 0x03cf, 0x0000, 116, 132 }, /* 114: p=0.020618 ( 63, 1) */ { 0x01aa, 0x0000, 61, 55 }, /* 115: p=0.009020 ( 2, 256) */ { 0x0285, 0x0000, 118, 130 }, /* 116: p=0.013652 ( 96, 1) */ { 0x0286, 0x0000, 57, 51 }, /* 117: p=0.013672 ( 2, 168) */ { 0x01ab, 0x0000, 120, 128 }, /* 118: p=0.009029 ( 146, 1) */ { 0x03d3, 0x0000, 53, 47 }, /* 119: p=0.020710 ( 2, 110) */ { 0x011a, 0x0000, 122, 126 }, /* 120: p=0.005961 ( 222, 1) */ { 0x05c5, 0x0000, 49, 41 }, /* 121: p=0.031250 ( 2, 72) */ { 0x00ba, 0x0000, 124, 62 }, /* 122: p=0.003925 ( 338, 1) */ { 0x08ad, 0x0000, 43, 37 }, /* 123: p=0.046979 ( 2, 47) */ { 0x007a, 0x0000, 72, 66 }, /* 124: p=0.002586 ( 514, 1) */ { 0x0ccc, 0x0000, 39, 31 }, /* 125: p=0.069306 ( 2, 31) */ { 0x01eb, 0x0000, 60, 54 }, /* 126: p=0.010386 ( 222, 2) */ { 0x1302, 0x0000, 33, 25 }, /* 127: p=0.102940 ( 2, 20) */ { 0x02e6, 0x0000, 56, 50 }, /* 128: p=0.015695 ( 146, 2) */ { 0x1b81, 0x0000, 29, 131 }, /* 129: p=0.148935 ( 2, 13) */ { 0x045e, 0x0000, 52, 46 }, /* 130: p=0.023648 ( 96, 2) */ { 0x24ef, 0x0000, 23, 17 }, /* 131: p=0.199999 ( 3, 13) */ { 0x0690, 0x0000, 48, 40 }, /* 132: p=0.035533 ( 63, 2) */ { 0x2865, 0x0000, 23, 15 }, /* 133: p=0.218748 ( 2, 8) */ { 0x09de, 0x0000, 42, 136 }, /* 134: p=0.053434 ( 41, 2) */ { 0x3987, 0x0000, 137, 7 }, /* 135: p=0.304346 ( 2, 5) */ { 0x0dc8, 0x0000, 38, 32 }, /* 136: p=0.074626 ( 41, 3) */ { 0x2c99, 0x0000, 21, 139 }, /* 137: p=0.241378 ( 2, 7) */ { 0x10ca, 0x0000, 140, 172 }, /* 138: p=0.090907 ( 13, 1) */ { 0x3b5f, 0x0000, 15, 9 }, /* 139: p=0.312499 ( 3, 7) */ { 0x0b5d, 0x0000, 142, 170 }, /* 140: p=0.061537 ( 20, 1) */ { 0x5695, 0x0000, 9, 85 }, /* 141: p=0.411764 ( 2, 3) */ { 0x078a, 0x0000, 144, 168 }, /* 142: p=0.040815 ( 31, 1) */ { 0x8000, 0x0000, 141, 248 }, /* 143: p=0.500000 ( 2, 2) */ { 0x050f, 0x0000, 146, 166 }, /* 144: p=0.027397 ( 47, 1) */ { 0x24ee, 0x0000, 147, 247 }, /* 145: p=0.199988 ( 0, 1) */ { 0x0358, 0x0000, 148, 164 }, /* 146: p=0.018099 ( 72, 1) */ { 0x0d30, 0x0000, 149, 197 }, /* 147: p=0.071422 ( 0, 4) */ { 0x0234, 0x0000, 150, 162 }, /* 148: p=0.011940 ( 110, 1) */ { 0x0481, 0x0000, 151, 95 }, /* 149: p=0.024388 ( 0, 13) */ { 0x0173, 0x0000, 152, 160 }, /* 150: p=0.007858 ( 168, 1) */ { 0x017a, 0x0000, 153, 173 }, /* 151: p=0.007999 ( 0, 41) */ { 0x00f5, 0x0000, 154, 158 }, /* 152: p=0.005175 ( 256, 1) */ { 0x007b, 0x0000, 155, 165 }, /* 153: p=0.002611 ( 0, 127) */ { 0x00a1, 0x0000, 70, 156 }, /* 154: p=0.003413 ( 389, 1) */ { 0x0028, 0x0000, 157, 161 }, /* 155: p=0.000849 ( 0, 392) */ { 0x011a, 0x0000, 66, 60 }, /* 156: p=0.005957 ( 389, 2) */ { 0x000d, 0x0000, 81, 159 }, /* 157: p=0.000276 ( 0, 1208) */ { 0x01aa, 0x0000, 62, 56 }, /* 158: p=0.009020 ( 256, 2) */ { 0x0034, 0x0000, 75, 71 }, /* 159: p=0.001102 ( 1, 1208) */ { 0x0286, 0x0000, 58, 52 }, /* 160: p=0.013672 ( 168, 2) */ { 0x00a0, 0x0000, 69, 163 }, /* 161: p=0.003387 ( 1, 392) */ { 0x03d3, 0x0000, 54, 48 }, /* 162: p=0.020710 ( 110, 2) */ { 0x0117, 0x0000, 65, 59 }, /* 163: p=0.005912 ( 2, 392) */ { 0x05c5, 0x0000, 50, 42 }, /* 164: p=0.031250 ( 72, 2) */ { 0x01ea, 0x0000, 167, 171 }, /* 165: p=0.010362 ( 1, 127) */ { 0x08ad, 0x0000, 44, 38 }, /* 166: p=0.046979 ( 47, 2) */ { 0x0144, 0x0000, 65, 169 }, /* 167: p=0.006849 ( 1, 193) */ { 0x0ccc, 0x0000, 40, 32 }, /* 168: p=0.069306 ( 31, 2) */ { 0x0234, 0x0000, 59, 53 }, /* 169: p=0.011925 ( 2, 193) */ { 0x1302, 0x0000, 34, 26 }, /* 170: p=0.102940 ( 20, 2) */ { 0x0353, 0x0000, 55, 47 }, /* 171: p=0.017995 ( 2, 127) */ { 0x1b81, 0x0000, 30, 174 }, /* 172: p=0.148935 ( 13, 2) */ { 0x05c5, 0x0000, 175, 193 }, /* 173: p=0.031249 ( 1, 41) */ { 0x24ef, 0x0000, 24, 18 }, /* 174: p=0.199999 ( 13, 3) */ { 0x03cf, 0x0000, 177, 191 }, /* 175: p=0.020618 ( 1, 63) */ { 0x2b74, 0x0000, 178, 222 }, /* 176: p=0.235291 ( 4, 1) */ { 0x0285, 0x0000, 179, 189 }, /* 177: p=0.013652 ( 1, 96) */ { 0x201d, 0x0000, 180, 218 }, /* 178: p=0.173910 ( 6, 1) */ { 0x01ab, 0x0000, 181, 187 }, /* 179: p=0.009029 ( 1, 146) */ { 0x1715, 0x0000, 182, 216 }, /* 180: p=0.124998 ( 9, 1) */ { 0x011a, 0x0000, 183, 185 }, /* 181: p=0.005961 ( 1, 222) */ { 0x0fb7, 0x0000, 184, 214 }, /* 182: p=0.085105 ( 14, 1) */ { 0x00ba, 0x0000, 69, 61 }, /* 183: p=0.003925 ( 1, 338) */ { 0x0a67, 0x0000, 186, 212 }, /* 184: p=0.056337 ( 22, 1) */ { 0x01eb, 0x0000, 59, 53 }, /* 185: p=0.010386 ( 2, 222) */ { 0x06e7, 0x0000, 188, 210 }, /* 186: p=0.037382 ( 34, 1) */ { 0x02e6, 0x0000, 55, 49 }, /* 187: p=0.015695 ( 2, 146) */ { 0x0496, 0x0000, 190, 208 }, /* 188: p=0.024844 ( 52, 1) */ { 0x045e, 0x0000, 51, 45 }, /* 189: p=0.023648 ( 2, 96) */ { 0x030d, 0x0000, 192, 206 }, /* 190: p=0.016529 ( 79, 1) */ { 0x0690, 0x0000, 47, 39 }, /* 191: p=0.035533 ( 2, 63) */ { 0x0206, 0x0000, 194, 204 }, /* 192: p=0.010959 ( 120, 1) */ { 0x09de, 0x0000, 41, 195 }, /* 193: p=0.053434 ( 2, 41) */ { 0x0155, 0x0000, 196, 202 }, /* 194: p=0.007220 ( 183, 1) */ { 0x0dc8, 0x0000, 37, 31 }, /* 195: p=0.074626 ( 3, 41) */ { 0x00e1, 0x0000, 198, 200 }, /* 196: p=0.004750 ( 279, 1) */ { 0x2b74, 0x0000, 199, 243 }, /* 197: p=0.235291 ( 1, 4) */ { 0x0094, 0x0000, 72, 64 }, /* 198: p=0.003132 ( 424, 1) */ { 0x201d, 0x0000, 201, 239 }, /* 199: p=0.173910 ( 1, 6) */ { 0x0188, 0x0000, 62, 56 }, /* 200: p=0.008284 ( 279, 2) */ { 0x1715, 0x0000, 203, 237 }, /* 201: p=0.124998 ( 1, 9) */ { 0x0252, 0x0000, 58, 52 }, /* 202: p=0.012567 ( 183, 2) */ { 0x0fb7, 0x0000, 205, 235 }, /* 203: p=0.085105 ( 1, 14) */ { 0x0383, 0x0000, 54, 48 }, /* 204: p=0.019021 ( 120, 2) */ { 0x0a67, 0x0000, 207, 233 }, /* 205: p=0.056337 ( 1, 22) */ { 0x0547, 0x0000, 50, 44 }, /* 206: p=0.028571 ( 79, 2) */ { 0x06e7, 0x0000, 209, 231 }, /* 207: p=0.037382 ( 1, 34) */ { 0x07e2, 0x0000, 46, 38 }, /* 208: p=0.042682 ( 52, 2) */ { 0x0496, 0x0000, 211, 229 }, /* 209: p=0.024844 ( 1, 52) */ { 0x0bc0, 0x0000, 40, 34 }, /* 210: p=0.063636 ( 34, 2) */ { 0x030d, 0x0000, 213, 227 }, /* 211: p=0.016529 ( 1, 79) */ { 0x1178, 0x0000, 36, 28 }, /* 212: p=0.094593 ( 22, 2) */ { 0x0206, 0x0000, 215, 225 }, /* 213: p=0.010959 ( 1, 120) */ { 0x19da, 0x0000, 30, 22 }, /* 214: p=0.139999 ( 14, 2) */ { 0x0155, 0x0000, 217, 223 }, /* 215: p=0.007220 ( 1, 183) */ { 0x24ef, 0x0000, 26, 16 }, /* 216: p=0.199998 ( 9, 2) */ { 0x00e1, 0x0000, 219, 221 }, /* 217: p=0.004750 ( 1, 279) */ { 0x320e, 0x0000, 20, 220 }, /* 218: p=0.269229 ( 6, 2) */ { 0x0094, 0x0000, 71, 63 }, /* 219: p=0.003132 ( 1, 424) */ { 0x432a, 0x0000, 14, 8 }, /* 220: p=0.344827 ( 6, 3) */ { 0x0188, 0x0000, 61, 55 }, /* 221: p=0.008284 ( 2, 279) */ { 0x447d, 0x0000, 14, 224 }, /* 222: p=0.349998 ( 4, 2) */ { 0x0252, 0x0000, 57, 51 }, /* 223: p=0.012567 ( 2, 183) */ { 0x5ece, 0x0000, 8, 2 }, /* 224: p=0.434782 ( 4, 3) */ { 0x0383, 0x0000, 53, 47 }, /* 225: p=0.019021 ( 2, 120) */ { 0x8000, 0x0000, 228, 87 }, /* 226: p=0.500000 ( 1, 1) */ { 0x0547, 0x0000, 49, 43 }, /* 227: p=0.028571 ( 2, 79) */ { 0x481a, 0x0000, 230, 246 }, /* 228: p=0.363634 ( 2, 1) */ { 0x07e2, 0x0000, 45, 37 }, /* 229: p=0.042682 ( 2, 52) */ { 0x3579, 0x0000, 232, 244 }, /* 230: p=0.285711 ( 3, 1) */ { 0x0bc0, 0x0000, 39, 33 }, /* 231: p=0.063636 ( 2, 34) */ { 0x24ef, 0x0000, 234, 238 }, /* 232: p=0.199997 ( 5, 1) */ { 0x1178, 0x0000, 35, 27 }, /* 233: p=0.094593 ( 2, 22) */ { 0x1978, 0x0000, 138, 236 }, /* 234: p=0.137929 ( 8, 1) */ { 0x19da, 0x0000, 29, 21 }, /* 235: p=0.139999 ( 2, 14) */ { 0x2865, 0x0000, 24, 16 }, /* 236: p=0.218748 ( 8, 2) */ { 0x24ef, 0x0000, 25, 15 }, /* 237: p=0.199998 ( 2, 9) */ { 0x3987, 0x0000, 240, 8 }, /* 238: p=0.304346 ( 5, 2) */ { 0x320e, 0x0000, 19, 241 }, /* 239: p=0.269229 ( 2, 6) */ { 0x2c99, 0x0000, 22, 242 }, /* 240: p=0.241378 ( 7, 2) */ { 0x432a, 0x0000, 13, 7 }, /* 241: p=0.344827 ( 3, 6) */ { 0x3b5f, 0x0000, 16, 10 }, /* 242: p=0.312499 ( 7, 3) */ { 0x447d, 0x0000, 13, 245 }, /* 243: p=0.349998 ( 2, 4) */ { 0x5695, 0x0000, 10, 2 }, /* 244: p=0.411764 ( 3, 2) */ { 0x5ece, 0x0000, 7, 1 }, /* 245: p=0.434782 ( 3, 4) */ { 0x8000, 0x0000, 244, 83 }, /* 246: p=0.500000 ( 2, 2) */ { 0x8000, 0x0000, 249, 250 }, /* 247: p=0.500000 ( 1, 1) */ { 0x5695, 0x0000, 10, 2 }, /* 248: p=0.411764 ( 3, 2) */ { 0x481a, 0x0000, 89, 143 }, /* 249: p=0.363634 ( 1, 2) */ { 0x481a, 0x0000, 230, 246 }, /* 250: p=0.363634 ( 2, 1) */ #endif #ifdef ZCODER /* This table has been designed for the ZCoder * by running the following command in file 'ztable2.sn': * (fast-crude (steady-mat 0.0035 0.0002) 260))) */ { 0x8000, 0x0000, 84, 139 }, /* 000: p=0.500000 ( 0, 0) */ { 0x8000, 0x0000, 3, 4 }, /* 001: p=0.500000 ( 0, 0) */ { 0x8000, 0x0000, 4, 3 }, /* 002: p=0.500000 ( 0, 0) */ { 0x7399, 0x10a5, 5, 1 }, /* 003: p=0.465226 ( 0, 0) */ { 0x7399, 0x10a5, 6, 2 }, /* 004: p=0.465226 ( 0, 0) */ { 0x6813, 0x1f28, 7, 3 }, /* 005: p=0.430708 ( 0, 0) */ { 0x6813, 0x1f28, 8, 4 }, /* 006: p=0.430708 ( 0, 0) */ { 0x5d65, 0x2bd3, 9, 5 }, /* 007: p=0.396718 ( 0, 0) */ { 0x5d65, 0x2bd3, 10, 6 }, /* 008: p=0.396718 ( 0, 0) */ { 0x5387, 0x36e3, 11, 7 }, /* 009: p=0.363535 ( 0, 0) */ { 0x5387, 0x36e3, 12, 8 }, /* 010: p=0.363535 ( 0, 0) */ { 0x4a73, 0x408c, 13, 9 }, /* 011: p=0.331418 ( 0, 0) */ { 0x4a73, 0x408c, 14, 10 }, /* 012: p=0.331418 ( 0, 0) */ { 0x421f, 0x48fe, 15, 11 }, /* 013: p=0.300562 ( 0, 0) */ { 0x421f, 0x48fe, 16, 12 }, /* 014: p=0.300562 ( 0, 0) */ { 0x3a85, 0x5060, 17, 13 }, /* 015: p=0.271166 ( 0, 0) */ { 0x3a85, 0x5060, 18, 14 }, /* 016: p=0.271166 ( 0, 0) */ { 0x339b, 0x56d3, 19, 15 }, /* 017: p=0.243389 ( 0, 0) */ { 0x339b, 0x56d3, 20, 16 }, /* 018: p=0.243389 ( 0, 0) */ { 0x2d59, 0x5c73, 21, 17 }, /* 019: p=0.217351 ( 0, 0) */ { 0x2d59, 0x5c73, 22, 18 }, /* 020: p=0.217351 ( 0, 0) */ { 0x27b3, 0x615e, 23, 19 }, /* 021: p=0.193091 ( 0, 0) */ { 0x27b3, 0x615e, 24, 20 }, /* 022: p=0.193091 ( 0, 0) */ { 0x22a1, 0x65a7, 25, 21 }, /* 023: p=0.170683 ( 0, 0) */ { 0x22a1, 0x65a7, 26, 22 }, /* 024: p=0.170683 ( 0, 0) */ { 0x1e19, 0x6963, 27, 23 }, /* 025: p=0.150134 ( 0, 0) */ { 0x1e19, 0x6963, 28, 24 }, /* 026: p=0.150134 ( 0, 0) */ { 0x1a0f, 0x6ca3, 29, 25 }, /* 027: p=0.131397 ( 0, 0) */ { 0x1a0f, 0x6ca3, 30, 26 }, /* 028: p=0.131397 ( 0, 0) */ { 0x167b, 0x6f75, 31, 27 }, /* 029: p=0.114441 ( 0, 0) */ { 0x167b, 0x6f75, 32, 28 }, /* 030: p=0.114441 ( 0, 0) */ { 0x1353, 0x71e6, 33, 29 }, /* 031: p=0.099214 ( 0, 0) */ { 0x1353, 0x71e6, 34, 30 }, /* 032: p=0.099214 ( 0, 0) */ { 0x108d, 0x7403, 35, 31 }, /* 033: p=0.085616 ( 0, 0) */ { 0x108d, 0x7403, 36, 32 }, /* 034: p=0.085616 ( 0, 0) */ { 0x0e1f, 0x75d7, 37, 33 }, /* 035: p=0.073525 ( 0, 0) */ { 0x0e1f, 0x75d7, 38, 34 }, /* 036: p=0.073525 ( 0, 0) */ { 0x0c01, 0x7769, 39, 35 }, /* 037: p=0.062871 ( 0, 0) */ { 0x0c01, 0x7769, 40, 36 }, /* 038: p=0.062871 ( 0, 0) */ { 0x0a2b, 0x78c2, 41, 37 }, /* 039: p=0.053524 ( 0, 0) */ { 0x0a2b, 0x78c2, 42, 38 }, /* 040: p=0.053524 ( 0, 0) */ { 0x0895, 0x79ea, 43, 39 }, /* 041: p=0.045374 ( 0, 0) */ { 0x0895, 0x79ea, 44, 40 }, /* 042: p=0.045374 ( 0, 0) */ { 0x0737, 0x7ae7, 45, 41 }, /* 043: p=0.038280 ( 0, 0) */ { 0x0737, 0x7ae7, 46, 42 }, /* 044: p=0.038280 ( 0, 0) */ { 0x060b, 0x7bbe, 47, 43 }, /* 045: p=0.032175 ( 0, 0) */ { 0x060b, 0x7bbe, 48, 44 }, /* 046: p=0.032175 ( 0, 0) */ { 0x050b, 0x7c75, 49, 45 }, /* 047: p=0.026926 ( 0, 0) */ { 0x050b, 0x7c75, 50, 46 }, /* 048: p=0.026926 ( 0, 0) */ { 0x0431, 0x7d10, 51, 47 }, /* 049: p=0.022430 ( 0, 0) */ { 0x0431, 0x7d10, 52, 48 }, /* 050: p=0.022430 ( 0, 0) */ { 0x0379, 0x7d92, 53, 49 }, /* 051: p=0.018623 ( 0, 0) */ { 0x0379, 0x7d92, 54, 50 }, /* 052: p=0.018623 ( 0, 0) */ { 0x02dd, 0x7dff, 55, 51 }, /* 053: p=0.015386 ( 0, 0) */ { 0x02dd, 0x7dff, 56, 52 }, /* 054: p=0.015386 ( 0, 0) */ { 0x025b, 0x7e5b, 57, 53 }, /* 055: p=0.012671 ( 0, 0) */ { 0x025b, 0x7e5b, 58, 54 }, /* 056: p=0.012671 ( 0, 0) */ { 0x01ef, 0x7ea7, 59, 55 }, /* 057: p=0.010414 ( 0, 0) */ { 0x01ef, 0x7ea7, 60, 56 }, /* 058: p=0.010414 ( 0, 0) */ { 0x0195, 0x7ee6, 61, 57 }, /* 059: p=0.008529 ( 0, 0) */ { 0x0195, 0x7ee6, 62, 58 }, /* 060: p=0.008529 ( 0, 0) */ { 0x0149, 0x7f1b, 63, 59 }, /* 061: p=0.006935 ( 0, 0) */ { 0x0149, 0x7f1b, 64, 60 }, /* 062: p=0.006935 ( 0, 0) */ { 0x010b, 0x7f46, 65, 61 }, /* 063: p=0.005631 ( 0, 0) */ { 0x010b, 0x7f46, 66, 62 }, /* 064: p=0.005631 ( 0, 0) */ { 0x00d5, 0x7f6c, 67, 63 }, /* 065: p=0.004495 ( 0, 0) */ { 0x00d5, 0x7f6c, 68, 64 }, /* 066: p=0.004495 ( 0, 0) */ { 0x00a5, 0x7f8d, 69, 65 }, /* 067: p=0.003484 ( 0, 0) */ { 0x00a5, 0x7f8d, 70, 66 }, /* 068: p=0.003484 ( 0, 0) */ { 0x007b, 0x7faa, 71, 67 }, /* 069: p=0.002592 ( 0, 0) */ { 0x007b, 0x7faa, 72, 68 }, /* 070: p=0.002592 ( 0, 0) */ { 0x0057, 0x7fc3, 73, 69 }, /* 071: p=0.001835 ( 0, 0) */ { 0x0057, 0x7fc3, 74, 70 }, /* 072: p=0.001835 ( 0, 0) */ { 0x0039, 0x7fd8, 75, 71 }, /* 073: p=0.001211 ( 0, 0) */ { 0x0039, 0x7fd8, 76, 72 }, /* 074: p=0.001211 ( 0, 0) */ { 0x0023, 0x7fe7, 77, 73 }, /* 075: p=0.000740 ( 0, 0) */ { 0x0023, 0x7fe7, 78, 74 }, /* 076: p=0.000740 ( 0, 0) */ { 0x0013, 0x7ff2, 79, 75 }, /* 077: p=0.000402 ( 0, 0) */ { 0x0013, 0x7ff2, 80, 76 }, /* 078: p=0.000402 ( 0, 0) */ { 0x0007, 0x7ffa, 81, 77 }, /* 079: p=0.000153 ( 0, 0) */ { 0x0007, 0x7ffa, 82, 78 }, /* 080: p=0.000153 ( 0, 0) */ { 0x0001, 0x7fff, 81, 79 }, /* 081: p=0.000027 ( 0, 0) */ { 0x0001, 0x7fff, 82, 80 }, /* 082: p=0.000027 ( 0, 0) */ { 0x620b, 0x0000, 9, 85 }, /* 083: p=0.411764 ( 2, 3) */ { 0x294a, 0x0000, 86, 216 }, /* 084: p=0.199988 ( 1, 0) */ { 0x8000, 0x0000, 5, 6 }, /* 085: p=0.500000 ( 3, 3) */ { 0x0db3, 0x0000, 88, 168 }, /* 086: p=0.071422 ( 4, 0) */ { 0x538e, 0x0000, 89, 137 }, /* 087: p=0.363634 ( 1, 2) */ { 0x0490, 0x0000, 90, 134 }, /* 088: p=0.024388 ( 13, 0) */ { 0x3e3e, 0x0000, 91, 135 }, /* 089: p=0.285711 ( 1, 3) */ { 0x017c, 0x0000, 92, 112 }, /* 090: p=0.007999 ( 41, 0) */ { 0x294a, 0x0000, 93, 133 }, /* 091: p=0.199997 ( 1, 5) */ { 0x007c, 0x0000, 94, 104 }, /* 092: p=0.002611 ( 127, 0) */ { 0x1b75, 0x0000, 95, 131 }, /* 093: p=0.137929 ( 1, 8) */ { 0x0028, 0x0000, 96, 100 }, /* 094: p=0.000849 ( 392, 0) */ { 0x12fc, 0x0000, 97, 129 }, /* 095: p=0.097559 ( 1, 12) */ { 0x000d, 0x0000, 82, 98 }, /* 096: p=0.000276 ( 1208, 0) */ { 0x0cfb, 0x0000, 99, 125 }, /* 097: p=0.067795 ( 1, 18) */ { 0x0034, 0x0000, 76, 72 }, /* 098: p=0.001102 ( 1208, 1) */ { 0x08cd, 0x0000, 101, 123 }, /* 099: p=0.046511 ( 1, 27) */ { 0x00a0, 0x0000, 70, 102 }, /* 100: p=0.003387 ( 392, 1) */ { 0x05de, 0x0000, 103, 119 }, /* 101: p=0.031249 ( 1, 41) */ { 0x0118, 0x0000, 66, 60 }, /* 102: p=0.005912 ( 392, 2) */ { 0x03e9, 0x0000, 105, 117 }, /* 103: p=0.020942 ( 1, 62) */ { 0x01ed, 0x0000, 106, 110 }, /* 104: p=0.010362 ( 127, 1) */ { 0x0298, 0x0000, 107, 115 }, /* 105: p=0.013937 ( 1, 94) */ { 0x0145, 0x0000, 66, 108 }, /* 106: p=0.006849 ( 193, 1) */ { 0x01b6, 0x0000, 109, 113 }, /* 107: p=0.009216 ( 1, 143) */ { 0x0237, 0x0000, 60, 54 }, /* 108: p=0.011925 ( 193, 2) */ { 0x0121, 0x0000, 65, 111 }, /* 109: p=0.006097 ( 1, 217) */ { 0x035b, 0x0000, 56, 48 }, /* 110: p=0.017995 ( 127, 2) */ { 0x01f9, 0x0000, 59, 53 }, /* 111: p=0.010622 ( 2, 217) */ { 0x05de, 0x0000, 114, 130 }, /* 112: p=0.031249 ( 41, 1) */ { 0x02fc, 0x0000, 55, 49 }, /* 113: p=0.016018 ( 2, 143) */ { 0x03e9, 0x0000, 116, 128 }, /* 114: p=0.020942 ( 62, 1) */ { 0x0484, 0x0000, 51, 45 }, /* 115: p=0.024138 ( 2, 94) */ { 0x0298, 0x0000, 118, 126 }, /* 116: p=0.013937 ( 94, 1) */ { 0x06ca, 0x0000, 47, 39 }, /* 117: p=0.036082 ( 2, 62) */ { 0x01b6, 0x0000, 120, 124 }, /* 118: p=0.009216 ( 143, 1) */ { 0x0a27, 0x0000, 41, 121 }, /* 119: p=0.053434 ( 2, 41) */ { 0x0121, 0x0000, 66, 122 }, /* 120: p=0.006097 ( 217, 1) */ { 0x0e57, 0x0000, 37, 31 }, /* 121: p=0.074626 ( 3, 41) */ { 0x01f9, 0x0000, 60, 54 }, /* 122: p=0.010622 ( 217, 2) */ { 0x0f25, 0x0000, 37, 29 }, /* 123: p=0.078651 ( 2, 27) */ { 0x02fc, 0x0000, 56, 50 }, /* 124: p=0.016018 ( 143, 2) */ { 0x1629, 0x0000, 33, 127 }, /* 125: p=0.112902 ( 2, 18) */ { 0x0484, 0x0000, 52, 46 }, /* 126: p=0.024138 ( 94, 2) */ { 0x1ee8, 0x0000, 27, 21 }, /* 127: p=0.153845 ( 3, 18) */ { 0x06ca, 0x0000, 48, 40 }, /* 128: p=0.036082 ( 62, 2) */ { 0x200f, 0x0000, 27, 19 }, /* 129: p=0.159089 ( 2, 12) */ { 0x0a27, 0x0000, 42, 132 }, /* 130: p=0.053434 ( 41, 2) */ { 0x2dae, 0x0000, 21, 15 }, /* 131: p=0.218748 ( 2, 8) */ { 0x0e57, 0x0000, 38, 32 }, /* 132: p=0.074626 ( 41, 3) */ { 0x4320, 0x0000, 15, 7 }, /* 133: p=0.304346 ( 2, 5) */ { 0x11a0, 0x0000, 136, 164 }, /* 134: p=0.090907 ( 13, 1) */ { 0x620b, 0x0000, 9, 85 }, /* 135: p=0.411764 ( 2, 3) */ { 0x0bbe, 0x0000, 138, 162 }, /* 136: p=0.061537 ( 20, 1) */ { 0x8000, 0x0000, 135, 248 }, /* 137: p=0.500000 ( 2, 2) */ { 0x07f3, 0x0000, 140, 160 }, /* 138: p=0.042104 ( 30, 1) */ { 0x294a, 0x0000, 141, 247 }, /* 139: p=0.199988 ( 0, 1) */ { 0x053e, 0x0000, 142, 158 }, /* 140: p=0.027971 ( 46, 1) */ { 0x0db3, 0x0000, 143, 199 }, /* 141: p=0.071422 ( 0, 4) */ { 0x0378, 0x0000, 144, 156 }, /* 142: p=0.018604 ( 70, 1) */ { 0x0490, 0x0000, 145, 167 }, /* 143: p=0.024388 ( 0, 13) */ { 0x024d, 0x0000, 146, 154 }, /* 144: p=0.012384 ( 106, 1) */ { 0x017c, 0x0000, 147, 101 }, /* 145: p=0.007999 ( 0, 41) */ { 0x0185, 0x0000, 148, 152 }, /* 146: p=0.008197 ( 161, 1) */ { 0x007c, 0x0000, 149, 159 }, /* 147: p=0.002611 ( 0, 127) */ { 0x0100, 0x0000, 68, 150 }, /* 148: p=0.005405 ( 245, 1) */ { 0x0028, 0x0000, 151, 155 }, /* 149: p=0.000849 ( 0, 392) */ { 0x01c0, 0x0000, 62, 56 }, /* 150: p=0.009421 ( 245, 2) */ { 0x000d, 0x0000, 81, 153 }, /* 151: p=0.000276 ( 0, 1208) */ { 0x02a7, 0x0000, 58, 52 }, /* 152: p=0.014256 ( 161, 2) */ { 0x0034, 0x0000, 75, 71 }, /* 153: p=0.001102 ( 1, 1208) */ { 0x0403, 0x0000, 54, 46 }, /* 154: p=0.021472 ( 106, 2) */ { 0x00a0, 0x0000, 69, 157 }, /* 155: p=0.003387 ( 1, 392) */ { 0x0608, 0x0000, 48, 42 }, /* 156: p=0.032110 ( 70, 2) */ { 0x0118, 0x0000, 65, 59 }, /* 157: p=0.005912 ( 2, 392) */ { 0x0915, 0x0000, 44, 38 }, /* 158: p=0.047945 ( 46, 2) */ { 0x01ed, 0x0000, 161, 165 }, /* 159: p=0.010362 ( 1, 127) */ { 0x0db4, 0x0000, 40, 32 }, /* 160: p=0.071428 ( 30, 2) */ { 0x0145, 0x0000, 65, 163 }, /* 161: p=0.006849 ( 1, 193) */ { 0x1417, 0x0000, 34, 26 }, /* 162: p=0.102940 ( 20, 2) */ { 0x0237, 0x0000, 59, 53 }, /* 163: p=0.011925 ( 2, 193) */ { 0x1dd6, 0x0000, 30, 166 }, /* 164: p=0.148935 ( 13, 2) */ { 0x035b, 0x0000, 55, 47 }, /* 165: p=0.017995 ( 2, 127) */ { 0x294a, 0x0000, 24, 18 }, /* 166: p=0.199999 ( 13, 3) */ { 0x11a0, 0x0000, 169, 195 }, /* 167: p=0.090907 ( 1, 13) */ { 0x31a3, 0x0000, 170, 212 }, /* 168: p=0.235291 ( 4, 1) */ { 0x0bbe, 0x0000, 171, 193 }, /* 169: p=0.061537 ( 1, 20) */ { 0x235a, 0x0000, 172, 208 }, /* 170: p=0.173910 ( 6, 1) */ { 0x07f3, 0x0000, 173, 191 }, /* 171: p=0.042104 ( 1, 30) */ { 0x18b3, 0x0000, 174, 206 }, /* 172: p=0.124998 ( 9, 1) */ { 0x053e, 0x0000, 175, 189 }, /* 173: p=0.027971 ( 1, 46) */ { 0x1073, 0x0000, 176, 204 }, /* 174: p=0.085105 ( 14, 1) */ { 0x0378, 0x0000, 177, 187 }, /* 175: p=0.018604 ( 1, 70) */ { 0x0b35, 0x0000, 178, 200 }, /* 176: p=0.058822 ( 21, 1) */ { 0x024d, 0x0000, 179, 185 }, /* 177: p=0.012384 ( 1, 106) */ { 0x0778, 0x0000, 180, 198 }, /* 178: p=0.039603 ( 32, 1) */ { 0x0185, 0x0000, 181, 183 }, /* 179: p=0.008197 ( 1, 161) */ { 0x04ed, 0x0000, 182, 194 }, /* 180: p=0.026315 ( 49, 1) */ { 0x0100, 0x0000, 67, 59 }, /* 181: p=0.005405 ( 1, 245) */ { 0x0349, 0x0000, 184, 192 }, /* 182: p=0.017621 ( 74, 1) */ { 0x02a7, 0x0000, 57, 51 }, /* 183: p=0.014256 ( 2, 161) */ { 0x022e, 0x0000, 186, 190 }, /* 184: p=0.011730 ( 112, 1) */ { 0x0403, 0x0000, 53, 45 }, /* 185: p=0.021472 ( 2, 106) */ { 0x0171, 0x0000, 64, 188 }, /* 186: p=0.007767 ( 170, 1) */ { 0x0608, 0x0000, 47, 41 }, /* 187: p=0.032110 ( 2, 70) */ { 0x0283, 0x0000, 58, 52 }, /* 188: p=0.013513 ( 170, 2) */ { 0x0915, 0x0000, 43, 37 }, /* 189: p=0.047945 ( 2, 46) */ { 0x03cc, 0x0000, 54, 48 }, /* 190: p=0.020349 ( 112, 2) */ { 0x0db4, 0x0000, 39, 31 }, /* 191: p=0.071428 ( 2, 30) */ { 0x05b6, 0x0000, 50, 42 }, /* 192: p=0.030434 ( 74, 2) */ { 0x1417, 0x0000, 33, 25 }, /* 193: p=0.102940 ( 2, 20) */ { 0x088a, 0x0000, 44, 196 }, /* 194: p=0.045161 ( 49, 2) */ { 0x1dd6, 0x0000, 29, 197 }, /* 195: p=0.148935 ( 2, 13) */ { 0x0c16, 0x0000, 40, 34 }, /* 196: p=0.063291 ( 49, 3) */ { 0x294a, 0x0000, 23, 17 }, /* 197: p=0.199999 ( 3, 13) */ { 0x0ce2, 0x0000, 40, 32 }, /* 198: p=0.067307 ( 32, 2) */ { 0x31a3, 0x0000, 201, 243 }, /* 199: p=0.235291 ( 1, 4) */ { 0x1332, 0x0000, 36, 202 }, /* 200: p=0.098590 ( 21, 2) */ { 0x235a, 0x0000, 203, 239 }, /* 201: p=0.173910 ( 1, 6) */ { 0x1adc, 0x0000, 30, 24 }, /* 202: p=0.135134 ( 21, 3) */ { 0x18b3, 0x0000, 205, 237 }, /* 203: p=0.124998 ( 1, 9) */ { 0x1be7, 0x0000, 30, 22 }, /* 204: p=0.139999 ( 14, 2) */ { 0x1073, 0x0000, 207, 235 }, /* 205: p=0.085105 ( 1, 14) */ { 0x294a, 0x0000, 26, 16 }, /* 206: p=0.199998 ( 9, 2) */ { 0x0b35, 0x0000, 209, 231 }, /* 207: p=0.058822 ( 1, 21) */ { 0x3a07, 0x0000, 20, 210 }, /* 208: p=0.269229 ( 6, 2) */ { 0x0778, 0x0000, 211, 229 }, /* 209: p=0.039603 ( 1, 32) */ { 0x4e30, 0x0000, 14, 8 }, /* 210: p=0.344827 ( 6, 3) */ { 0x04ed, 0x0000, 213, 225 }, /* 211: p=0.026315 ( 1, 49) */ { 0x4fa6, 0x0000, 14, 214 }, /* 212: p=0.349998 ( 4, 2) */ { 0x0349, 0x0000, 215, 223 }, /* 213: p=0.017621 ( 1, 74) */ { 0x6966, 0x0000, 8, 2 }, /* 214: p=0.434782 ( 4, 3) */ { 0x022e, 0x0000, 217, 221 }, /* 215: p=0.011730 ( 1, 112) */ { 0x8000, 0x0000, 218, 87 }, /* 216: p=0.500000 ( 1, 1) */ { 0x0171, 0x0000, 63, 219 }, /* 217: p=0.007767 ( 1, 170) */ { 0x538e, 0x0000, 220, 246 }, /* 218: p=0.363634 ( 2, 1) */ { 0x0283, 0x0000, 57, 51 }, /* 219: p=0.013513 ( 2, 170) */ { 0x3e3e, 0x0000, 222, 244 }, /* 220: p=0.285711 ( 3, 1) */ { 0x03cc, 0x0000, 53, 47 }, /* 221: p=0.020349 ( 2, 112) */ { 0x294a, 0x0000, 224, 242 }, /* 222: p=0.199997 ( 5, 1) */ { 0x05b6, 0x0000, 49, 41 }, /* 223: p=0.030434 ( 2, 74) */ { 0x1b75, 0x0000, 226, 240 }, /* 224: p=0.137929 ( 8, 1) */ { 0x088a, 0x0000, 43, 227 }, /* 225: p=0.045161 ( 2, 49) */ { 0x12fc, 0x0000, 228, 238 }, /* 226: p=0.097559 ( 12, 1) */ { 0x0c16, 0x0000, 39, 33 }, /* 227: p=0.063291 ( 3, 49) */ { 0x0cfb, 0x0000, 230, 234 }, /* 228: p=0.067795 ( 18, 1) */ { 0x0ce2, 0x0000, 39, 31 }, /* 229: p=0.067307 ( 2, 32) */ { 0x08cd, 0x0000, 112, 232 }, /* 230: p=0.046511 ( 27, 1) */ { 0x1332, 0x0000, 35, 233 }, /* 231: p=0.098590 ( 2, 21) */ { 0x0f25, 0x0000, 38, 30 }, /* 232: p=0.078651 ( 27, 2) */ { 0x1adc, 0x0000, 29, 23 }, /* 233: p=0.135134 ( 3, 21) */ { 0x1629, 0x0000, 34, 236 }, /* 234: p=0.112902 ( 18, 2) */ { 0x1be7, 0x0000, 29, 21 }, /* 235: p=0.139999 ( 2, 14) */ { 0x1ee8, 0x0000, 28, 22 }, /* 236: p=0.153845 ( 18, 3) */ { 0x294a, 0x0000, 25, 15 }, /* 237: p=0.199998 ( 2, 9) */ { 0x200f, 0x0000, 28, 20 }, /* 238: p=0.159089 ( 12, 2) */ { 0x3a07, 0x0000, 19, 241 }, /* 239: p=0.269229 ( 2, 6) */ { 0x2dae, 0x0000, 22, 16 }, /* 240: p=0.218748 ( 8, 2) */ { 0x4e30, 0x0000, 13, 7 }, /* 241: p=0.344827 ( 3, 6) */ { 0x4320, 0x0000, 16, 8 }, /* 242: p=0.304346 ( 5, 2) */ { 0x4fa6, 0x0000, 13, 245 }, /* 243: p=0.349998 ( 2, 4) */ { 0x620b, 0x0000, 10, 2 }, /* 244: p=0.411764 ( 3, 2) */ { 0x6966, 0x0000, 7, 1 }, /* 245: p=0.434782 ( 3, 4) */ { 0x8000, 0x0000, 244, 83 }, /* 246: p=0.500000 ( 2, 2) */ { 0x8000, 0x0000, 249, 250 }, /* 247: p=0.500000 ( 1, 1) */ { 0x620b, 0x0000, 10, 2 }, /* 248: p=0.411764 ( 3, 2) */ { 0x538e, 0x0000, 89, 137 }, /* 249: p=0.363634 ( 1, 2) */ { 0x538e, 0x0000, 220, 246 }, /* 250: p=0.363634 ( 2, 1) */ #endif }; //////////////////////////////////////////////////////////////// // CONSTRUCTOR/DESTRUCTOR //////////////////////////////////////////////////////////////// class ZPCodec::Encode : public ZPCodec { public: Encode(GP<ByteStream> gbs, const bool djvucompat); virtual ~Encode(); private: void init(void); }; ZPCodec::Encode::Encode(GP<ByteStream> gbs, const bool djvucompat) : ZPCodec(gbs,true,djvucompat) { init(); // Codebit counter #ifdef ZPCODEC_BITCOUNT bitcount = 0; #endif } ZPCodec::Encode::~Encode() { eflush(); } class ZPCodec::Decode : public ZPCodec { public: Decode(GP<ByteStream> gbs, const bool djvucompat); virtual ~Decode(); private: void init(void); }; ZPCodec::Decode::Decode(GP<ByteStream> gbs, const bool djvucompat) : ZPCodec(gbs,false,djvucompat) { init(); // Codebit counter #ifdef ZPCODEC_BITCOUNT bitcount = 0; #endif } ZPCodec::Decode::~Decode() {} ZPCodec::ZPCodec(GP<ByteStream> xgbs, const bool xencoding, const bool djvucompat) : gbs(xgbs), bs(xgbs), encoding(xencoding), fence(0), subend(0), buffer(0), nrun(0) { // Create machine independent ffz table for (int i=0; i<256; i++) { ffzt[i]=0; for (int j=i; j&0x80; j<<=1) ffzt[i] += 1; } // Initialize table newtable(default_ztable); // Patch table table (and lose DjVu compatibility). if (!djvucompat) { for (int j=0; j<256; j++) { unsigned short a = 0x10000-p[j]; while (a>=0x8000) a=(unsigned short)(a<<1); if (m[j]>0 && a+p[j]>=0x8000 && a>=m[j]) { BitContext x = default_ztable[j].dn; BitContext y = default_ztable[x].dn; dn[j] = y; } } } } ZPCodec::~ZPCodec() {} GP<ZPCodec> ZPCodec::create(GP<ByteStream> gbs, const bool encoding, const bool djvucompat) { GP<ZPCodec> retval; if(encoding) { retval=new ZPCodec::Encode(gbs,djvucompat); }else { retval=new ZPCodec::Decode(gbs,djvucompat); } return retval; } //////////////////////////////////////////////////////////////// // Z CODER DECODE ALGORITHM //////////////////////////////////////////////////////////////// void ZPCodec::Decode::init(void) { assert(sizeof(unsigned int)==4); assert(sizeof(unsigned short)==2); a = 0; /* Read first 16 bits of code */ if (! bs->read((void*)&byte, 1)) byte = 0xff; code = (byte<<8); if (! bs->read((void*)&byte, 1)) byte = 0xff; code = code | byte; /* Preload buffer */ delay = 25; scount = 0; preload(); /* Compute initial fence */ fence = code; if (code >= 0x8000) fence = 0x7fff; } void ZPCodec::preload(void) { while (scount<=24) { if (bs->read((void*)&byte, 1) < 1) { byte = 0xff; if (--delay < 1) G_THROW( ByteStream::EndOfFile ); } buffer = (buffer<<8) | byte; scount += 8; } } inline int ZPCodec::ffz(unsigned int x) { // DO NOT DEFINE FASTBSR : // Test shows that it hardly helps on a PPro, // and rumors are that BSR is very slow on PPlain. #if defined(FASTBSR) && defined(_MSC_VER) && defined(_M_IX86) int r; __asm { mov ebx, x xor ebx, 0xffff mov eax, -1 bsr eax, ebx mov r, eax } return 15 - r; #elif defined(FASTBSR) && defined(__GNUC__) && defined(__i386__) int r, dummy; __asm__ const ( "movl %2,%1\n\t" "xorl $0xffff, %1\n\t" "movl $-1, %0\n\t" "bsrl %1, %0" : "=&q" (r), "=q" (dummy) : "rm" (x) ); return 15 - r; #else return (x>=0xff00) ? (ffzt[x&0xff]+8) : (ffzt[(x>>8)&0xff]); #endif } int ZPCodec::decode_sub(BitContext &ctx, unsigned int z) { /* Save bit */ int bit = (ctx & 1); /* Avoid interval reversion */ #ifdef ZPCODER unsigned int d = 0x6000 + ((z+a)>>2); if (z > d) z = d; #endif #ifdef ZCODER if (z >= 0x8000) z = 0x4000 + (z>>1); #endif /* Test MPS/LPS */ if (z > code) { /* LPS branch */ z = 0x10000 - z; a = a + z; code = code + z; /* LPS adaptation */ ctx = dn[ctx]; /* LPS renormalization */ int shift = ffz(a); scount -= shift; a = (unsigned short)(a<<shift); code = (unsigned short)(code<<shift) | ((buffer>>scount) & ((1<<shift)-1)); #ifdef ZPCODEC_BITCOUNT bitcount += shift; #endif if (scount<16) preload(); /* Adjust fence */ fence = code; if (code >= 0x8000) fence = 0x7fff; return bit ^ 1; } else { /* MPS adaptation */ if (a >= m[ctx]) ctx = up[ctx]; /* MPS renormalization */ scount -= 1; a = (unsigned short)(z<<1); code = (unsigned short)(code<<1) | ((buffer>>scount) & 1); #ifdef ZPCODEC_BITCOUNT bitcount += 1; #endif if (scount<16) preload(); /* Adjust fence */ fence = code; if (code >= 0x8000) fence = 0x7fff; return bit; } } int ZPCodec::decode_sub_simple(int mps, unsigned int z) { /* Test MPS/LPS */ if (z > code) { /* LPS branch */ z = 0x10000 - z; a = a + z; code = code + z; /* LPS renormalization */ int shift = ffz(a); scount -= shift; a = (unsigned short)(a<<shift); code = (unsigned short)(code<<shift) | ((buffer>>scount) & ((1<<shift)-1)); #ifdef ZPCODEC_BITCOUNT bitcount += shift; #endif if (scount<16) preload(); /* Adjust fence */ fence = code; if (code >= 0x8000) fence = 0x7fff; return mps ^ 1; } else { /* MPS renormalization */ scount -= 1; a = (unsigned short)(z<<1); code = (unsigned short)(code<<1) | ((buffer>>scount) & 1); #ifdef ZPCODEC_BITCOUNT bitcount += 1; #endif if (scount<16) preload(); /* Adjust fence */ fence = code; if (code >= 0x8000) fence = 0x7fff; return mps; } } int ZPCodec::decode_sub_nolearn(int mps, unsigned int z) { #ifdef ZPCODER unsigned int d = 0x6000 + ((z+a)>>2); if (z > d) z = d; #endif #ifdef ZCODER if (z >= 0x8000) z = 0x4000 + (z>>1); #endif /* Test MPS/LPS */ if (z > code) { /* LPS branch */ z = 0x10000 - z; a = a + z; code = code + z; /* LPS renormalization */ int shift = ffz(a); scount -= shift; a = (unsigned short)(a<<shift); code = (unsigned short)(code<<shift) | ((buffer>>scount) & ((1<<shift)-1)); #ifdef ZPCODEC_BITCOUNT bitcount += shift; #endif if (scount<16) preload(); /* Adjust fence */ fence = code; if (code >= 0x8000) fence = 0x7fff; return mps ^ 1; } else { /* MPS renormalization */ scount -= 1; a = (unsigned short)(z<<1); code = (unsigned short)(code<<1) | ((buffer>>scount) & 1); #ifdef ZPCODEC_BITCOUNT bitcount += 1; #endif if (scount<16) preload(); /* Adjust fence */ fence = code; if (code >= 0x8000) fence = 0x7fff; return mps; } } //////////////////////////////////////////////////////////////// // Z CODER ENCODE ALGORITHM //////////////////////////////////////////////////////////////// void ZPCodec::Encode::init(void) { assert(sizeof(unsigned int)==4); assert(sizeof(unsigned short)==2); a = 0; scount = 0; byte = 0; delay = 25; subend = 0; buffer = 0xffffff; nrun = 0; } void ZPCodec::outbit(int bit) { if (delay > 0) { if (delay < 0xff) // delay=0xff suspends emission forever delay -= 1; } else { /* Insert a bit */ byte = (byte<<1) | bit; /* Output a byte */ if (++scount == 8) { if (!encoding) G_THROW( ERR_MSG("ZPCodec.no_encoding") ); if (bs->write((void*)&byte, 1) != 1) G_THROW( ERR_MSG("ZPCodec.write_error") ); scount = 0; byte = 0; } } } void ZPCodec::zemit(int b) { /* Shift new bit into 3bytes buffer */ buffer = (buffer<<1) + b; /* Examine bit going out of the 3bytes buffer */ b = (buffer >> 24); buffer = (buffer & 0xffffff); /* The following lines have been changed in order to emphazise the * similarity between this bit counting and the scheme of Witten, Neal & Cleary * (WN&C). Corresponding changes have been made in outbit and eflush. * Variable 'nrun' is similar to the 'bits_to_follow' in the W&N code. */ switch(b) { /* Similar to WN&C upper renormalization */ case 1: outbit(1); while (nrun-- > 0) outbit(0); nrun = 0; break; /* Similar to WN&C lower renormalization */ case 0xff: outbit(0); while (nrun-- > 0) outbit(1); nrun = 0; break; /* Similar to WN&C central renormalization */ case 0: nrun += 1; break; default: assert(0); } /* Code bit counter */ #ifdef ZPCODEC_BITCOUNT bitcount += 1; #endif } void ZPCodec::eflush() { /* adjust subend */ if (subend > 0x8000) subend = 0x10000; else if (subend > 0) subend = 0x8000; /* zemit many mps bits */ while (buffer != 0xffffff || subend ) { zemit(1 - (subend>>15) ); subend = (unsigned short)(subend<<1); } /* zemit pending run */ outbit(1); while (nrun-- > 0) outbit(0); nrun = 0; /* zemit 1 until full byte */ while (scount > 0) outbit(1); /* prevent further emission */ delay = 0xff; } void ZPCodec::encode_mps(BitContext &ctx, unsigned int z) { /* Avoid interval reversion */ #ifdef ZPCODER unsigned int d = 0x6000 + ((z+a)>>2); if (z > d) z = d; #endif #ifdef ZCODER if (z >= 0x8000) z = 0x4000 + (z>>1); #endif /* Adaptation */ if (a >= m[ctx]) ctx = up[ctx]; /* Code MPS */ a = z; /* Export bits */ if (a >= 0x8000) { zemit(1 - (subend>>15) ); subend = (unsigned short)(subend<<1); a = (unsigned short)(a<<1); } } void ZPCodec::encode_lps(BitContext &ctx, unsigned int z) { /* Avoid interval reversion */ #ifdef ZPCODER unsigned int d = 0x6000 + ((z+a)>>2); if (z > d) z = d; #endif #ifdef ZCODER if (z >= 0x8000) z = 0x4000 + (z>>1); #endif /* Adaptation */ ctx = dn[ctx]; /* Code LPS */ z = 0x10000 - z; subend += z; a += z; /* Export bits */ while (a >= 0x8000) { zemit(1 - (subend>>15) ); subend = (unsigned short)(subend<<1); a = (unsigned short)(a<<1); } } void ZPCodec::encode_mps_simple(unsigned int z) { /* Code MPS */ a = z; /* Export bits */ if (a >= 0x8000) { zemit(1 - (subend>>15) ); subend = (unsigned short)(subend<<1); a = (unsigned short)(a<<1); } } void ZPCodec::encode_lps_simple(unsigned int z) { /* Code LPS */ z = 0x10000 - z; subend += z; a += z; /* Export bits */ while (a >= 0x8000) { zemit(1 - (subend>>15) ); subend = (unsigned short)(subend<<1); a = (unsigned short)(a<<1); } } void ZPCodec::encode_mps_nolearn(unsigned int z) { #ifdef ZPCODER unsigned int d = 0x6000 + ((z+a)>>2); if (z > d) z = d; #endif #ifdef ZCODER if (z >= 0x8000) z = 0x4000 + (z>>1); #endif /* Code MPS */ a = z; /* Export bits */ if (a >= 0x8000) { zemit(1 - (subend>>15) ); subend = (unsigned short)(subend<<1); a = (unsigned short)(a<<1); } } void ZPCodec::encode_lps_nolearn(unsigned int z) { #ifdef ZPCODER unsigned int d = 0x6000 + ((z+a)>>2); if (z > d) z = d; #endif #ifdef ZCODER if (z >= 0x8000) z = 0x4000 + (z>>1); #endif /* Code LPS */ z = 0x10000 - z; subend += z; a += z; /* Export bits */ while (a >= 0x8000) { zemit(1 - (subend>>15) ); subend = (unsigned short)(subend<<1); a = (unsigned short)(a<<1); } } //////////////////////////////////////////////////////////////// // TABLE AND PARAMETER MANAGEMENT //////////////////////////////////////////////////////////////// void ZPCodec::newtable(ZPCodec::Table *table) { for (int i=0; i<256; i++) { p[i] = table[i].p; m[i] = table[i].m; up[i] = table[i].up; dn[i] = table[i].dn; } } static float p_to_plps(unsigned short p) { float fplps; float fp = (float)(p) / (float)(0x10000); const float log2 = (float)0.69314718055994530942; #ifdef ZCODER fplps = fp - (fp+0.5) * log(fp+0.5) + (fp-0.5)*log2; #endif #ifdef ZPCODER if (fp <= (1.0/6.0) ) fplps = fp * 2 * log2; else fplps = (float)((1.5*fp-0.25) - (1.5*fp+0.25)*log(1.5*fp+0.25) + (0.5*fp-0.25)*log2); #endif return fplps; } BitContext ZPCodec::state(float prob1) { // Return a state representing 'prob1' in the steady chain // FixMe: This is quite slow! int mps = (prob1 <= 0.5 ? 0 : 1); float plps = (float)(mps ? 1.0 - prob1 : prob1); // Locate steady chain (ordered, decreasing) int sz = 0; int lo = (mps ? 1 : 2); while (p[lo+sz+sz+2] < p[lo+sz+sz]) sz+=1; // Bisection while (sz > 1) { int nsz = sz >> 1; float nplps = p_to_plps( p[lo+nsz+nsz] ); if (nplps < plps) { sz=nsz; } else { lo=lo+nsz+nsz; sz=sz-nsz; } } // Choose closest one float f1 = p_to_plps(p[lo])-plps; float f2 = plps-p_to_plps(p[lo+2]); return (f1<f2) ? lo : lo+2; } #ifdef HAVE_NAMESPACES } # ifndef NOT_USING_DJVU_NAMESPACE using namespace DJVU; # endif #endif
/* * Copyright (c) 2019-2022, Adam Chyła <adam@chyla.org>. * All rights reserved. * * Distributed under the terms of the BSD 3-Clause License. */ #pragma once #include <string_view> namespace omtt::expectation::validation { struct PartialOutputCause { const std::string_view fExpectedPartialOutput; }; }
// Copyright 2003 The Trustees of Indiana University. // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Shared container iterator adaptor // Author: Ronald Garcia // See http://boost.org/libs/utility/shared_container_iterator.html // for documentation. // // shared_iterator_test.cpp - Regression tests for shared_container_iterator. // #include "boost/shared_container_iterator.hpp" #include "boost/shared_ptr.hpp" #include <vector> #include <cassert> struct resource { static int count; resource() { ++count; } resource(resource const&) { ++count; } ~resource() { --count; } }; int resource::count = 0; typedef std::vector<resource> resources_t; typedef boost::shared_container_iterator< resources_t > iterator; void set_range(iterator& i, iterator& end) { boost::shared_ptr< resources_t > objs(new resources_t()); for (int j = 0; j != 6; ++j) objs->push_back(resource()); i = iterator(objs->begin(),objs); end = iterator(objs->end(),objs); assert(resource::count == 6); } int main() { assert(resource::count == 0); { iterator i; { iterator end; set_range(i,end); assert(resource::count == 6); } assert(resource::count == 6); } assert(resource::count == 0); return 0; }
#include "left.h" #include "ui_left.h" #include "main.h" Left::Left(QWidget *parent) : QWidget(parent), ui(new Ui::Left) { ui->setupUi(this); } void Left::updateText(QString pos, QString text, QString inverted) { QString labelIdent = "label_"; labelIdent.append(pos); QLabel* label = this->findChild<QLabel*>(labelIdent); QString fullText = ""; if(label == NULL) return; if(inverted.compare("true") == 0) { fullText.append(INVERTED); } else { fullText.append(NOTINVERTED); } fullText.append(text); fullText.append(END); label->setText(fullText); } Left::~Left() { delete ui; }
#include "GameObject.hpp" #include <iostream> namespace mbgl { class TestObject : public GameObject { public: TestObject(std::string name) : GameObject(name) { d_LogIsButtonPressed.Bind(this, &TestObject::LogIsButtonPressed); } void OnCreate() override { data->inputManager.GetInputLayer(0).BindOnKeyDown(d_LogIsButtonPressed, sf::Keyboard::A); } void LogIsButtonPressed() { std::cout << data->inputManager.IsKeyDown(sf::Keyboard::H) << std::endl; } delegate<void(), TestObject> d_LogIsButtonPressed; }; }
/*! * Copyright (C) tkornuta, IBM Corporation 2015-2019 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! * \file DrawingUtils.cpp * \brief Definition of methods for drawing in OpenGL windows * \author tkornut * \date Dec 4, 2015 */ #include <stdio.h> #include <cmath> #include <cstring> #include <opengl/visualization/DrawingUtils.hpp> namespace mic { namespace opengl { namespace visualization { /*void DrawingUtils::display_image_roi(image* img, unsigned w, unsigned h, int x1, int y1, int x2, int y2, float r, float g, float b, float a) { if (img != NULL) { float scale_x = (float) w / (float) (img->width); float scale_y = (float) h / (float) (img->height); draw_rectangle((float) x1 * scale_x, (float) y1 * scale_y, (float) (x2 - x1) * scale_y, (float) (y2 - y1) * scale_x, r, g, b, a); } } void DrawingUtils::display_image(image* img, unsigned w, unsigned h, bool show_grid) { if (img != NULL && img->image_data != NULL) { float scale_x = (float) w / (float) (img->width); float scale_y = (float) h / (float) (img->height); for (unsigned x = 0; x < img->width; x++) { for (unsigned y = 0; y < img->height; y++) { if (img->type == BINARY) { uint8_t color = get_color(img, GRAY, y, x); draw_filled_rectangle((float) x * scale_x, float(y) * scale_y, scale_y, scale_x, (float) color / 255.0f, (float) color / 255.0f, (float) color / 255.0f, 1.0f); } else if (img->type == GRAYSCALE) { float color = get_color_float(img, GRAY, y, x); draw_filled_rectangle((float) x * scale_x, float(y) * scale_y, scale_y, scale_x, (float) color, (float) color, (float) color, 1.0f); } else if (img->type == RGBA) { uint8_t color_r = get_color(img, RED, y, x); uint8_t color_g = get_color(img, GREEN, y, x); uint8_t color_b = get_color(img, BLUE, y, x); uint8_t color_a = get_color(img, ALPHA, y, x); draw_filled_rectangle((float) x * scale_x, float(y) * scale_y, scale_y, scale_x, (float) color_r / 255.0f, (float) color_g / 255.0f, (float) color_b / 255.0f, (float) color_a / 255.0f); } } } if (show_grid) { glColor4f(0.8f, 0.0f, 0.0f, 0.5f); glBegin(GL_LINES); for (unsigned i = 0; i < w; i++) { glVertex2i((int) ((float) i * scale_x), 0); glVertex2i((int) ((float) i * scale_x), (GLint) h); } for (unsigned i = 0; i < h; i++) { glVertex2i(0, (int) ((float) i * scale_y)); glVertex2i((GLint) w, (int) ((float) i * scale_y)); } glEnd(); } } else { //CHECK(img != NULL && img->image_data != NULL); } }*/ void DrawingUtils::draw_frame(float x1, float y1, float x2, float y2, float r, float g, float b, float a) { glColor4f(r, g, b, a); glBegin(GL_LINE_STRIP); //margins, top frame glVertex2i((int) x1, (int) y1); glVertex2i((int) x1, (int) y2); glVertex2i((int) x2, (int) y2); glVertex2i((int) x2, (int) y1); glVertex2i((int) x1, (int) y1); glEnd(); } void DrawingUtils::draw_grid(float r, float g, float b, float a, float cells_h, float cells_v, float line_width_) { GLint h = glutGet(GLUT_WINDOW_HEIGHT); GLint w = glutGet(GLUT_WINDOW_WIDTH); float scale_x = (float) w / (float) (cells_h); float scale_y = (float) h / (float) (cells_v); glColor4f(r, g, b, a); glLineWidth(line_width_); glBegin(GL_LINES); for (unsigned i = 1; i < cells_h; i++) { glVertex2i((int) ((float) i * scale_x), 0); glVertex2i((int) ((float) i * scale_x), (GLint) h); } for (unsigned i = 1; i < cells_v; i++) { glVertex2i(0, (int) ((float) i * scale_y)); glVertex2i((GLint) w, (int) ((float) i * scale_y)); } glEnd(); } void DrawingUtils::draw_mark(mark m, float x, float y, float size, float line_width, float r, float g, float b, float a) { switch (m) { case CIRCLE: case ONE_CIRCLE: draw_circle(x, y, size, line_width, r, g, b, a); break; case PLUS: draw_plus(x, y, size, line_width, r, g, b, a); break; case CROSS: draw_cross(x, y, size, line_width, r, g, b, a); break; case SQUARE: draw_square(x, y, size, line_width, r, g, b, a); break; case NO_MARK: case NO_LINE: break; } } void DrawingUtils::draw_circle(float x, float y, float radius, float line_width, float r, float g, float b, float a) { glColor4f(r, g, b, a); glLineWidth(line_width); glBegin(GL_LINE_STRIP); for (float angle = 0.0f; angle <= 360.0f; angle += 30.0f) { glVertex2f((x + sinf((angle * (float) M_PI) / 180.0f) * radius), (y + cosf((angle * (float) M_PI) / 180.0f) * radius)); } glEnd(); } void DrawingUtils::draw_plus(float x, float y, float radius, float line_width, float r, float g, float b, float a) { glColor4f(r, g, b, a); glLineWidth(line_width); glBegin(GL_LINES); glVertex2i((int) x, (int) (y - radius)); glVertex2i((int) x, (int) (y + radius)); glVertex2i((int) (x - radius), (int) y); glVertex2i((int) (x + radius), (int) y); glEnd(); glLineWidth(1.0f); } void DrawingUtils::draw_cross(float x, float y, float radius, float line_width, float r, float g, float b, float a) { glColor4f(r, g, b, a); glLineWidth(line_width); glBegin(GL_LINES); glVertex2i((int) (x - radius), (int) (y - radius)); glVertex2i((int) (x + radius), (int) (y + radius)); glVertex2i((int) (x + radius), (int) (y - radius)); glVertex2i((int) (x - radius), (int) (y + radius)); glEnd(); } void DrawingUtils::draw_square(float x, float y, float radius, float line_width, float r, float g, float b, float a) { glColor4f(r, g, b, a); glLineWidth(line_width); glBegin(GL_LINE_STRIP); glVertex2i((int) (x - radius), (int) (y - radius)); glVertex2i((int) (x + radius), (int) (y - radius)); glVertex2i((int) (x + radius), (int) (y + radius)); glVertex2i((int) (x - radius), (int) (y + radius)); glVertex2i((int) (x - radius), (int) (y - radius)); glEnd(); } void DrawingUtils::draw_square_in_place(float radius, float line_width, float r, float g, float b, float a) { glColor4f(r, g, b, a); glLineWidth(line_width); glBegin(GL_LINE_STRIP); glNormal3f(0.0f, 0.0f, 1.0f); glVertex3f(-radius, -radius, 0.0f); glVertex3f(radius, -radius, 0.0f); glVertex3f(radius, radius, 0.0f); glVertex3f(-radius, radius, 0.0f); glVertex3f(-radius, -radius, 0.0f); glEnd(); } void DrawingUtils::draw_filled_square_in_place(float radius, float line_width, float r, float g, float b, float a) { glColor4f(r, g, b, a); glLineWidth(line_width); glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, 1.0f); glVertex3f(-radius, -radius, 0.0f); glVertex3f(radius, -radius, 0.0f); glVertex3f(radius, radius, 0.0f); glVertex3f(-radius, radius, 0.0f); glEnd(); } void DrawingUtils::draw_filled_rectangle_in_place(float radius_x, float radius_y, float line_width, float r, float g, float b, float a) { glColor4f(r, g, b, a); glLineWidth(line_width); glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, 1.0f); glVertex3f(-radius_x, -radius_y, 0.0f); glVertex3f(radius_x, -radius_y, 0.0f); glVertex3f(radius_x, radius_y, 0.0f); glVertex3f(-radius_x, radius_y, 0.0f); glEnd(); } void DrawingUtils::draw_cuboid(float radius, float line_width, float height, float r, float g, float b, float a) { glColor4f(r, g, b, a); glLineWidth(line_width); glBegin(GL_POLYGON); glNormal3f(0, 0, 1); glVertex3f(-radius, -radius, height); glVertex3f(radius, -radius, height); glVertex3f(radius, radius, height); glVertex3f(-radius, radius, height); glEnd(); glBegin(GL_POLYGON); glNormal3f(-1.0f, 0.0f, 0.0f); glVertex3f(-radius, -radius, 0.0f); glVertex3f(-radius, -radius, height); glVertex3f(-radius, radius, height); glVertex3f(-radius, radius, 0.0f); glEnd(); glBegin(GL_POLYGON); glNormal3f(1.0f, 0.0f, 0.0f); glVertex3f(radius, -radius, 0.0f); glVertex3f(radius, -radius, height); glVertex3f(radius, radius, height); glVertex3f(radius, radius, 0.0f); glEnd(); glBegin(GL_POLYGON); glNormal3f(0.0f, 1.0f, 0.0f); glVertex3f(-radius, radius, 0.0f); glVertex3f(-radius, radius, height); glVertex3f(radius, radius, height); glVertex3f(radius, radius, 0.0f); glEnd(); glBegin(GL_POLYGON); glNormal3f(0.0f, -1.0f, 0.0f); glVertex3f(-radius, -radius, 0.0f); glVertex3f(-radius, -radius, height); glVertex3f(radius, -radius, height); glVertex3f(radius, -radius, 0.0f); glEnd(); } void DrawingUtils::draw_texture_in_place(float radius) { glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-radius, -radius, 0.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(radius, -radius, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(radius, radius, 0.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-radius, radius, 0.0f); glEnd(); } void DrawingUtils::draw_filled_square(float x, float y, float radius, float r, float g, float b, float a) { draw_filled_rectangle(x, y, radius / 2.0f, radius / 2.0f, r, g, b, a); } void DrawingUtils::draw_filled_rectangle(float x, float y, float h, float w, float r, float g, float b, float a) { glColor4f(r, g, b, a); glBegin(GL_QUADS); //margins, top frame glVertex2i((int) (x), (int) (y)); glVertex2i((int) (x + w), (int) (y)); glVertex2i((int) (x + w), (int) (y + h)); glVertex2i((int) (x), (int) (y + h)); glEnd(); } void DrawingUtils::draw_rectangle(float x, float y, float h, float w, float r, float g, float b, float a) { glColor4f(r, g, b, a); glBegin(GL_LINE_STRIP); //margins, top frame glVertex2i((int) (x), (int) (y)); glVertex2i((int) (x + w), (int) (y)); glVertex2i((int) (x + w), (int) (y + h)); glVertex2i((int) (x), (int) (y + h)); glVertex2i((int) (x), (int) (y)); glEnd(); } void DrawingUtils::draw_text(float x, float y, char* string, float r, float g, float b, float a, void* font) { size_t len, i; glColor4f(r, g, b, a); glRasterPos2i((int) x, (int) y); len = (size_t) strlen(string); for (i = 0; i < len; i++) glutBitmapCharacter(font, string[i]); } void DrawingUtils::draw_text_3i(float x, float y, float z, char* string, float r, float g, float b, float a, void* font) { int len, i; glColor4f(r, g, b, a); glRasterPos3i((int) x, (int) y, (int) z); len = (int) strlen(string); for (i = 0; i < len; i++) glutBitmapCharacter(font, string[i]); } void DrawingUtils::draw_cursor(float x, float y, float r, float g, float b, float a) { char str[32]; sprintf(str, "[%.3f, %.3f]", x, y); draw_text(x, y, str, r, g, b, a, GLUT_BITMAP_HELVETICA_10); } float DrawingUtils::to_radians(float degrees) { return degrees * (float) (M_PI / 180.0f); } /*v_3f DrawingUtils::get_3d_position(int x, int y, float plane) { GLint viewport[4]; GLdouble modelview[16]; GLdouble projection[16]; GLfloat winX, winY, winZ; GLdouble posX, posY, posZ; v_3f point; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, viewport); winX = (float) x; winY = (float) viewport[3] - (float) y; glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ); gluUnProject(winX, winY, plane, modelview, projection, viewport, &posX, &posY, &posZ); point.x = (float) posX; point.y = (float) posY; point.z = (float) posZ; return point; }*/ } /* namespace visualization */ } /* namespace opengl */ } /* namespace mic */
// Clang Build Analyzer https://github.com/aras-p/ClangBuildAnalyzer // SPDX-License-Identifier: Unlicense #include "Utils.h" #ifdef _MSC_VER #define WIN32_LEAN_AND_MEAN struct IUnknown; // workaround for old Win SDK header failures when using /permissive- #include <windows.h> #else #include <unistd.h> #endif static std::string s_CurrentDir; static std::string s_Root = "./"; inline char ToLower(char c) { return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c; } inline char ToUpper(char c) { return (c >= 'a' && c <= 'z') ? (c - ('a' - 'A')) : c; } #ifdef _MSC_VER std::string WideToUtf(const std::wstring& s) { char path[1000] = { 0 }; ::WideCharToMultiByte(CP_UTF8, 0, s.data(), (int)s.size(), path, sizeof(path), NULL, NULL); return path; } #endif void utils::Initialize() { #ifdef _MSC_VER WCHAR buffer[1000] = { 0 }; GetCurrentDirectoryW(1000, buffer); s_CurrentDir = WideToUtf(buffer); #else char buffer[1000]; s_CurrentDir = getcwd(buffer, 1000); #endif ForwardSlashify(s_CurrentDir); if (!s_CurrentDir.empty()) { if (*s_CurrentDir.rbegin() != '/') s_CurrentDir += '/'; } } void utils::ForwardSlashify(std::string& path) { for (size_t i = 0, n = path.size(); i != n; ++i) if (path[i] == '\\') path[i] = '/'; } void utils::Lowercase(std::string& path) { for (size_t i = 0, n = path.size(); i != n; ++i) path[i] = ToLower(path[i]); } bool utils::BeginsWith(const std::string& str, const std::string& prefix) { if (str.size() < prefix.size()) return false; for (size_t i = 0, n = prefix.size(); i != n; ++i) { char c1 = ToLower(str[i]); char c2 = ToLower(prefix[i]); if (c1 != c2) return false; } return true; } bool utils::EndsWith(const std::string_view& str, const std::string& suffix) { if (str.size() < suffix.size()) return false; size_t start = str.size() - suffix.size(); for (size_t i = 0, n = suffix.size(); i != n; ++i) { char c1 = ToLower(str[i+start]); char c2 = ToLower(suffix[i]); if (c1 != c2) return false; } return true; } bool utils::IsHeader(const std::string_view& path) { size_t dot = path.rfind('.'); if (dot == std::string::npos) return true; // no extension is likely a header, e.g. <vector> size_t len = path.size(); if (dot + 1 < len && (ToLower(path[dot + 1]) == 'h' || ToLower(path[dot + 1]) == 'i')) return true; // extension starting with .h or .i (h, hpp, hxx, inc etc) likely a header return false; } static void makeSubstr(std::string& str, std::size_t pos = 0, std::size_t len = std::string::npos) { str.erase(0, pos); if(str.size() - len <= str.size()) { str.erase(len, str.size() - len); } } std::string utils::GetNicePath(const std::string_view& path) { std::string res(path); ForwardSlashify(res); if (BeginsWith(res, s_CurrentDir)) makeSubstr(res, s_CurrentDir.size(), res.size() - s_CurrentDir.size()); if (BeginsWith(res, s_Root)) makeSubstr(res, s_Root.size(), res.size() - s_Root.size()); return res; } std::string_view utils::GetFilename(const std::string_view& path) { size_t dirIdx = path.rfind('/'); if (dirIdx != std::string::npos) return path.substr(dirIdx + 1, path.size() - dirIdx - 1); return path; }
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1998-2010 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@zend.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/smart_allocator.h" #include "hphp/runtime/base/memory_manager.h" #include "hphp/runtime/base/resource_data.h" #include "hphp/runtime/server/server_stats.h" #include "hphp/runtime/base/runtime_option.h" #include "hphp/util/logger.h" #include "hphp/util/trace.h" /* * Enabling these will prevent us from allocating out of the free list * and cause deallocated objects to be filled with garbage. This is * intended for detecting data that is freed too eagerly. */ #if defined(SMART_ALLOCATOR_DEBUG_FREE) && !defined(DETECT_DOUBLE_FREE) # define DETECT_DOUBLE_FREE #endif namespace HPHP { TRACE_SET_MOD(smartalloc); /////////////////////////////////////////////////////////////////////////////// // initializer std::set<AllocatorThreadLocalInit>& GetAllocatorInitList() { static std::set<AllocatorThreadLocalInit> allocatorInitList; return allocatorInitList; } void InitAllocatorThreadLocal() { for (std::set<AllocatorThreadLocalInit>::iterator it = GetAllocatorInitList().begin(); it != GetAllocatorInitList().end(); it++) { (*it)(); } } /////////////////////////////////////////////////////////////////////////////// // constructor and destructor SmartAllocatorImpl::SmartAllocatorImpl(const std::type_info* typeId, uint itemSize) : m_itemSize(itemSizeRoundup(itemSize)) , m_typeId(typeId) { assert(itemSize > 0); MemoryManager::TheMemoryManager()->add(this); } /////////////////////////////////////////////////////////////////////////////// SmartAllocatorImpl::Iterator::Iterator(const SmartAllocatorImpl* sa) { next(); } void* SmartAllocatorImpl::Iterator::current() const { return 0; } void SmartAllocatorImpl::Iterator::next() { } /////////////////////////////////////////////////////////////////////////////// // ObjectAllocator classes ObjectAllocatorBase::ObjectAllocatorBase(int itemSize) : SmartAllocatorImpl(&typeid(ObjectData), itemSize) { } /////////////////////////////////////////////////////////////////////////////// }
// Copyright (c) 2014-2018, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <iostream> extern "C" { void cn_slow_hash(const void *data, size_t length, char *hash, int variant, int prehashed, uint64_t height) { throw std::runtime_error("Didn't expect cn_slow_hash to be called in stripped-down monero-core-custom"); } }
/**************************************************** * Template for coding contests * * Author : Sanjeev Sharma * * Email : thedevelopersanjeev@gmail.com * *****************************************************/ #pragma GCC optimize ("O3") #pragma GCC optimize("Ofast") #pragma GCC optimize ("unroll-loops") #pragma GCC optimize("no-stack-protector,fast-math") #pragma GCC target ("sse4") #pragma comment(linker, "/stack:200000000") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define deb(x) cout << #x << " is " << x << "\n"; #define int long long #define mod 1000000007 const double PI = 2 * acos(0.0); const long long INF = 1e18L + 5; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; void solve() { int n, k, d, x; cin >> n >> k; vector<bool> arr(n + 1, false); while (k--) { cin >> d; while (d--) { cin >> x; arr[x] = true; } } int ans = 0; for (int i = 1; i <= n; i++) { if (arr[i] == false) ans++; } cout << ans << "\n"; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
#include "taskparts/scheduler.hpp" #include "taskparts/stats.hpp" #include "taskparts/chaselev.hpp" #include "taskparts/machine.hpp" #include "taskparts/logging.hpp" #include "../example/fib_par.hpp" #include "../example/fib_nativefj.hpp" #include "../example/fib_oracleguided.hpp" #include <map> #include <stdio.h> #include <assert.h> namespace taskparts { class my_stats_configuration { public: static constexpr bool enabled = true; using counter_id_type = enum counter_id_enum { nb_fibers, nb_steals, nb_sleeps, nb_counters }; static const char* name_of_counter(counter_id_type id) { std::map<counter_id_type, const char*> names; names[nb_fibers] = "nb_fibers"; names[nb_steals] = "nb_steals"; names[nb_sleeps] = "nb_sleeps"; return names[id]; } }; using test_stats = stats_base<my_stats_configuration>; using my_logging = logging_base<true>; perworker::array<int> pwints; auto test1() -> bool { test_stats ts; minimal_worker mw; for (int i = 0; i < pwints.size(); i++) { pwints[i] = 123; } return true; } auto test_fib1() -> bool { int n = 40; int64_t dst; my_logging::initialize(false, true, false, true); using my_scheduler = minimal_scheduler<minimal_stats, my_logging>; auto f_body = new fib_par<my_scheduler>(n, &dst); auto f_term = new terminal_fiber<my_scheduler>; fiber<my_scheduler>::add_edge(f_body, f_term); f_body->release(); f_term->release(); chase_lev_work_stealing_scheduler<my_scheduler, fiber, minimal_stats, my_logging>::launch(); my_logging::output(); return (dst == fib_seq(n)); } auto test_fib2() -> bool { int64_t n = 40; int64_t dst; my_logging::initialize(false, true, false, true); using my_scheduler = minimal_scheduler<minimal_stats, my_logging>; nativefj_from_lambda f_body([&] { dst = fib_nativefj(n, my_scheduler()); printf("dst=%lu\n",dst); }, my_scheduler()); auto f_term = new terminal_fiber<my_scheduler>; fiber<my_scheduler>::add_edge(&f_body, f_term); f_body.release(); f_term->release(); chase_lev_work_stealing_scheduler<my_scheduler, fiber, minimal_stats, my_logging>::launch(); return (dst == fib_seq(n)); } auto test_fib3() -> bool { int n = 40; int64_t dst; using my_scheduler = minimal_scheduler<>; auto body = [&] { dst = fib_oracleguided(n); }; nativefj_from_lambda<decltype(body), my_scheduler> f_body(body); auto f_term = new terminal_fiber<my_scheduler>; fiber<my_scheduler>::add_edge(&f_body, f_term); f_body.release(); f_term->release(); chase_lev_work_stealing_scheduler<my_scheduler, fiber>::launch(); return (dst == fib_seq(n)); } } // end namespace int main() { //taskparts::test1(); //printf("fib1 %d\n", taskparts::test_fib1()); printf("fib2 %d\n", taskparts::test_fib2()); // taskparts::test_fib3(); return 0; }
/********************************************************************** * File: quspline.cpp (Formerly qspline.c) * Description: Code for the QSPLINE class. * Author: Ray Smith * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H # include "config_auto.h" #endif #include "quspline.h" #include "points.h" // for ICOORD #include "quadlsq.h" // for QLSQ #include "quadratc.h" // for QUAD_COEFFS #include <allheaders.h> // for pixRenderPolyline, pixGetDepth, pixGetHeight #include "pix.h" // for L_CLEAR_PIXELS, L_SET_PIXELS, Pix (ptr only) namespace tesseract { #define QSPLINE_PRECISION 16 // no of steps to draw /********************************************************************** * QSPLINE::QSPLINE * * Constructor to build a QSPLINE given the components used in the old code. **********************************************************************/ QSPLINE::QSPLINE( // constructor int32_t count, // no of segments int32_t *xstarts, // start coords double *coeffs // coefficients ) { int32_t index; // segment index // get memory xcoords = new int32_t[count + 1]; quadratics = new QUAD_COEFFS[count]; segments = count; for (index = 0; index < segments; index++) { // copy them xcoords[index] = xstarts[index]; quadratics[index] = QUAD_COEFFS(coeffs[index * 3], coeffs[index * 3 + 1], coeffs[index * 3 + 2]); } // right edge xcoords[index] = xstarts[index]; } /********************************************************************** * QSPLINE::QSPLINE * * Constructor to build a QSPLINE by appproximation of points. **********************************************************************/ QSPLINE::QSPLINE( // constructor int xstarts[], // spline boundaries int segcount, // no of segments int xpts[], // points to fit int ypts[], int pointcount, // no of pts int degree // fit required ) { int pointindex; /*no along text line */ int segment; /*segment no */ int32_t *ptcounts; // no in each segment QLSQ qlsq; /*accumulator */ segments = segcount; xcoords = new int32_t[segcount + 1]; ptcounts = new int32_t[segcount + 1]; quadratics = new QUAD_COEFFS[segcount]; memmove(xcoords, xstarts, (segcount + 1) * sizeof(int32_t)); ptcounts[0] = 0; /*none in any yet */ for (segment = 0, pointindex = 0; pointindex < pointcount; pointindex++) { while (segment < segcount && xpts[pointindex] >= xstarts[segment]) { segment++; /*try next segment */ /*cumulative counts */ ptcounts[segment] = ptcounts[segment - 1]; } ptcounts[segment]++; /*no in previous partition */ } while (segment < segcount) { segment++; /*zero the rest */ ptcounts[segment] = ptcounts[segment - 1]; } for (segment = 0; segment < segcount; segment++) { qlsq.clear(); /*first blob */ pointindex = ptcounts[segment]; if (pointindex > 0 && xpts[pointindex] != xpts[pointindex - 1] && xpts[pointindex] != xstarts[segment]) { qlsq.add(xstarts[segment], ypts[pointindex - 1] + (ypts[pointindex] - ypts[pointindex - 1]) * (xstarts[segment] - xpts[pointindex - 1]) / (xpts[pointindex] - xpts[pointindex - 1])); } for (; pointindex < ptcounts[segment + 1]; pointindex++) { qlsq.add(xpts[pointindex], ypts[pointindex]); } if (pointindex > 0 && pointindex < pointcount && xpts[pointindex] != xstarts[segment + 1]) { qlsq.add(xstarts[segment + 1], ypts[pointindex - 1] + (ypts[pointindex] - ypts[pointindex - 1]) * (xstarts[segment + 1] - xpts[pointindex - 1]) / (xpts[pointindex] - xpts[pointindex - 1])); } qlsq.fit(degree); quadratics[segment].a = qlsq.get_a(); quadratics[segment].b = qlsq.get_b(); quadratics[segment].c = qlsq.get_c(); } delete[] ptcounts; } /********************************************************************** * QSPLINE::QSPLINE * * Constructor to build a QSPLINE from another. **********************************************************************/ QSPLINE::QSPLINE( // constructor const QSPLINE &src) { segments = 0; xcoords = nullptr; quadratics = nullptr; *this = src; } /********************************************************************** * QSPLINE::~QSPLINE * * Destroy a QSPLINE. **********************************************************************/ QSPLINE::~QSPLINE() { delete[] xcoords; delete[] quadratics; } /********************************************************************** * QSPLINE::operator= * * Copy a QSPLINE **********************************************************************/ QSPLINE &QSPLINE::operator=( // assignment const QSPLINE &source) { delete[] xcoords; delete[] quadratics; segments = source.segments; xcoords = new int32_t[segments + 1]; quadratics = new QUAD_COEFFS[segments]; memmove(xcoords, source.xcoords, (segments + 1) * sizeof(int32_t)); memmove(quadratics, source.quadratics, segments * sizeof(QUAD_COEFFS)); return *this; } /********************************************************************** * QSPLINE::step * * Return the total of the step functions between the given coords. **********************************************************************/ double QSPLINE::step( // find step functions double x1, // between coords double x2) { int index1, index2; // indices of coords double total; /*total steps */ index1 = spline_index(x1); index2 = spline_index(x2); total = 0; while (index1 < index2) { total += static_cast<double>(quadratics[index1 + 1].y(static_cast<float>(xcoords[index1 + 1]))); total -= static_cast<double>(quadratics[index1].y(static_cast<float>(xcoords[index1 + 1]))); index1++; /*next segment */ } return total; /*total steps */ } /********************************************************************** * QSPLINE::y * * Return the y value at the given x value. **********************************************************************/ double QSPLINE::y( // evaluate double x // coord to evaluate at ) const { int32_t index; // segment index index = spline_index(x); return quadratics[index].y(x); // in correct segment } /********************************************************************** * QSPLINE::spline_index * * Return the index to the largest xcoord not greater than x. **********************************************************************/ int32_t QSPLINE::spline_index( // evaluate double x // coord to evaluate at ) const { int32_t index; // segment index int32_t bottom; // bottom of range int32_t top; // top of range bottom = 0; top = segments; while (top - bottom > 1) { index = (top + bottom) / 2; // centre of range if (x >= xcoords[index]) { bottom = index; // new min } else { top = index; // new max } } return bottom; } /********************************************************************** * QSPLINE::move * * Reposition spline by vector **********************************************************************/ void QSPLINE::move( // reposition spline ICOORD vec // by vector ) { int32_t segment; // index of segment int16_t x_shift = vec.x(); for (segment = 0; segment < segments; segment++) { xcoords[segment] += x_shift; quadratics[segment].move(vec); } xcoords[segment] += x_shift; } /********************************************************************** * QSPLINE::overlap * * Return true if spline2 overlaps this by no more than fraction less * than the bounds of this. **********************************************************************/ bool QSPLINE::overlap( // test overlap QSPLINE *spline2, // 2 cannot be smaller double fraction // by more than this ) { int leftlimit = xcoords[1]; /*common left limit */ int rightlimit = xcoords[segments - 1]; /*common right limit */ /*or too non-overlap */ return !(spline2->segments < 3 || spline2->xcoords[1] > leftlimit + fraction * (rightlimit - leftlimit) || spline2->xcoords[spline2->segments - 1] < rightlimit - fraction * (rightlimit - leftlimit)); } /********************************************************************** * extrapolate_spline * * Extrapolates the spline linearly using the same gradient as the * quadratic has at either end. **********************************************************************/ void QSPLINE::extrapolate( // linear extrapolation double gradient, // gradient to use int xmin, // new left edge int xmax // new right edge ) { int segment; /*current segment of spline */ int dest_segment; // dest index int32_t *xstarts; // new boundaries QUAD_COEFFS *quads; // new ones int increment; // in size increment = xmin < xcoords[0] ? 1 : 0; if (xmax > xcoords[segments]) { increment++; } if (increment == 0) { return; } xstarts = new int32_t[segments + 1 + increment]; quads = new QUAD_COEFFS[segments + increment]; if (xmin < xcoords[0]) { xstarts[0] = xmin; quads[0].a = 0; quads[0].b = gradient; quads[0].c = y(xcoords[0]) - quads[0].b * xcoords[0]; dest_segment = 1; } else { dest_segment = 0; } for (segment = 0; segment < segments; segment++) { xstarts[dest_segment] = xcoords[segment]; quads[dest_segment] = quadratics[segment]; dest_segment++; } xstarts[dest_segment] = xcoords[segment]; if (xmax > xcoords[segments]) { quads[dest_segment].a = 0; quads[dest_segment].b = gradient; quads[dest_segment].c = y(xcoords[segments]) - quads[dest_segment].b * xcoords[segments]; dest_segment++; xstarts[dest_segment] = xmax + 1; } segments = dest_segment; delete[] xcoords; delete[] quadratics; xcoords = xstarts; quadratics = quads; } /********************************************************************** * QSPLINE::plot * * Draw the QSPLINE in the given colour. **********************************************************************/ #ifndef GRAPHICS_DISABLED void QSPLINE::plot( // draw it ScrollView *window, // window to draw in ScrollView::Color colour // colour to draw in ) const { int32_t segment; // index of segment int16_t step; // index of poly piece double increment; // x increment double x; // x coord window->Pen(colour); for (segment = 0; segment < segments; segment++) { increment = static_cast<double>(xcoords[segment + 1] - xcoords[segment]) / QSPLINE_PRECISION; x = xcoords[segment]; for (step = 0; step <= QSPLINE_PRECISION; step++) { if (segment == 0 && step == 0) { window->SetCursor(x, quadratics[segment].y(x)); } else { window->DrawTo(x, quadratics[segment].y(x)); } x += increment; } } } #endif void QSPLINE::plot(Image pix) const { if (pix == nullptr) { return; } int32_t segment; // Index of segment int16_t step; // Index of poly piece double increment; // x increment double x; // x coord auto height = static_cast<double>(pixGetHeight(pix)); Pta *points = ptaCreate(QSPLINE_PRECISION * segments); const int kLineWidth = 5; for (segment = 0; segment < segments; segment++) { increment = static_cast<double>((xcoords[segment + 1] - xcoords[segment])) / QSPLINE_PRECISION; x = xcoords[segment]; for (step = 0; step <= QSPLINE_PRECISION; step++) { double y = height - quadratics[segment].y(x); ptaAddPt(points, x, y); x += increment; } } switch (pixGetDepth(pix)) { case 1: pixRenderPolyline(pix, points, kLineWidth, L_SET_PIXELS, 1); break; case 32: pixRenderPolylineArb(pix, points, kLineWidth, 255, 0, 0, 1); break; default: pixRenderPolyline(pix, points, kLineWidth, L_CLEAR_PIXELS, 1); break; } ptaDestroy(&points); } } // namespace tesseract
/*** * ==++== * * Copyright (c) Microsoft Corporation. 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. * * ==--== * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ * * Basic tests for PPLX task options. * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ****/ #include "stdafx.h" #if _MSC_VER >= 1800 // Dev12 doesn't have an in-box ambient scheduler, since all tasks execute on ConcRT. // Therefore, we need to provide one. A scheduler that directly executes a functor given to it is // a simple and valid implementation of a PPL scheduler class direct_executor : public pplx::scheduler_interface { public: virtual void schedule( concurrency::TaskProc_t proc, _In_ void* param) { proc(param); } }; static std::shared_ptr<pplx::scheduler_interface> g_executor; std::shared_ptr<pplx::scheduler_interface> __cdecl get_scheduler() { if ( !g_executor) { g_executor = std::make_shared<direct_executor>(); } return g_executor; } #else std::shared_ptr<pplx::scheduler_interface> __cdecl get_scheduler() { return pplx::get_ambient_scheduler(); } #endif class TaskOptionsTestScheduler : public pplx::scheduler_interface { public: TaskOptionsTestScheduler() : m_numTasks(0), m_scheduler(get_scheduler()) { } virtual void schedule(pplx::TaskProc_t proc, void* param) { pplx::details::atomic_increment(m_numTasks); m_scheduler->schedule(proc, param); } long get_num_tasks() { return m_numTasks; } private: pplx::details::atomic_long m_numTasks; pplx::scheduler_ptr m_scheduler; TaskOptionsTestScheduler(const TaskOptionsTestScheduler &); TaskOptionsTestScheduler & operator=(const TaskOptionsTestScheduler &); }; #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4512) #endif class CheckLifetimeScheduler : public pplx::scheduler_interface { public: CheckLifetimeScheduler(pplx::extensibility::event_t& ev) : m_event(ev), m_numTasks(0) { } ~CheckLifetimeScheduler() { m_event.set(); } virtual void schedule(pplx::TaskProc_t proc, void* param) { pplx::details::atomic_increment(m_numTasks); get_scheduler()->schedule(proc, param); } long get_num_tasks() { return m_numTasks; } pplx::extensibility::event_t& m_event; pplx::details::atomic_long m_numTasks; }; #if defined(_MSC_VER) #pragma warning(pop) #endif namespace tests { namespace functional { namespace PPLX { SUITE(pplx_task_options_tests) { TEST(voidtask_schedoption_test) { TaskOptionsTestScheduler sched; long n=0; auto t1 = pplx::create_task([&n]() {n++;}, sched); // run on sched t1.wait(); VERIFY_ARE_EQUAL(sched.get_num_tasks(), n); } TEST(task_schedoption_test) { TaskOptionsTestScheduler sched; long n=0; auto t1 = pplx::create_task([&n]() -> int {n++; return 1;}, sched); // run on sched t1.wait(); VERIFY_ARE_EQUAL(sched.get_num_tasks(), n); } TEST(then_nooptions_test) { TaskOptionsTestScheduler sched; long n=0; auto t1 = pplx::create_task([&n]() {n++;}, sched); t1.then([&n](){n++;}) // inherit sched .then([&n](){n++;}) .wait(); VERIFY_ARE_EQUAL(sched.get_num_tasks(), n); } TEST(then_multiple_schedulers_test1) { TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; auto emptyFunc = [](){}; auto t1 = pplx::create_task(emptyFunc, sched1); // sched1 t1.then(emptyFunc, sched2).wait(); // sched2 VERIFY_ARE_EQUAL(sched1.get_num_tasks(), 1); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 1); } TEST(then_multiple_schedulers_test2) { TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; auto emptyFunc = [](){}; auto t1 = pplx::create_task(emptyFunc, sched1); t1.then(emptyFunc, sched2) .then(emptyFunc) // inherit sched2 .wait(); VERIFY_ARE_EQUAL(sched1.get_num_tasks(), 1); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 2); } TEST(opand_nooptions_test) { TaskOptionsTestScheduler sched; auto t1 = pplx::create_task([]() {}, sched); auto t2 = pplx::create_task([]() {}, sched); auto t3 = t1 && t2; // Does not run on the scheduler - it should run inline t3.then([](){}, sched).wait(); // run on sched VERIFY_ARE_EQUAL(sched.get_num_tasks(), 3); } TEST(whenall_nooptions_test) { TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; std::vector<pplx::task<void>> taskVect; const int n = 10; for (int i = 0; i < n; i++) { taskVect.push_back(pplx::create_task([]() {}, sched1)); } auto t3 = pplx::when_all(begin(taskVect), end(taskVect)); // Does not run on the scheduler - it should run inline t3.then([](){}, sched2).wait(); // run on sched2 VERIFY_ARE_EQUAL(sched1.get_num_tasks(), n); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 1); } TEST(whenall_options_test1) { TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; std::vector<pplx::task<void>> taskVect; const int n = 10; for (int i = 0; i < n; i++) { taskVect.push_back(pplx::create_task([]() {}, sched1)); } auto t3 = pplx::when_all(begin(taskVect), end(taskVect), sched2); // Does not run on the scheduler - it should run inline t3.then([](){}).wait(); // run on sched2 (inherits from the when_all task VERIFY_ARE_EQUAL(sched1.get_num_tasks(), n); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 1); } TEST(whenall_options_test2) { // Same as the above test but use task<int> to instatinate those templates TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; std::vector<pplx::task<int>> taskVect; const int n = 10; for (int i = 0; i < n; i++) { taskVect.push_back(pplx::create_task([i]() ->int { return i;}, sched1)); } auto t3 = pplx::when_all(begin(taskVect), end(taskVect), sched2); // Does not run on the scheduler - it should run inline t3.then([](std::vector<int>){}).wait(); // run on sched2 (inherits from the when_all task VERIFY_ARE_EQUAL(sched1.get_num_tasks(), n); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 1); } TEST(whenall_options_test3) { // Same as the above test but use multiple when_all TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; std::vector<pplx::task<int>> taskVect; const int n = 10; for (int i = 0; i < n; i++) { taskVect.push_back(pplx::create_task([i]() ->int { return i;}, sched1)); } auto t2 = pplx::create_task([]()->int { return 0;}, sched1); auto t3 = pplx::when_all(begin(taskVect), end(taskVect), sched2); // Does not run on the scheduler - it should run inline auto t4 = t2 && t3; t4.then([](std::vector<int>){}).wait(); // run on default scheduler as the operator && breaks the chain of inheritance VERIFY_ARE_EQUAL(sched1.get_num_tasks(), n+1); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 0); } TEST(opor_nooptions_test) { TaskOptionsTestScheduler sched; auto t1 = pplx::create_task([]() {}, sched); auto t2 = pplx::create_task([]() {}, sched); auto t3 = t1 || t2; // Runs inline t3.then([](){}, sched).wait(); VERIFY_ARE_EQUAL(sched.get_num_tasks(), 3); } TEST(whenany_nooptions_test) { TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; std::vector<pplx::task<void>> taskVect; const int n = 10; for (int i = 0; i < n; i++) { taskVect.push_back(pplx::create_task([]() {}, sched1)); } auto t3 = pplx::when_any(begin(taskVect), end(taskVect)); // Does not run on the scheduler - it should run inline t3.then([](size_t){}, sched2).wait(); // run on sched2 // Do a whenall to wait for all the tasks pplx::when_all(begin(taskVect), end(taskVect)).wait(); VERIFY_ARE_EQUAL(sched1.get_num_tasks(), n); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 1); } TEST(whenany_options_test1) { TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; std::vector<pplx::task<void>> taskVect; const int n = 10; for (int i = 0; i < n; i++) { taskVect.push_back(pplx::create_task([]() {}, sched1)); } auto t3 = pplx::when_any(begin(taskVect), end(taskVect), sched2); // Does not run on the scheduler - it should run inline t3.then([](size_t){}).wait(); // run on sched2 (inherits from the when_all task // Do a whenall to wait for all the tasks pplx::when_all(begin(taskVect), end(taskVect)).wait(); VERIFY_ARE_EQUAL(sched1.get_num_tasks(), n); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 1); } TEST(whenany_options_test2) { // Same as whenany_options_test1 except that we instantiate a different set of template functions TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; std::vector<pplx::task<int>> taskVect; const int n = 10; for (int i = 0; i < n; i++) { taskVect.push_back(pplx::create_task([]() -> int {return 0;}, sched1)); } auto t3 = pplx::when_any(begin(taskVect), end(taskVect), sched2); // Does not run on the scheduler - it should run inline t3.then([](std::pair<int, size_t>){}).wait(); // run on sched2 (inherits from the when_all task // Do a whenall to wait for all the tasks pplx::when_all(begin(taskVect), end(taskVect)).wait(); VERIFY_ARE_EQUAL(sched1.get_num_tasks(), n); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 1); } TEST(tce_nooptions_test) { TaskOptionsTestScheduler sched; TaskOptionsTestScheduler sched1; TaskOptionsTestScheduler sched2; pplx::task_completion_event<void> tce; auto t1 = pplx::create_task(tce, sched1); auto t2 = pplx::create_task(tce, sched2); tce.set(); t1.wait(); t2.wait(); // There is nothing to execute VERIFY_ARE_EQUAL(sched1.get_num_tasks(), 0); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 0); auto emptyFunc = [](){}; auto t3 = t1.then(emptyFunc); auto t4 = t2.then(emptyFunc); t3.wait(); t4.wait(); VERIFY_ARE_EQUAL(sched1.get_num_tasks(), 1); VERIFY_ARE_EQUAL(sched2.get_num_tasks(), 1); } TEST(fromresult_options_test) { TaskOptionsTestScheduler sched; int value = 10; auto t1 = pplx::task_from_result(value); t1.wait(); VERIFY_ARE_EQUAL(sched.get_num_tasks(), 0); t1.then([](int i) -> int {return i;}, sched).wait(); VERIFY_ARE_EQUAL(sched.get_num_tasks(), 1); } TEST(scheduler_lifetime) { pplx::extensibility::event_t ev; { auto sched = std::make_shared<CheckLifetimeScheduler>(ev); pplx::create_task([]() {}, sched) // runs on sched (1) .then([](){}) // runs on sched (2) .wait(); VERIFY_ARE_EQUAL(sched->get_num_tasks(), 2); } ev.wait(); } TEST(scheduler_lifetime_mixed) { pplx::extensibility::event_t ev; auto t = pplx::create_task([](){}); // use default scheduler { auto sched = std::make_shared<CheckLifetimeScheduler>(ev); t.then([]() {}, sched) // (1) .then([](){}) // (2) .wait(); VERIFY_ARE_EQUAL(sched->get_num_tasks(), 2); } ev.wait(); } TEST(scheduler_lifetime_nested) { pplx::extensibility::event_t ev; auto t = pplx::create_task([](){}); // use default scheduler { auto sched = std::make_shared<CheckLifetimeScheduler>(ev); t.then([]() {}, sched) // custom scheduler (1) .then([sched]() { // We are on the default scheduler pplx::create_task([](){}, sched); // run on custom scheduler (2) }, t.scheduler()) .wait(); VERIFY_ARE_EQUAL(sched->get_num_tasks(), 2); } ev.wait(); } } // SUITE(pplx_task_options_tests) }}} // namespaces
/* * Created by * Shivani Bhardwaj <shivanib134@gmail.com> */ #include<iostream> using namespace std; long long Merge(long long * a, long long l, long long mid, long long n){ long long p=l,q=mid,i=0,c=0; long long tmp[n-l+1]; while(p<mid && q<=n){ if(a[p]<=a[q]) tmp[i++]=a[p++]; else{ tmp[i++]=a[q++]; c+=mid-p; } } while(p<mid) tmp[i++]=a[p++]; while(q<=n) tmp[i++]=a[q++]; long long j=0; while(l<=n) a[l++]=tmp[j++]; return c; } long long MergeSort(long long * a, long long b, long long n){ long long mid,c=0; if(b<n){ mid=(b+n)/2; c+=MergeSort(a,b,mid); c+=MergeSort(a,mid+1,n); c+=Merge(a,b,mid+1,n); } return c; } int main() { long long n; while(cin>>n && n!=0){ long long a[n]; for(int i=0;i<n;i++) cin>>a[i]; cout<<MergeSort(a,0,n-1)<<"\n"; //for(int i=0;i<n;i++) // cout<<a[i]<<" "; // cout<<"\n"; } }
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net) /// 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. /// /// @ref core /// @file glm/core/type_mat3x3.hpp /// @date 2005-01-27 / 2011-06-15 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// #ifndef glm_core_type_mat3x3 #define glm_core_type_mat3x3 #include "type_mat.hpp" namespace glm{ namespace detail { template <typename T> struct tvec1; template <typename T> struct tvec2; template <typename T> struct tvec3; template <typename T> struct tvec4; template <typename T> struct tmat2x2; template <typename T> struct tmat2x3; template <typename T> struct tmat2x4; template <typename T> struct tmat3x2; template <typename T> struct tmat3x3; template <typename T> struct tmat3x4; template <typename T> struct tmat4x2; template <typename T> struct tmat4x3; template <typename T> struct tmat4x4; template <typename T> struct tmat3x3 { enum ctor{null}; typedef T value_type; typedef std::size_t size_type; typedef tvec3<T> col_type; typedef tvec3<T> row_type; typedef tmat3x3<T> type; typedef tmat3x3<T> transpose_type; static GLM_FUNC_DECL size_type col_size(); static GLM_FUNC_DECL size_type row_size(); GLM_FUNC_DECL GLM_CONSTEXPR size_type length() const; public: /// Implementation detail /// @cond DETAIL GLM_FUNC_DECL tmat3x3<T> _inverse() const; /// @endcond private: // Data col_type value[3]; public: // Constructors GLM_FUNC_DECL tmat3x3(); GLM_FUNC_DECL tmat3x3(tmat3x3 const & m); GLM_FUNC_DECL explicit tmat3x3( ctor Null); GLM_FUNC_DECL explicit tmat3x3( value_type const & s); GLM_FUNC_DECL explicit tmat3x3( value_type const & x0, value_type const & y0, value_type const & z0, value_type const & x1, value_type const & y1, value_type const & z1, value_type const & x2, value_type const & y2, value_type const & z2); GLM_FUNC_DECL explicit tmat3x3( col_type const & v0, col_type const & v1, col_type const & v2); ////////////////////////////////////// // Conversions template <typename U> GLM_FUNC_DECL explicit tmat3x3( U const & x); template < typename X1, typename Y1, typename Z1, typename X2, typename Y2, typename Z2, typename X3, typename Y3, typename Z3 > GLM_FUNC_DECL explicit tmat3x3( X1 const & x1, Y1 const & y1, Z1 const & z1, X2 const & x2, Y2 const & y2, Z2 const & z2, X3 const & x3, Y3 const & y3, Z3 const & z3); template <typename V1, typename V2, typename V3> GLM_FUNC_DECL explicit tmat3x3( tvec3<V1> const & v1, tvec3<V2> const & v2, tvec3<V3> const & v3); // Matrix conversions template <typename U> GLM_FUNC_DECL explicit tmat3x3(tmat3x3<U> const & m); GLM_FUNC_DECL explicit tmat3x3(tmat2x2<T> const & x); GLM_FUNC_DECL explicit tmat3x3(tmat4x4<T> const & x); GLM_FUNC_DECL explicit tmat3x3(tmat2x3<T> const & x); GLM_FUNC_DECL explicit tmat3x3(tmat3x2<T> const & x); GLM_FUNC_DECL explicit tmat3x3(tmat2x4<T> const & x); GLM_FUNC_DECL explicit tmat3x3(tmat4x2<T> const & x); GLM_FUNC_DECL explicit tmat3x3(tmat3x4<T> const & x); GLM_FUNC_DECL explicit tmat3x3(tmat4x3<T> const & x); // Accesses GLM_FUNC_DECL col_type & operator[](size_type i); GLM_FUNC_DECL col_type const & operator[](size_type i) const; // Unary updatable operators GLM_FUNC_DECL tmat3x3<T>& operator= (tmat3x3<T> const & m); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator= (tmat3x3<U> const & m); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator+= (U const & s); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator+= (tmat3x3<U> const & m); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator-= (U const & s); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator-= (tmat3x3<U> const & m); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator*= (U const & s); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator*= (tmat3x3<U> const & m); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator/= (U const & s); template <typename U> GLM_FUNC_DECL tmat3x3<T>& operator/= (tmat3x3<U> const & m); GLM_FUNC_DECL tmat3x3<T>& operator++ (); GLM_FUNC_DECL tmat3x3<T>& operator-- (); }; // Binary operators template <typename T> GLM_FUNC_DECL tmat3x3<T> operator+ ( tmat3x3<T> const & m, typename tmat3x3<T>::value_type const & s); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator+ ( typename tmat3x3<T>::value_type const & s, tmat3x3<T> const & m); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator+ ( tmat3x3<T> const & m1, tmat3x3<T> const & m2); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator- ( tmat3x3<T> const & m, typename tmat3x3<T>::value_type const & s); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator- ( typename tmat3x3<T>::value_type const & s, tmat3x3<T> const & m); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator- ( tmat3x3<T> const & m1, tmat3x3<T> const & m2); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator* ( tmat3x3<T> const & m, typename tmat3x3<T>::value_type const & s); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator* ( typename tmat3x3<T>::value_type const & s, tmat3x3<T> const & m); template <typename T> GLM_FUNC_DECL typename tmat3x3<T>::col_type operator* ( tmat3x3<T> const & m, typename tmat3x3<T>::row_type const & v); template <typename T> GLM_FUNC_DECL typename tmat3x3<T>::row_type operator* ( typename tmat3x3<T>::col_type const & v, tmat3x3<T> const & m); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator* ( tmat3x3<T> const & m1, tmat3x3<T> const & m2); template <typename T> GLM_FUNC_DECL tmat2x3<T> operator* ( tmat3x3<T> const & m1, tmat2x3<T> const & m2); template <typename T> GLM_FUNC_DECL tmat4x3<T> operator* ( tmat3x3<T> const & m1, tmat4x3<T> const & m2); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator/ ( tmat3x3<T> const & m, typename tmat3x3<T>::value_type const & s); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator/ ( typename tmat3x3<T>::value_type const & s, tmat3x3<T> const & m); template <typename T> GLM_FUNC_DECL typename tmat3x3<T>::col_type operator/ ( tmat3x3<T> const & m, typename tmat3x3<T>::row_type const & v); template <typename T> GLM_FUNC_DECL typename tmat3x3<T>::row_type operator/ ( typename tmat3x3<T>::col_type const & v, tmat3x3<T> const & m); template <typename T> GLM_FUNC_DECL tmat3x3<T> operator/ ( tmat3x3<T> const & m1, tmat3x3<T> const & m2); // Unary constant operators template <typename T> GLM_FUNC_DECL tmat3x3<T> const operator- ( tmat3x3<T> const & m); template <typename T> GLM_FUNC_DECL tmat3x3<T> const operator-- ( tmat3x3<T> const & m, int); template <typename T> GLM_FUNC_DECL tmat3x3<T> const operator++ ( tmat3x3<T> const & m, int); } //namespace detail /// @addtogroup core_precision /// @{ /// 3 columns of 3 components matrix of low precision floating-point numbers. /// There is no guarantee on the actual precision. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef detail::tmat3x3<lowp_float> lowp_mat3; /// 3 columns of 3 components matrix of medium precision floating-point numbers. /// There is no guarantee on the actual precision. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef detail::tmat3x3<mediump_float> mediump_mat3; /// 3 columns of 3 components matrix of high precision floating-point numbers. /// There is no guarantee on the actual precision. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef detail::tmat3x3<highp_float> highp_mat3; /// 3 columns of 3 components matrix of low precision floating-point numbers. /// There is no guarantee on the actual precision. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef detail::tmat3x3<lowp_float> lowp_mat3x3; /// 3 columns of 3 components matrix of medium precision floating-point numbers. /// There is no guarantee on the actual precision. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef detail::tmat3x3<mediump_float> mediump_mat3x3; /// 3 columns of 3 components matrix of high precision floating-point numbers. /// There is no guarantee on the actual precision. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef detail::tmat3x3<highp_float> highp_mat3x3; /// @} }//namespace glm #ifndef GLM_EXTERNAL_TEMPLATE #include "type_mat3x3.inl" #endif #endif //glm_core_type_mat3x3
// Problem Statement // We are given a binary tree (with root node root), a target node, and an integer value K. // // Return a list of the values of all nodes that have a distance K from the // target node. The answer can be returned in any order. #include <bits/stdc++.h> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> distanceK(TreeNode* root, TreeNode* target, int K) { map<TreeNode *,vector<TreeNode*>> graph; createGraph(root,graph); return bfs(graph,target,K); } void createGraph(TreeNode *node,map<TreeNode *,vector<TreeNode*>> &graph){ if(!node) return; if(node->left){ graph[node->left].push_back(node); graph[node].push_back(node->left); createGraph(node->left,graph); } if(node->right){ graph[node->right].push_back(node); graph[node].push_back(node->right); createGraph(node->right,graph); } } vector<int> bfs(map<TreeNode*,vector<TreeNode*>> &graph, TreeNode* &target, int K){ vector<int> result; unordered_set<TreeNode*> visited; queue<TreeNode*> bfs_helper; bfs_helper.push(target); while(!bfs_helper.empty()){ if(K==0){ while(!bfs_helper.empty()){ TreeNode *vertex = bfs_helper.front(); bfs_helper.pop(); result.push_back(vertex->val); } break; } int tam = bfs_helper.size(); for(int i=0;i<tam;i++){ TreeNode* vertex = bfs_helper.front(); bfs_helper.pop(); if(visited.count(vertex)>0) continue; visited.insert(vertex); for(auto child : graph[vertex]){ if(visited.count(child)==0) bfs_helper.push(child); } } K--; } return result; } };
/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * @date 2015 * @author Manuel Wuthrich (manuel.wuthrich@gmail.com) * Max-Planck-Institute for Intelligent Systems */ #include <gtest/gtest.h> #include <Eigen/Core> #include <fl/util/math/linear_algebra.hpp> #include <fl/filter/particle/particle_filter.hpp> #include <fl/filter/gaussian/gaussian_filter_kf.hpp> #include <fl/model/sensor/linear_sensor.hpp> #include <fl/model/process/linear_transition.hpp> template<typename Vector, typename Matrix> bool moments_are_similar(Vector mean_a, Matrix cov_a, Vector mean_b, Matrix cov_b, double epsilon = 0.1) { Matrix cov_delta = cov_a.inverse() * cov_b; bool are_similar = cov_delta.isApprox(Matrix::Identity(), epsilon); Matrix square_root = fl::matrix_sqrt(cov_a); double max_mean_delta = (square_root.inverse() * (mean_a-mean_b)).cwiseAbs().maxCoeff(); are_similar = are_similar && max_mean_delta < epsilon; return are_similar; } Eigen::Matrix<double, 3, 3> some_rotation() { double angle = 2 * M_PI * double(rand()) / double(RAND_MAX); Eigen::Matrix<double, 3, 3> R = Eigen::Matrix<double, 3, 3>::Identity(); R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitX()); R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitZ()); R = R * Eigen::AngleAxisd(angle, Eigen::Vector3d::UnitY()); return R; } TEST(particle_filter, predict) { typedef Eigen::Matrix<double, 3, 1> State; typedef Eigen::Matrix<double, 3, 1> Observation; typedef Eigen::Matrix<double, 3, 1> Input; typedef Eigen::Matrix<double, 3, 3> Matrix; typedef fl::LinearGaussianProcessModel<State, Input> ProcessModel; typedef fl::LinearObservationModel<Observation, State> ObservationModel; // particle filter typedef fl::ParticleFilter<ProcessModel, ObservationModel> ParticleFilter; typedef ParticleFilter::Belief ParticleBelief; // gaussian filter typedef fl::GaussianFilter<ProcessModel, ObservationModel> GaussianFilter; typedef GaussianFilter::Belief GaussianBelief; srand(0); size_t N_particles = 10000; size_t N_steps = 10; size_t delta_time = 1; // create process model ProcessModel transition; { transition.A(some_rotation()); Matrix R = some_rotation(); Matrix D = Eigen::DiagonalMatrix<double, 3>(1, 3.5, 1.2); transition.covariance(R*D*R.transpose()); } // create observation model /// \todo this is a hack because the GF does not currently work with the new /// observation model interface ObservationModel sensor; { sensor.sensor_matrix(some_rotation()); Matrix R = some_rotation(); Matrix D = Eigen::DiagonalMatrix<double, 3>(3.1, 1.0, 1.3); D = D.cwiseSqrt(); sensor.noise_matrix(R*D); } // create filters ParticleFilter particle_filter(transition, sensor); GaussianFilter gaussian_filter(transition, sensor); // create intial beliefs GaussianBelief gaussian_belief; { gaussian_belief.mean(State::Zero()); gaussian_belief.covariance(Matrix::Identity()); } ParticleBelief particle_belief; particle_belief.from_distribution(gaussian_belief, N_particles); // run prediction for(size_t i = 0; i < N_steps; i++) { particle_filter.predict(delta_time, State::Zero(), particle_belief, particle_belief); gaussian_filter.predict(delta_time, State::Zero(), gaussian_belief, gaussian_belief); EXPECT_TRUE(moments_are_similar( particle_belief.mean(), particle_belief.covariance(), gaussian_belief.mean(), gaussian_belief.covariance())); } } TEST(particle_filter, update) { typedef Eigen::Matrix<double, 3, 1> State; typedef Eigen::Matrix<double, 3, 1> Observation; typedef Eigen::Matrix<double, 3, 1> Input; typedef Eigen::Matrix<double, 3, 3> Matrix; typedef fl::LinearGaussianProcessModel<State, Input> ProcessModel; typedef fl::LinearObservationModel<Observation, State> ObservationModel; // particle filter typedef fl::ParticleFilter<ProcessModel, ObservationModel> ParticleFilter; typedef ParticleFilter::Belief ParticleBelief; // gaussian filter typedef fl::GaussianFilter<ProcessModel, ObservationModel> GaussianFilter; typedef GaussianFilter::Belief GaussianBelief; srand(0); size_t N_particles = 10000; size_t N_steps = 10; // create process model ProcessModel transition; { transition.A(some_rotation()); Matrix R = some_rotation(); Matrix D = Eigen::DiagonalMatrix<double, 3>(1, 3.5, 1.2); transition.covariance(R*D*R.transpose()); } // create observation model /// \todo this is a hack because the GF does not currently work with the new /// observation model interface ObservationModel sensor; { sensor.sensor_matrix(some_rotation()); Matrix R = some_rotation(); Matrix D = Eigen::DiagonalMatrix<double, 3>(3.1, 1.0, 1.3); D = D.cwiseSqrt(); sensor.noise_matrix(R*D); } // create filters ParticleFilter particle_filter(transition, sensor); GaussianFilter gaussian_filter(transition, sensor); // create intial beliefs GaussianBelief gaussian_belief; { gaussian_belief.mean(State::Zero()); gaussian_belief.covariance(Matrix::Identity()); } ParticleBelief particle_belief; particle_belief.from_distribution(gaussian_belief, N_particles); // run prediction for(size_t i = 0; i < N_steps; i++) { Observation observation(0.5, 0.5, 0.5); particle_filter.update(observation, particle_belief, particle_belief); gaussian_filter.update(observation, gaussian_belief, gaussian_belief); EXPECT_TRUE(moments_are_similar( particle_belief.mean(), particle_belief.covariance(), gaussian_belief.mean(), gaussian_belief.covariance())); } } TEST(particle_filter, predict_and_update) { typedef Eigen::Matrix<double, 3, 1> State; typedef Eigen::Matrix<double, 3, 1> Observation; typedef Eigen::Matrix<double, 3, 1> Input; typedef Eigen::Matrix<double, 3, 3> Matrix; typedef fl::LinearGaussianProcessModel<State, Input> ProcessModel; typedef fl::LinearObservationModel<Observation, State> ObservationModel; // particle filter typedef fl::ParticleFilter<ProcessModel, ObservationModel> ParticleFilter; typedef ParticleFilter::Belief ParticleBelief; // gaussian filter typedef fl::GaussianFilter<ProcessModel, ObservationModel> GaussianFilter; typedef GaussianFilter::Belief GaussianBelief; srand(0); size_t N_particles = 10000; size_t N_steps = 10; size_t delta_time = 1; // create process model ProcessModel transition; { transition.A(some_rotation()); Matrix R = some_rotation(); Matrix D = Eigen::DiagonalMatrix<double, 3>(1, 3.5, 1.2); transition.covariance(R*D*R.transpose()); } // create observation model /// \todo this is a hack because the GF does not currently work with the new /// observation model interface ObservationModel sensor; { sensor.sensor_matrix(some_rotation()); Matrix R = some_rotation(); Matrix D = Eigen::DiagonalMatrix<double, 3>(3.1, 1.0, 1.3); D = D.cwiseSqrt(); sensor.noise_matrix(R*D); } // create filters ParticleFilter particle_filter(transition, sensor); GaussianFilter gaussian_filter(transition, sensor); // create intial beliefs GaussianBelief gaussian_belief; { gaussian_belief.mean(State::Zero()); gaussian_belief.covariance(Matrix::Identity()); } ParticleBelief particle_belief; particle_belief.from_distribution(gaussian_belief, N_particles); fl::StandardGaussian<State> standard_gaussian; State state = gaussian_belief.sample(); // run prediction for(size_t i = 0; i < N_steps; i++) { // simulate system state = transition.predict_state(delta_time, state, standard_gaussian.sample(), State::Zero()); Observation observation = sensor.observation(state, standard_gaussian.sample()); // predict particle_filter.predict(delta_time, State::Zero(), particle_belief, particle_belief); gaussian_filter.predict(delta_time, State::Zero(), gaussian_belief, gaussian_belief); // update particle_filter.update(observation, particle_belief, particle_belief); gaussian_filter.update(observation, gaussian_belief, gaussian_belief); } State delta = particle_belief.mean() - gaussian_belief.mean(); double mh_distance = delta.transpose() * gaussian_belief.precision() * delta; // make sure that the estimate of the pf is within one std dev EXPECT_TRUE(std::sqrt(mh_distance) <= 1.0); }
/** \file * Quantum kernel abstraction implementation. */ #include "kernel.h" #include <sstream> #include <algorithm> #include <iterator> #define K_PI 3.141592653589793238462643383279502884197169399375105820974944592307816406L #include "utils/json.h" #include "utils/str.h" #include "utils/vec.h" #include "options.h" #include "gate.h" #include "classical.h" #include "ir.h" #include "unitary.h" #include "platform.h" namespace ql { using namespace utils; quantum_kernel::quantum_kernel(const Str &name) : name(name), iterations(1), type(kernel_type_t::STATIC) { condition = cond_always; } quantum_kernel::quantum_kernel( const Str &name, const quantum_platform& platform, UInt qcount, UInt ccount, UInt bcount ) : name(name), iterations(1), qubit_count(qcount), creg_count(ccount), breg_count(bcount), type(kernel_type_t::STATIC) { instruction_map = platform.instruction_map; cycle_time = platform.cycle_time; cycles_valid = true; condition = cond_always; // FIXME: check qubit_count and creg_count against platform // FIXME: what is the reason we can specify qubit_count and creg_count here anyway } void quantum_kernel::set_condition(const operation &oper) { if ((oper.operands[0])->as_creg().id >= creg_count || (oper.operands[1]->as_creg().id >= creg_count)) { QL_EOUT("Out of range operand(s) for '" << oper.operation_name); throw Exception("Out of range operand(s) for '" + oper.operation_name + "' !", false); } if (oper.operation_type != operation_type_t::RELATIONAL) { QL_EOUT("Relational operator not used for conditional '" << oper.operation_name); throw Exception("Relational operator not used for conditional '" + oper.operation_name + "' !", false); } br_condition = oper; } void quantum_kernel::set_kernel_type(kernel_type_t typ) { type = typ; } Str quantum_kernel::get_gates_definition() const { StrStrm ss; for (auto i = instruction_map.begin(); i != instruction_map.end(); i++) { ss << i->first << std::endl; } return ss.str(); } Str quantum_kernel::get_name() const { return name; } circuit &quantum_kernel::get_circuit() { return c; } const circuit &quantum_kernel::get_circuit() const { return c; } void quantum_kernel::identity(UInt qubit) { gate("identity", qubit); } void quantum_kernel::i(UInt qubit) { gate("identity", qubit); } void quantum_kernel::hadamard(UInt qubit) { gate("hadamard", qubit); } void quantum_kernel::h(UInt qubit) { hadamard(qubit); } void quantum_kernel::rx(UInt qubit, Real angle) { c.push_back(new ql::rx(qubit,angle)); c.back()->condition = condition; c.back()->cond_operands = cond_operands;; cycles_valid = false; } void quantum_kernel::ry(UInt qubit, Real angle) { c.push_back(new ql::ry(qubit,angle)); c.back()->condition = condition; c.back()->cond_operands = cond_operands;; cycles_valid = false; } void quantum_kernel::rz(UInt qubit, Real angle) { c.push_back(new ql::rz(qubit,angle)); c.back()->condition = condition; c.back()->cond_operands = cond_operands;; cycles_valid = false; } void quantum_kernel::s(UInt qubit) { gate("s", qubit); } void quantum_kernel::sdag(UInt qubit) { gate("sdag", qubit); } void quantum_kernel::t(UInt qubit) { gate("t", qubit); } void quantum_kernel::tdag(UInt qubit) { gate("tdag", qubit); } void quantum_kernel::x(UInt qubit) { gate("x", qubit); } void quantum_kernel::y(UInt qubit) { gate("y", qubit); } void quantum_kernel::z(UInt qubit) { gate("z", qubit); } void quantum_kernel::rx90(UInt qubit) { gate("rx90", qubit); } void quantum_kernel::mrx90(UInt qubit) { gate("mrx90", qubit); } void quantum_kernel::rx180(UInt qubit) { gate("rx180", qubit); } void quantum_kernel::ry90(UInt qubit) { gate("ry90", qubit); } void quantum_kernel::mry90(UInt qubit) { gate("mry90", qubit); } void quantum_kernel::ry180(UInt qubit) { gate("ry180", qubit); } void quantum_kernel::measure(UInt qubit) { gate("measure", {qubit}, {}, 0, 0.0, {}); } void quantum_kernel::measure(UInt qubit, UInt bit) { gate("measure", {qubit}, {}, 0, 0.0, {bit}); } void quantum_kernel::prepz(UInt qubit) { gate("prepz", qubit); } void quantum_kernel::cnot(UInt qubit1, UInt qubit2) { gate("cnot", {qubit1, qubit2}); } void quantum_kernel::cz(UInt qubit1, UInt qubit2) { gate("cz", {qubit1, qubit2}); } void quantum_kernel::cphase(UInt qubit1, UInt qubit2) { gate("cphase", {qubit1, qubit2}); } void quantum_kernel::toffoli(UInt qubit1, UInt qubit2, UInt qubit3) { // TODO add custom gate check if needed c.push_back(new ql::toffoli(qubit1, qubit2, qubit3)); c.back()->condition = condition; c.back()->cond_operands = cond_operands;; cycles_valid = false; } void quantum_kernel::swap(UInt qubit1, UInt qubit2) { gate("swap", {qubit1, qubit2}); } void quantum_kernel::wait(const Vec<UInt> &qubits, UInt duration) { gate("wait", qubits, {}, duration); } void quantum_kernel::display() { c.push_back(new ql::display()); cycles_valid = false; } void quantum_kernel::clifford(Int id, UInt qubit) { switch (id) { case 0 : break; // ['I'] case 1 : ry90(qubit); rx90(qubit); break; // ['Y90', 'X90'] case 2 : mrx90(qubit); mry90(qubit); break; // ['mX90', 'mY90'] case 3 : rx180(qubit); break; // ['X180'] case 4 : mry90(qubit); mrx90(qubit); break; // ['mY90', 'mX90'] case 5 : rx90(qubit); mry90(qubit); break; // ['X90', 'mY90'] case 6 : ry180(qubit); break; // ['Y180'] case 7 : mry90(qubit); rx90(qubit); break; // ['mY90', 'X90'] case 8 : rx90(qubit); ry90(qubit); break; // ['X90', 'Y90'] case 9 : rx180(qubit); ry180(qubit); break; // ['X180', 'Y180'] case 10: ry90(qubit); mrx90(qubit); break; // ['Y90', 'mX90'] case 11: mrx90(qubit); ry90(qubit); break; // ['mX90', 'Y90'] case 12: ry90(qubit); rx180(qubit); break; // ['Y90', 'X180'] case 13: mrx90(qubit); break; // ['mX90'] case 14: rx90(qubit); mry90(qubit); mrx90(qubit); break; // ['X90', 'mY90', 'mX90'] case 15: mry90(qubit); break; // ['mY90'] case 16: rx90(qubit); break; // ['X90'] case 17: rx90(qubit); ry90(qubit); rx90(qubit); break; // ['X90', 'Y90', 'X90'] case 18: mry90(qubit); rx180(qubit); break; // ['mY90', 'X180'] case 19: rx90(qubit); ry180(qubit); break; // ['X90', 'Y180'] case 20: rx90(qubit); mry90(qubit); rx90(qubit); break; // ['X90', 'mY90', 'X90'] case 21: ry90(qubit); break; // ['Y90'] case 22: mrx90(qubit); ry180(qubit); break; // ['mX90', 'Y180'] case 23: rx90(qubit); ry90(qubit); mrx90(qubit); break; // ['X90', 'Y90', 'mX90'] default: break; } } Bool quantum_kernel::add_default_gate_if_available( const Str &gname, const Vec<UInt> &qubits, const Vec<UInt> &cregs, UInt duration, Real angle, const Vec<UInt> &bregs, cond_type_t gcond, const Vec<UInt> &gcondregs ) { Bool result = false; Bool is_one_qubit_gate = (gname == "identity") || (gname == "i") || (gname == "hadamard") || (gname == "h") || (gname == "pauli_x") || (gname == "pauli_y") || (gname == "pauli_z") || (gname == "x") || (gname == "y") || (gname == "z") || (gname == "s") || (gname == "sdag") || (gname == "t") || (gname == "tdag") || (gname == "rx") || (gname == "ry") || (gname == "rz") || (gname == "rx90") || (gname == "mrx90") || (gname == "rx180") || (gname == "ry90") || (gname == "mry90") || (gname == "ry180") || (gname == "measure") || (gname == "prepz"); Bool is_two_qubit_gate = (gname == "cnot") || (gname == "cz") || (gname == "cphase") || (gname == "swap"); Bool is_multi_qubit_gate = (gname == "toffoli") || (gname == "wait") || (gname == "barrier"); Bool is_non_conditional_gate = (gname == "wait") || (gname == "barrier"); if (is_one_qubit_gate) { if (qubits.size() != 1) { return false; } } else if (is_two_qubit_gate) { if (qubits.size() != 2) { return false; } if (qubits[0] == qubits[1]) { return false; } } else if (!is_multi_qubit_gate) { return false; } if (gname == "identity" || gname == "i") { c.push_back(new ql::identity(qubits[0])); result = true; } else if (gname == "hadamard" || gname == "h") { c.push_back(new ql::hadamard(qubits[0])); result = true; } else if (gname == "pauli_x" || gname == "x") { c.push_back(new pauli_x(qubits[0])); result = true; } else if( gname == "pauli_y" || gname == "y") { c.push_back(new pauli_y(qubits[0])); result = true; } else if (gname == "pauli_z" || gname == "z") { c.push_back(new pauli_z(qubits[0])); result = true; } else if (gname == "s" || gname == "phase") { c.push_back(new phase(qubits[0])); result = true; } else if (gname == "sdag" || gname == "phasedag") { c.push_back(new phasedag(qubits[0])); result = true; } else if (gname == "t") { c.push_back(new ql::t(qubits[0])); result = true; } else if (gname == "tdag") { c.push_back(new ql::tdag(qubits[0])); result = true; } else if (gname == "rx") { c.push_back(new ql::rx(qubits[0], angle)); result = true; } else if (gname == "ry") { c.push_back(new ql::ry(qubits[0], angle)); result = true; } else if( gname == "rz") { c.push_back(new ql::rz(qubits[0], angle)); result = true; } else if (gname == "rx90") { c.push_back(new ql::rx90(qubits[0])); result = true; } else if (gname == "mrx90") { c.push_back(new ql::mrx90(qubits[0])); result = true; } else if (gname == "rx180") { c.push_back(new ql::rx180(qubits[0])); result = true; } else if (gname == "ry90") { c.push_back(new ql::ry90(qubits[0])); result = true; } else if (gname == "mry90") { c.push_back(new ql::mry90(qubits[0])); result = true; } else if (gname == "ry180") { c.push_back(new ql::ry180(qubits[0])); result = true; } else if (gname == "measure") { if (cregs.empty()) { c.push_back(new ql::measure(qubits[0])); } else { c.push_back(new ql::measure(qubits[0], cregs[0])); } result = true; } else if (gname == "prepz") { c.push_back(new ql::prepz(qubits[0])); result = true; } else if (gname == "cnot") { c.push_back(new ql::cnot(qubits[0], qubits[1])); result = true; } else if (gname == "cz" || gname == "cphase") { c.push_back(new ql::cphase(qubits[0], qubits[1]) ); result = true; } else if (gname == "toffoli") { c.push_back(new ql::toffoli(qubits[0], qubits[1], qubits[2])); result = true; } else if (gname == "swap") { c.push_back(new ql::swap(qubits[0], qubits[1])); result = true; } else if (gname == "barrier") { /* wait/barrier is applied on the qubits specified as arguments. if no qubits are specified, then wait/barrier is applied on all qubits */ if (qubits.empty()) { Vec<UInt> all_qubits; for (UInt q = 0; q < qubit_count; q++) { all_qubits.push_back(q); } c.push_back(new ql::wait(all_qubits, 0, 0)); } else { c.push_back(new ql::wait(qubits, 0, 0)); } result = true; } else if (gname == "wait") { /* wait/barrier is applied on the qubits specified as arguments. if no qubits are specified, then wait/barrier is applied on all qubits */ UInt duration_in_cycles = ceil(static_cast<float>(duration) / cycle_time); if (qubits.empty()) { Vec<UInt> all_qubits; for (UInt q = 0; q < qubit_count; q++) { all_qubits.push_back(q); } c.push_back(new ql::wait(all_qubits, duration, duration_in_cycles)); } else { c.push_back(new ql::wait(qubits, duration, duration_in_cycles)); } result = true; } else { result = false; } if (result) { c.back()->breg_operands = bregs; if (gcond != cond_always && is_non_conditional_gate ) { QL_WOUT("Condition " << gcond << " on default gate '" << gname << "' specified while gate cannot be executed conditionally; condition will be ignored"); c.back()->condition = cond_always; c.back()->cond_operands = {}; } else { c.back()->condition = gcond; c.back()->cond_operands = gcondregs; } cycles_valid = false; } return result; } // if a specialized custom gate ("e.g. cz q0,q4") is available, add it to circuit and return true // if a parameterized custom gate ("e.g. cz") is available, add it to circuit and return true // // note that there is no check for the found gate being a composite gate Bool quantum_kernel::add_custom_gate_if_available( const Str &gname, const Vec<UInt> &qubits, const Vec<UInt> &cregs, UInt duration, Real angle, const Vec<UInt> &bregs, cond_type_t gcond, const Vec<UInt> &gcondregs ) { #if OPT_DECOMPOSE_WAIT_BARRIER // hack to skip wait/barrier if (gname=="wait" || gname=="barrier") { return false; // return, so a default gate will be attempted } #endif // construct canonical name Str instr = ""; for (auto qubit : qubits) { if (!instr.empty()) { instr += ","; } instr += "q" + to_string(qubit); } instr = gname + " " + instr; // first check if a specialized custom gate is available // a specialized custom gate is of the form: "cz q0 q3" instruction_map_t::iterator it = instruction_map.find(instr); if (it == instruction_map.end()) { it = instruction_map.find(gname); } if (it == instruction_map.end()) { QL_DOUT("custom gate not added for " << gname); return false; } custom_gate *g = new custom_gate(*(it->second)); for (auto qubit : qubits) { g->operands.push_back(qubit); } for (auto &cop : cregs) { g->creg_operands.push_back(cop); } for (auto &bop : bregs) { g->breg_operands.push_back(bop); } if (duration > 0) { g->duration = duration; } g->angle = angle; g->condition = gcond; g->cond_operands = gcondregs; c.push_back(g); QL_DOUT("custom gate added for " << gname); cycles_valid = false; return true; } // FIXME: move to class composite_gate? // return the subinstructions of a composite gate // while doing, test whether the subinstructions have a definition (so they cannot be specialized or default ones!) void quantum_kernel::get_decomposed_ins( const composite_gate *gptr, Vec<Str> &sub_instructions ) const { auto &sub_gates = gptr->gs; QL_DOUT("composite ins: " << gptr->name); for (auto &agate : sub_gates) { Str &sub_ins = agate->name; QL_DOUT(" sub ins: " << sub_ins); auto it = instruction_map.find(sub_ins); if (it != instruction_map.end()) { sub_instructions.push_back(sub_ins); } else { throw Exception("[x] error : kernel::gate() : gate decomposition not available for '" + sub_ins + "'' in the target platform !", false); } } } // if specialized composed gate: "e.g. cz q0,q3" available, with composition of subinstructions, return true // also check each subinstruction for presence of a custom_gate (or a default gate) // otherwise, return false // don't add anything to circuit // // add specialized decomposed gate, example JSON definition: "cl_14 q1": ["rx90 %0", "rym90 %0", "rxm90 %0"] Bool quantum_kernel::add_spec_decomposed_gate_if_available( const Str &gate_name, const Vec<UInt> &all_qubits, const Vec<UInt> &cregs, const Vec<UInt> &bregs, cond_type_t gcond, const Vec<UInt> &gcondregs ) { Bool added = false; QL_DOUT("Checking if specialized decomposition is available for " << gate_name); // construct canonical name Str instr_parameterized = ""; for (auto qubit : all_qubits) { if (!instr_parameterized.empty()) { instr_parameterized += ","; } instr_parameterized += "q" + to_string(qubit); } instr_parameterized = gate_name + " " + instr_parameterized; QL_DOUT("specialized instruction name: " << instr_parameterized); // find the name auto it = instruction_map.find(instr_parameterized); if (it != instruction_map.end()) { // check gate type QL_DOUT("specialized composite gate found for " << instr_parameterized); composite_gate * gptr = (composite_gate *)(it->second); if (gptr->type() == __composite_gate__) { QL_DOUT("composite gate type"); } else { QL_DOUT("not a composite gate type"); return false; } // perform decomposition Vec<Str> sub_instructions; get_decomposed_ins(gptr, sub_instructions); for (auto &sub_ins : sub_instructions) { // extract name and qubits QL_DOUT("Adding sub ins: " << sub_ins); std::replace(sub_ins.begin(), sub_ins.end(), ',', ' '); // FIXME: perform all conversions in sanitize_instruction_name() QL_DOUT(" after comma removal, sub ins: " << sub_ins); std::istringstream iss(sub_ins); Vec<Str> tokens{ std::istream_iterator<Str>{iss}, std::istream_iterator<Str>{} }; Vec<UInt> this_gate_qubits; Str &sub_ins_name = tokens[0]; for (UInt i = 1; i < tokens.size(); i++) { QL_DOUT("tokens[i] : " << tokens[i]); auto sub_str_token = tokens[i].substr(1); QL_DOUT("sub_str_token[i] : " << sub_str_token); this_gate_qubits.push_back(stoi(tokens[i].substr(1))); } QL_DOUT("actual qubits of this gate:" << this_gate_qubits); // custom gate check // when found, custom_added is true, and the expanded subinstruction was added to the circuit Bool custom_added = add_custom_gate_if_available(sub_ins_name, this_gate_qubits, cregs, 0, 0.0, bregs, gcond, gcondregs); if (!custom_added) { if (options::get("use_default_gates") == "yes") { // default gate check QL_DOUT("adding default gate for " << sub_ins_name); Bool default_available = add_default_gate_if_available(sub_ins_name, this_gate_qubits, cregs, 0, 0.0, bregs, gcond, gcondregs); if (default_available) { QL_DOUT("added default gate '" << sub_ins_name << "' with qubits " << this_gate_qubits); // // NB: changed WOUT to DOUT, since this is common for 'barrier', spamming log } else { QL_EOUT("unknown gate '" << sub_ins_name << "' with qubits " << this_gate_qubits); throw Exception("[x] error : kernel::gate() : the gate '" + sub_ins_name + "' with qubits " + to_string(this_gate_qubits) + " is not supported by the target platform !", false); } } else { QL_EOUT("unknown gate '" << sub_ins_name << "' with qubits " << this_gate_qubits); throw Exception("[x] error : kernel::gate() : the gate '" + sub_ins_name + "' with qubits " + to_string(this_gate_qubits) + " is not supported by the target platform !", false); } } } added = true; } else { QL_DOUT("composite gate not found for " << instr_parameterized); } return added; } // if composite gate: "e.g. cz %0 %1" available, return true; // also check each subinstruction for availability as a custom gate (or default gate) // if not, return false // don't add anything to circuit // // add parameterized decomposed gate, example JSON definition: "cl_14 %0": ["rx90 %0", "rym90 %0", "rxm90 %0"] Bool quantum_kernel::add_param_decomposed_gate_if_available( const Str &gate_name, const Vec<UInt> &all_qubits, const Vec<UInt> &cregs, const Vec<UInt> &bregs, cond_type_t gcond, const Vec<UInt> &gcondregs ) { Bool added = false; QL_DOUT("Checking if parameterized composite gate is available for " << gate_name); // construct instruction name from gate_name and actual qubit parameters Str instr_parameterized = ""; for (UInt i = 0; i < all_qubits.size(); i++) { if (!instr_parameterized.empty()) { instr_parameterized += ","; } instr_parameterized += "%" + to_string(i); } instr_parameterized = gate_name + " " + instr_parameterized; QL_DOUT("parameterized instruction name: " << instr_parameterized); // check for composite ins auto it = instruction_map.find(instr_parameterized); if (it != instruction_map.end()) { QL_DOUT("parameterized gate found for " << instr_parameterized); composite_gate * gptr = (composite_gate *)(it->second); if (gptr->type() == __composite_gate__) { QL_DOUT("composite gate type"); } else { QL_DOUT("Not a composite gate type"); return false; } Vec<Str> sub_instructions; get_decomposed_ins(gptr, sub_instructions); for (auto &sub_ins : sub_instructions) { QL_DOUT("Adding sub ins: " << sub_ins); std::replace( sub_ins.begin(), sub_ins.end(), ',', ' '); QL_DOUT(" after comma removal, sub ins: " << sub_ins); // tokenize sub_ins into sub_ins_name and this_gate_qubits // FIXME: similar code in add_spec_decomposed_gate_if_available() std::istringstream iss(sub_ins); Vec<Str> tokens{ std::istream_iterator<Str>{iss}, std::istream_iterator<Str>{} }; Vec<UInt> this_gate_qubits; Str & sub_ins_name = tokens[0]; for (UInt i = 1; i < tokens.size(); i++) { auto sub_str_token = tokens[i].substr(1); // example: tokens[i] equals "%1" -> sub_str_token equals "1" UInt qubit_idx = stoi(sub_str_token); if (qubit_idx >= all_qubits.size()) { QL_FATAL("Illegal qubit parameter index " << sub_str_token << " exceeds actual number of parameters given (" << all_qubits.size() << ") while adding sub ins '" << sub_ins << "' in parameterized instruction '" << instr_parameterized << "'"); } this_gate_qubits.push_back(all_qubits[qubit_idx]); } QL_DOUT("actual qubits of this gate: " << this_gate_qubits); // FIXME: following code block exists several times in this file // custom gate check // when found, custom_added is true, and the expanded subinstruction was added to the circuit Bool custom_added = add_custom_gate_if_available(sub_ins_name, this_gate_qubits, cregs, 0, 0.0, bregs, gcond, gcondregs); if (!custom_added) { if (options::get("use_default_gates") == "yes") { // default gate check QL_DOUT("adding default gate for " << sub_ins_name); Bool default_available = add_default_gate_if_available(sub_ins_name, this_gate_qubits, cregs, 0, 0.0, bregs, gcond, gcondregs); if (default_available) { QL_WOUT("added default gate '" << sub_ins_name << "' with qubits " << this_gate_qubits); } else { QL_EOUT("unknown gate '" << sub_ins_name << "' with qubits " << this_gate_qubits); throw Exception("[x] error : kernel::gate() : the gate '" + sub_ins_name + "' with qubits " + to_string(this_gate_qubits) + " is not supported by the target platform !", false); } } else { QL_EOUT("unknown gate '" << sub_ins_name << "' with qubits " << this_gate_qubits); throw Exception("[x] error : kernel::gate() : the gate '" + sub_ins_name + "' with qubits " + to_string(this_gate_qubits) + " is not supported by the target platform !", false); } } } added = true; } else { QL_DOUT("composite gate not found for " << instr_parameterized); } return added; } void quantum_kernel::gate(const Str &gname, UInt q0) { gate(gname, Vec<UInt> {q0}); } void quantum_kernel::gate(const Str &gname, UInt q0, UInt q1) { gate(gname, Vec<UInt> {q0, q1}); } /** * general user-level gate creation with any combination of operands * * check argument register indices against platform parameters; fail fatally if an index is out of range * add implicit arguments if absent (used when no register argument means all registers) * find matching gate in kernel's and platform's gate_definition (custom or default); when no match, fail * return the gate (or its decomposition) by appending it to kernel.c, the current kernel's circuit */ void quantum_kernel::gate( const Str &gname, const Vec<UInt> &qubits, const Vec<UInt> &cregs, UInt duration, Real angle, const Vec<UInt> &bregs, cond_type_t gcond, const Vec<UInt> &gcondregs ) { QL_DOUT("gate:" <<" gname=" << gname <<" qubits=" << qubits <<" cregs=" << cregs <<" duration=" << duration <<" angle=" << angle <<" bregs=" << bregs <<" gcond=" << gcond <<" gcondregs=" << gcondregs); for (auto &qno : qubits) { if (qno >= qubit_count) { QL_FATAL("Number of qubits in platform: " << to_string(qubit_count) << ", specified qubit numbers out of range for gate: '" << gname << "' with qubits " << qubits); } } for (auto &cno : cregs) { if (cno >= creg_count) { QL_FATAL("Out of range operand(s) for '" << gname << "' with cregs " << cregs); } } for (auto &bno : bregs) { if (bno >= breg_count) { QL_FATAL("Out of range operand(s) for '" << gname << "' with bregs " << bregs); } } if (!gate::is_valid_cond(gcond, gcondregs)) { QL_FATAL("Condition " << gcond << " of '" << gname << "' incompatible with gcondregs " << gcondregs); } for (auto &cbno : gcondregs) { if (cbno >= breg_count) { QL_FATAL("Out of range condition operand(s) for '" << gname << "' with gcondregs " << gcondregs); } } auto lqubits = qubits; auto lcregs = cregs; auto lbregs = bregs; gate_add_implicits(gname, lqubits, lcregs, duration, angle, lbregs, gcond, gcondregs); if (!gate_nonfatal(gname, lqubits, lcregs, duration, angle, lbregs, gcond, gcondregs)) { QL_FATAL("Unknown gate '" << gname << "' with qubits " << lqubits); } } /** * preset condition to make all future created gates conditional gates with this condition * preset ends when cleared: back to {cond_always, {}}; * useful in combination with higher-level gate creation interfaces * that don't support adding a condition for conditional execution */ void quantum_kernel::gate_preset_condition( cond_type_t gcond, const utils::Vec<utils::UInt> &gcondregs ) { if (!gate::is_valid_cond(gcond, gcondregs)) { QL_FATAL("Condition " << gcond << " of gate_preset_condition incompatible with gcondregs " << gcondregs); } QL_DOUT("Gate_preset_condition: setting condition=" << condition << " cond_operands=" << cond_operands); condition = gcond; cond_operands = gcondregs; } /** * clear preset condition again */ void quantum_kernel::gate_clear_condition() { gate_preset_condition(cond_always, {}); } /** * short-cut creation of conditional gate with only qubits as operands */ void quantum_kernel::condgate( const utils::Str &gname, const utils::Vec<utils::UInt> &qubits, cond_type_t gcond, const utils::Vec<utils::UInt> &gcondregs ) { gate(gname, qubits, {}, 0, 0.0, {}, gcond, gcondregs); } /** * conversion used by Python conditional execution interface */ ql::cond_type_t quantum_kernel::condstr2condvalue(const std::string &condstring) { ql::cond_type_t condvalue; if (condstring == "COND_ALWAYS") condvalue = ql::cond_always; else if (condstring == "COND_NEVER") condvalue = ql::cond_never; else if (condstring == "COND_UNARY") condvalue = ql::cond_unary; else if (condstring == "COND_NOT") condvalue = ql::cond_not; else if (condstring == "COND_AND") condvalue = ql::cond_and; else if (condstring == "COND_NAND") condvalue = ql::cond_nand; else if (condstring == "COND_OR") condvalue = ql::cond_or; else if (condstring == "COND_NOR") condvalue = ql::cond_nor; else if (condstring == "COND_XOR") condvalue = ql::cond_xor; else if (condstring == "COND_NXOR") condvalue = ql::cond_nxor; else { throw std::runtime_error("Error: Unknown condition " + condstring); } return condvalue; } /** * add implicit parameters to gate to match IR requirements */ void quantum_kernel::gate_add_implicits( const Str &gname, Vec<UInt> &qubits, Vec<UInt> &cregs, UInt &duration, Real &angle, Vec<UInt> &bregs, cond_type_t &gcond, const Vec<UInt> &gcondregs ) { if (gname == "measure" || gname == "measx" || gname == "measz") { QL_DOUT("gate_add_implicits:" <<" gname=" << gname <<" qubits=" << qubits <<" cregs=" << cregs <<" duration=" << duration <<" angle=" << angle <<" bregs=" << bregs <<" gcond=" << gcond <<" gcondregs=" << gcondregs); if (bregs.size() == 0 && qubits[0] < breg_count) { bregs.push_back(qubits[0]); } QL_DOUT("gate_add_implicits (after):" <<" gname=" << gname <<" qubits=" << qubits <<" cregs=" << cregs <<" duration=" << duration <<" angle=" << angle <<" bregs=" << bregs <<" gcond=" << gcond <<" gcondregs=" << gcondregs); } } /** * custom gate with arbitrary number of operands * as gate above but return whether gate was successfully matched in gate_definition, next to gate in kernel.c */ Bool quantum_kernel::gate_nonfatal( const Str &gname, const Vec<UInt> &qubits, const Vec<UInt> &cregs, UInt duration, Real angle, const Vec<UInt> &bregs, cond_type_t gcond, const Vec<UInt> &gcondregs ) { Vec<UInt> lcondregs = gcondregs; // check and impose kernel's preset condition if any if (condition != cond_always && ( condition != gcond || cond_operands != gcondregs)) { // a non-trivial condition, different from the current condition argument (gcond/gcondregs), // was preset in the kernel to be imposed on all subsequently created gates // if the condition argument is also non-trivial, there is a clash (but we could also take the intersection) if (gcond != cond_always) { QL_FATAL("Condition " << gcond << " for '" << gname << "' specified while a different non-trivial condition was already preset"); } // impose kernel's preset condition gcond = condition; lcondregs = cond_operands; } Bool added = false; // check if specialized composite gate is available // if not, check if parameterized composite gate is available // if not, check if a specialized custom gate is available // if not, check if a parameterized custom gate is available // if not, check if a default gate is available // if not, then error QL_DOUT("Gate_nonfatal:" <<" gname=" << gname <<" qubits=" << qubits <<" cregs=" << cregs <<" duration=" << duration <<" angle=" << angle <<" bregs=" << bregs <<" gcond=" << gcond <<" gcondregs=" << gcondregs); auto gname_lower = to_lower(gname); QL_DOUT("Adding gate : " << gname_lower << " with qubits " << qubits); // specialized composite gate check QL_DOUT("trying to add specialized composite gate for: " << gname_lower); Bool spec_decom_added = add_spec_decomposed_gate_if_available(gname_lower, qubits, cregs, bregs, gcond, lcondregs); if (spec_decom_added) { added = true; QL_DOUT("specialized decomposed gates added for " << gname_lower); } else { // parameterized composite gate check QL_DOUT("trying to add parameterized composite gate for: " << gname_lower); Bool param_decom_added = add_param_decomposed_gate_if_available(gname_lower, qubits, cregs, bregs, gcond, lcondregs); if (param_decom_added) { added = true; QL_DOUT("decomposed gates added for " << gname_lower); } else { // specialized/parameterized custom gate check QL_DOUT("adding custom gate for " << gname_lower); // when found, custom_added is true, and the gate was added to the circuit Bool custom_added = add_custom_gate_if_available(gname_lower, qubits, cregs, duration, angle, bregs, gcond, lcondregs); if (custom_added) { added = true; QL_DOUT("custom gate added for " << gname_lower); } else { if (options::get("use_default_gates") == "yes") { // default gate check (which is always parameterized) QL_DOUT("adding default gate for " << gname_lower); Bool default_available = add_default_gate_if_available(gname_lower, qubits, cregs, duration, angle, bregs, gcond, lcondregs); if (default_available) { added = true; QL_DOUT("default gate added for " << gname_lower); // FIXME: used to be WOUT, but that gives a warning for every "wait" and spams the log } } } } } if (added) { cycles_valid = false; } return added; } // to add unitary to kernel void quantum_kernel::gate( const unitary &u, const Vec<UInt> &qubits ) { UInt u_size = log2(u.size()) / 2; if (u_size != qubits.size()) { QL_EOUT("Unitary " << u.name << " has been applied to the wrong number of qubits! " << qubits.size() << " and not " << u_size); throw Exception("Unitary '" + u.name + "' has been applied to the wrong number of qubits. Cannot be added to kernel! " + to_string(qubits.size()) + " and not " + to_string(u_size), false); } for (uint64_t i = 0; i < qubits.size()-1; i++) { for (uint64_t j = i + 1; j < qubits.size(); j++) { if (qubits[i] == qubits[j]) { QL_EOUT("Qubit numbers used more than once in Unitary: " << u.name << ". Double qubit is number " << qubits[j]); throw Exception("Qubit numbers used more than once in Unitary: " + u.name + ". Double qubit is number " + to_string(qubits[j]), false); } } } // applying unitary to gates QL_COUT("Applying unitary '" << u.name << "' to qubits: " << qubits); if (u.is_decomposed) { QL_DOUT("Adding decomposed unitary to kernel ..."); QL_IOUT("The list is this many items long: " << u.instructionlist.size()); //COUT("Instructionlist" << to_string(u.instructionlist)); cycles_valid = false; Int end_index = recursiveRelationsForUnitaryDecomposition(u,qubits, u_size, 0); QL_DOUT("Total number of gates added: " << end_index); } else { QL_EOUT("Unitary " << u.name << " not decomposed. Cannot be added to kernel!"); throw Exception("Unitary '" + u.name + "' not decomposed. Cannot be added to kernel!", false); } } //recursive gate count function //n is number of qubits //i is the start point for the instructionlist Int quantum_kernel::recursiveRelationsForUnitaryDecomposition( const unitary &u, const Vec<UInt> &qubits, UInt n, UInt i ) { // DOUT("Adding a new unitary starting at index: "<< i << ", to " << n << to_string(qubits, " qubits: ")); if (n > 1) { // Need to be checked here because it changes the structure of the decomposition. // This checks whether the first qubit is affected, if not, it applies a unitary to the all qubits except the first one. UInt numberforcontrolledrotation = pow2(n - 1); //number of gates per rotation // code for last one not affected if (u.instructionlist[i] == 100.0) { QL_DOUT("[kernel.h] Optimization: last qubit is not affected, skip one step in the recursion. New start_index: " << i + 1); Vec<UInt> subvector(qubits.begin() + 1, qubits.end()); return recursiveRelationsForUnitaryDecomposition(u, subvector, n - 1, i + 1) + 1; // for the number 10.0 } else if (u.instructionlist[i] == 200.0) { Vec<UInt> subvector(qubits.begin(), qubits.end() - 1); // This is a special case of only demultiplexing if (u.instructionlist[i+1] == 300.0) { // Two numbers that aren't rotation gate angles UInt start_counter = i + 2; QL_DOUT("[kernel.h] Optimization: first qubit not affected, skip one step in the recursion. New start_index: " << start_counter); return recursiveRelationsForUnitaryDecomposition(u, subvector, n - 1, start_counter) + 2; //for the numbers 20 and 30 } else { UInt start_counter = i + 1; QL_DOUT("[kernel.h] Optimization: only demultiplexing will be performed. New start_index: " << start_counter); start_counter += recursiveRelationsForUnitaryDecomposition(u, subvector, n - 1, start_counter); multicontrolled_rz(u.instructionlist, start_counter, start_counter + numberforcontrolledrotation - 1, qubits); start_counter += numberforcontrolledrotation; //multicontrolled rotation always has the same number of gates start_counter += recursiveRelationsForUnitaryDecomposition(u, subvector, n - 1, start_counter); return start_counter - i; } } else { // The new qubit vector that is passed to the recursive function Vec<UInt> subvector(qubits.begin(), qubits.end() - 1); UInt start_counter = i; start_counter += recursiveRelationsForUnitaryDecomposition(u, subvector, n - 1, start_counter); multicontrolled_rz(u.instructionlist, start_counter, start_counter + numberforcontrolledrotation - 1, qubits); start_counter += numberforcontrolledrotation; start_counter += recursiveRelationsForUnitaryDecomposition(u, subvector, n - 1, start_counter); multicontrolled_ry(u.instructionlist, start_counter, start_counter + numberforcontrolledrotation - 1, qubits); start_counter += numberforcontrolledrotation; start_counter += recursiveRelationsForUnitaryDecomposition(u, subvector, n - 1, start_counter); multicontrolled_rz(u.instructionlist, start_counter, start_counter + numberforcontrolledrotation - 1, qubits); start_counter += numberforcontrolledrotation; start_counter += recursiveRelationsForUnitaryDecomposition(u, subvector, n - 1, start_counter); return start_counter -i; //it is just the total } } else { //n=1 // DOUT("Adding the zyz decomposition gates at index: "<< i); // zyz gates happen on the only qubit in the list. c.push_back(new ql::rz(qubits.back(), u.instructionlist[i])); c.push_back(new ql::ry(qubits.back(), u.instructionlist[i + 1])); c.push_back(new ql::rz(qubits.back(), u.instructionlist[i + 2])); // How many gates this took return 3; } } //controlled qubit is the first in the list. void quantum_kernel::multicontrolled_rz( const Vec<Real> &instruction_list, UInt start_index, UInt end_index, const Vec<UInt> &qubits ) { // DOUT("Adding a multicontrolled rz-gate at start index " << start_index << ", to " << to_string(qubits, "qubits: ")); UInt idx; //The first one is always controlled from the last to the first qubit. c.push_back(new ql::rz(qubits.back(),-instruction_list[start_index])); c.push_back(new ql::cnot(qubits[0], qubits.back())); for (UInt i = 1; i < end_index - start_index; i++) { idx = log2(((i)^((i)>>1))^((i+1)^((i+1)>>1))); c.push_back(new ql::rz(qubits.back(),-instruction_list[i+start_index])); c.push_back(new ql::cnot(qubits[idx], qubits.back())); } // The last one is always controlled from the next qubit to the first qubit c.push_back(new ql::rz(qubits.back(),-instruction_list[end_index])); c.push_back(new ql::cnot(qubits.end()[-2], qubits.back())); cycles_valid = false; } //controlled qubit is the first in the list. void quantum_kernel::multicontrolled_ry( const Vec<Real> &instruction_list, UInt start_index, UInt end_index, const Vec<UInt> &qubits ) { // DOUT("Adding a multicontrolled ry-gate at start index "<< start_index << ", to " << to_string(qubits, "qubits: ")); UInt idx; //The first one is always controlled from the last to the first qubit. c.push_back(new ql::ry(qubits.back(),-instruction_list[start_index])); c.push_back(new ql::cnot(qubits[0], qubits.back())); for (UInt i = 1; i < end_index - start_index; i++) { idx = log2(((i)^((i)>>1))^((i+1)^((i+1)>>1))); c.push_back(new ql::ry(qubits.back(),-instruction_list[i+start_index])); c.push_back(new ql::cnot(qubits[idx], qubits.back())); } // Last one is controlled from the next qubit to the first one. c.push_back(new ql::ry(qubits.back(),-instruction_list[end_index])); c.push_back(new ql::cnot(qubits.end()[-2], qubits.back())); cycles_valid = false; } /** * qasm output */ // FIXME: create a separate QASM backend? Str quantum_kernel::get_prologue() const { StrStrm ss; ss << "\n"; ss << "." << name << "\n"; // ss << name << ":\n"; if (type == kernel_type_t::IF_START) { ss << " b" << br_condition->inv_operation_name <<" r" << (br_condition->operands[0])->as_creg().id <<", r" << (br_condition->operands[1])->as_creg().id << ", " << name << "_end\n"; } if (type == kernel_type_t::ELSE_START) { ss << " b" << br_condition->operation_name <<" r" << (br_condition->operands[0])->as_creg().id <<", r" << (br_condition->operands[1])->as_creg().id << ", " << name << "_end\n"; } if (type == kernel_type_t::FOR_START) { // TODO for now r29, r30, r31 are used, fix it ss << " ldi r29" <<", " << iterations << "\n"; ss << " ldi r30" <<", " << 1 << "\n"; ss << " ldi r31" <<", " << 0 << "\n"; } return ss.str(); } Str quantum_kernel::get_epilogue() const { StrStrm ss; if (type == kernel_type_t::DO_WHILE_END) { ss << " b" << br_condition->operation_name <<" r" << (br_condition->operands[0])->as_creg().id <<", r" << (br_condition->operands[1])->as_creg().id << ", " << name << "_start\n"; } if (type == kernel_type_t::FOR_END) { Str kname(name); std::replace( kname.begin(), kname.end(), '_', ' '); std::istringstream iss(kname); Vec<Str> tokens{ std::istream_iterator<Str>{iss}, std::istream_iterator<Str>{} }; // TODO for now r29, r30, r31 are used, fix it ss << " add r31, r31, r30\n"; ss << " blt r31, r29, " << tokens[0] << "\n"; } return ss.str(); } Str quantum_kernel::qasm() const { StrStrm ss; ss << get_prologue(); for (UInt i = 0; i < c.size(); ++i) { ss << " " << c[i]->qasm() << "\n"; } ss << get_epilogue(); return ss.str(); } /** * classical gate */ void quantum_kernel::classical(const creg &destination, const operation &oper) { // check sanity of destination if (destination.id >= creg_count) { QL_EOUT("Out of range operand(s) for '" << oper.operation_name); throw Exception("Out of range operand(s) for '" + oper.operation_name + "' !", false); } // check sanity of other operands for (auto &op : oper.operands) { if (op->type() == operand_type_t::CREG) { if (op->as_creg().id >= creg_count) { QL_EOUT("Out of range operand(s) for '" << oper.operation_name); throw Exception("Out of range operand(s) for '" + oper.operation_name + "' !", false); } } } c.push_back(new ql::classical(destination, oper)); cycles_valid = false; } void quantum_kernel::classical(const Str &operation) { c.push_back(new ql::classical(operation)); cycles_valid = false; } void quantum_kernel::controlled_x(UInt tq, UInt cq) { // from: https://arxiv.org/pdf/1206.0758v3.pdf // A meet-in-the-middle algorithm for fast synthesis // of depth-optimal quantum circuits cnot(cq, tq); } void quantum_kernel::controlled_y(UInt tq, UInt cq) { // from: https://arxiv.org/pdf/1206.0758v3.pdf // A meet-in-the-middle algorithm for fast synthesis // of depth-optimal quantum circuits sdag(tq); cnot(cq, tq); s(tq); } void quantum_kernel::controlled_z(UInt tq, UInt cq) { // from: https://arxiv.org/pdf/1206.0758v3.pdf // A meet-in-the-middle algorithm for fast synthesis // of depth-optimal quantum circuits hadamard(tq); cnot(cq, tq); hadamard(tq); } void quantum_kernel::controlled_h(UInt tq, UInt cq) { // from: https://arxiv.org/pdf/1206.0758v3.pdf // A meet-in-the-middle algorithm for fast synthesis // of depth-optimal quantum circuits s(tq); hadamard(tq); t(tq); cnot(cq, tq); tdag(tq); hadamard(tq); sdag(tq); } void quantum_kernel::controlled_i(UInt tq, UInt cq) { // well, basically you dont need to do anything for it :‑) } void quantum_kernel::controlled_s(UInt tq, UInt cq) { // cphase(cq, tq); // from: https://arxiv.org/pdf/1206.0758v3.pdf // A meet-in-the-middle algorithm for fast synthesis // of depth-optimal quantum circuits cnot(tq, cq); tdag(cq); cnot(tq, cq); t(cq); t(tq); } void quantum_kernel::controlled_sdag(UInt tq, UInt cq) { // based on: https://arxiv.org/pdf/1206.0758v3.pdf // A meet-in-the-middle algorithm for fast synthesis // of depth-optimal quantum circuits tdag(cq); tdag(tq); cnot(tq, cq); t(cq); cnot(tq, cq); } void quantum_kernel::controlled_t(UInt tq, UInt cq, UInt aq) { QL_WOUT("Controlled-T implementation requires an ancilla"); QL_WOUT("At the moment, Qubit 0 is used as ancilla"); QL_WOUT("This will change when Qubit allocater is implemented"); // from: https://arxiv.org/pdf/1206.0758v3.pdf // A meet-in-the-middle algorithm for fast synthesis // of depth-optimal quantum circuits cnot(cq, tq); hadamard(aq); sdag(cq); cnot(tq, aq); cnot(aq, cq); t(cq); tdag(aq); cnot(tq, cq); cnot(tq, aq); t(cq); tdag(aq); cnot(aq, cq); h(cq); t(cq); h(cq); cnot(aq, cq); tdag(cq); t(aq); cnot(tq, aq); cnot(tq, cq); t(aq); tdag(cq); cnot(aq, cq); s(cq); cnot(tq, aq); cnot(cq, tq); h(aq); } void quantum_kernel::controlled_tdag(UInt tq, UInt cq, UInt aq) { QL_WOUT("Controlled-Tdag implementation requires an ancilla"); QL_WOUT("At the moment, Qubit 0 is used as ancilla"); QL_WOUT("This will change when Qubit allocater is implemented"); // from: https://arxiv.org/pdf/1206.0758v3.pdf // A meet-in-the-middle algorithm for fast synthesis // of depth-optimal quantum circuits h(aq); cnot(cq, tq); sdag(cq); cnot(tq, aq); cnot(aq, cq); t(cq); cnot(tq, cq); tdag(aq); cnot(tq, aq); t(cq); tdag(aq); cnot(aq, cq); h(cq); tdag(cq); h(cq); cnot(aq, cq); tdag(cq); t(aq); cnot(tq, aq); cnot(tq, cq); tdag(cq); t(aq); cnot(aq, cq); s(cq); cnot(tq, aq); cnot(cq, tq); hadamard(aq); } void quantum_kernel::controlled_ix(UInt tq, UInt cq) { // from: https://arxiv.org/pdf/1210.0974.pdf // Quantum circuits of T-depth one cnot(cq, tq); s(cq); } // toffoli decomposition // from: https://arxiv.org/pdf/1210.0974.pdf // Quantum circuits of T-depth one void quantum_kernel::controlled_cnot_AM(UInt tq, UInt cq1, UInt cq2) { h(tq); t(cq1); t(cq2); t(tq); cnot(cq2, cq1); cnot(tq, cq2); cnot(cq1, tq); tdag(cq2); cnot(cq1, cq2); tdag(cq1); tdag(cq2); tdag(tq); cnot(tq, cq2); cnot(cq1, tq); cnot(cq2, cq1); h(tq); } // toffoli decomposition // Neilsen and Chuang void quantum_kernel::controlled_cnot_NC(UInt tq, UInt cq1, UInt cq2) { h(tq); cnot(cq2,tq); tdag(tq); cnot(cq1,tq); t(tq); cnot(cq2,tq); tdag(tq); cnot(cq1,tq); tdag(cq2); t(tq); cnot(cq1,cq2); h(tq); tdag(cq2); cnot(cq1,cq2); t(cq1); s(cq2); } void quantum_kernel::controlled_swap(UInt tq1, UInt tq2, UInt cq) { // from: https://arxiv.org/pdf/1210.0974.pdf // Quantum circuits of T-depth one cnot(tq2, tq1); cnot(cq, tq1); h(tq2); t(cq); tdag(tq1); t(tq2); cnot(tq2, tq1); cnot(cq, tq2); t(tq1); cnot(cq, tq1); tdag(tq2); tdag(tq1); cnot(cq, tq2); cnot(tq2, tq1); t(tq1); h(tq2); cnot(tq2, tq1); } void quantum_kernel::controlled_rx(UInt tq, UInt cq, Real theta) { rx(tq, theta/2); cz(cq, tq); rx(tq, -theta/2); cz(cq, tq); } void quantum_kernel::controlled_ry(UInt tq, UInt cq, Real theta) { ry(tq, theta/2); cnot(cq, tq); ry(tq, -theta/2); cnot(cq, tq); } void quantum_kernel::controlled_rz(UInt tq, UInt cq, Real theta) { rz(tq, theta/2); cnot(cq, tq); rz(tq, -theta/2); cnot(cq, tq); } void quantum_kernel::controlled_single( const quantum_kernel *k, UInt control_qubit, UInt ancilla_qubit ) { const circuit &ckt = k->get_circuit(); for (auto &g : ckt) { Str gname = g->name; gate_type_t gtype = g->type(); Vec<UInt> goperands = g->operands; QL_DOUT("Generating controlled gate for " << gname); QL_DOUT("Type : " << gtype); if (gtype == __pauli_x_gate__ || gtype == __rx180_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_x(tq, cq); } else if (gtype == __pauli_y_gate__ || gtype == __ry180_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_y(tq, cq); } else if (gtype == __pauli_z_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_z(tq, cq); } else if (gtype == __hadamard_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_h(tq, cq); } else if (gtype == __identity_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_i(tq, cq); } else if (gtype == __t_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; UInt aq = ancilla_qubit; controlled_t(tq, cq, aq); } else if (gtype == __tdag_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; UInt aq = ancilla_qubit; controlled_tdag(tq, cq, aq); } else if (gtype == __phase_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_s(tq, cq); } else if (__phasedag_gate__ == gtype) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_sdag(tq, cq); } else if (__cnot_gate__ == gtype) { UInt cq1 = goperands[0]; UInt cq2 = control_qubit; UInt tq = goperands[1]; auto opt = options::get("decompose_toffoli"); if (opt == "AM") { controlled_cnot_AM(tq, cq1, cq2); } else if (opt == "NC") { controlled_cnot_NC(tq, cq1, cq2); } else { toffoli(cq1, cq2, tq); } } else if (gtype == __swap_gate__) { UInt tq1 = goperands[0]; UInt tq2 = goperands[1]; UInt cq = control_qubit; controlled_swap(tq1, tq2, cq); } else if (gtype == __rx_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_rx(tq, cq, g->angle); } else if (gtype == __ry_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_ry(tq, cq, g->angle); } else if (gtype == __rz_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_rz(tq, cq, g->angle); } else if (gtype == __rx90_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_rx(tq, cq, K_PI/2); } else if (gtype == __mrx90_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_rx(tq, cq, -1*K_PI/2); } else if (gtype == __rx180_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_rx(tq, cq, K_PI); // controlled_x(tq, cq); } else if (gtype == __ry90_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_ry(tq, cq, K_PI/4); } else if (gtype == __mry90_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_ry(tq, cq, -1*K_PI/4); } else if (gtype == __ry180_gate__) { UInt tq = goperands[0]; UInt cq = control_qubit; controlled_ry(tq, cq, K_PI); // controlled_y(tq, cq); } else { QL_EOUT("Controlled version of gate '" << gname << "' not defined !"); throw Exception("[x] error : kernel::controlled : Controlled version of gate '" + gname + "' not defined ! ", false); } } } void quantum_kernel::controlled( const quantum_kernel *k, const Vec<UInt> &control_qubits, const Vec<UInt> &ancilla_qubits ) { QL_DOUT("Generating controlled kernel ... "); Int ncq = control_qubits.size(); Int naq = ancilla_qubits.size(); if (ncq == 0) { QL_EOUT("At least one control_qubits should be specified !"); throw Exception("[x] error : kernel::controlled : At least one control_qubits should be specified !", false); } else if (ncq == 1) { // control ancilla controlled_single(k, control_qubits[0], ancilla_qubits[0]); } else if (ncq > 1) { // Network implementing C^n(U) operation // - based on Fig. 4.10, p.p 185, Nielson & Chuang // - requires as many ancilla/work qubits as control qubits if (naq == ncq) { toffoli(control_qubits[0], control_qubits[1], ancilla_qubits[0]); for (Int n = 0; n <= naq - 3; n++) { toffoli(control_qubits[n+2], ancilla_qubits[n], ancilla_qubits[n+1]); } // control ancilla controlled_single(k, ancilla_qubits[naq-2], ancilla_qubits[naq-1]); for (Int n = naq - 3; n >= 0; n--) { toffoli(control_qubits[n+2], ancilla_qubits[n], ancilla_qubits[n+1]); } toffoli(control_qubits[0], control_qubits[1], ancilla_qubits[0]); } else { QL_EOUT("No. of control qubits should be equal to No. of ancilla qubits!"); throw Exception("[x] error : kernel::controlled : No. of control qubits should be equal to No. of ancilla qubits!", false); } } QL_DOUT("Generating controlled kernel [Done]"); } void quantum_kernel::conjugate(const quantum_kernel *k) { QL_COUT("Generating conjugate kernel"); const circuit &ckt = k->get_circuit(); for (auto rgit = ckt.rbegin(); rgit != ckt.rend(); ++rgit) { auto g = *rgit; Str gname = g->name; gate_type_t gtype = g->type(); QL_DOUT("Generating conjugate gate for " << gname); QL_DOUT("Type : " << gtype); if (gtype == __pauli_x_gate__ || gtype == __rx180_gate__) { gate("x", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __pauli_y_gate__ || gtype == __ry180_gate__) { gate("y", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __pauli_z_gate__) { gate("z", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __hadamard_gate__) { gate("hadamard", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __identity_gate__) { gate("identity", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __t_gate__) { gate("tdag", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __tdag_gate__) { gate("t", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __phase_gate__) { gate("sdag", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __phasedag_gate__) { gate("s", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __cnot_gate__) { gate("cnot", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __swap_gate__) { gate("swap", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __rx_gate__) { gate("rx", g->operands, {}, g->duration, -(g->angle) , g->breg_operands); } else if (gtype == __ry_gate__) { gate("ry", g->operands, {}, g->duration, -(g->angle) , g->breg_operands); } else if (gtype == __rz_gate__) { gate("rz", g->operands, {}, g->duration, -(g->angle) , g->breg_operands); } else if (gtype == __rx90_gate__) { gate("mrx90", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __mrx90_gate__) { gate("rx90", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __rx180_gate__) { gate("x", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __ry90_gate__) { gate("mry90", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __mry90_gate__) { gate("ry90", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __ry180_gate__) { gate("y", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __cphase_gate__) { gate("cphase", g->operands, {}, g->duration, g->angle, g->breg_operands); } else if (gtype == __toffoli_gate__) { gate("toffoli", g->operands, {}, g->duration, g->angle, g->breg_operands); } else { QL_EOUT("Conjugate version of gate '" << gname << "' not defined !"); throw Exception("[x] error : kernel::conjugate : Conjugate version of gate '" + gname + "' not defined ! ", false); } } QL_COUT("Generating conjugate kernel [Done]"); } } // namespace ql
#include <assert.h> #include <stdlib.h> #include <stdio.h> #include <libelf.h> #include <fcntl.h> #include <unistd.h> #include <iostream.h> #include "cachemire-2.h" #include "cm_memory.h" int load_file(char* file, unsigned long * start_address) { int fp; char name[80]; int main_found = 0; int slave_found = 0; char err_str[80]; Elf *elf; Elf_Cmd cmd; Elf_Scn *scn = 0; Elf32_Ehdr *ehdr; Elf32_Shdr *shdr; Elf32_Phdr *phdr; Elf_Scn *scn_string_table; Elf_Data *string_table = 0; Elf_Data *sym_string_table = 0; Elf_Data *data = 0; int little_endian = 0; fprintf(stderr,"\n"); /* Check if file exists, otherwise exit */ if ((fp = open(file, O_RDONLY)) == -1) { perror("File doesn't exist\n"); exit(1); } if (elf_version(EV_CURRENT) == EV_NONE) { /* library out of date */ /* recover from error */ } cmd = ELF_C_READ; elf = elf_begin(fp, cmd, (Elf *)0); /* Check that the file is an elf file */ if (elf_kind(elf) != ELF_K_ELF) { fprintf(stderr,"Error: file %s is not an elf file\n", file); return CM_ERROR; } ehdr = elf32_getehdr(elf); if (ehdr->e_ident[EI_DATA] == ELFDATA2LSB){ little_endian = 1; } else if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB){ little_endian = 0; } else { perror("Unknown data encoding!"); exit(-1); } *start_address = (unsigned long) ehdr->e_entry; // What am I going to do with it??? phdr = elf32_getphdr(elf); // Get the section string table scn_string_table = elf_getscn(elf, (size_t) ehdr->e_shstrndx); string_table = elf_getdata(scn_string_table, string_table); while ((scn = elf_nextscn(elf, scn)) != 0) { char *id; char *t; shdr = elf32_getshdr(scn); t = (char *)string_table->d_buf; id = (char *)&(t[shdr->sh_name]); #if 0 id = (char *)&(string_table->d_buf[shdr->sh_name]); #endif data = 0; data = elf_getdata(scn, data); #if DEBUGLEVEL>=1 if (shdr->sh_addr) fprintf(stderr,"Section %s start occupies addresses 0x%x to 0x%x\n", id, shdr->sh_addr, shdr->sh_addr+data->d_size); #endif if (shdr->sh_addr) { // Find the start and finish of text and data respectively. // Try also to determine where the heap is going to be. // If the section is writeable, then it is data // otherwise text if (shdr->sh_flags & SHF_WRITE) { // data min_data_addr = (min_data_addr < shdr->sh_addr ? min_data_addr : shdr->sh_addr); max_data_addr = (max_data_addr > (shdr->sh_addr+data->d_size) ? max_data_addr : (shdr->sh_addr+data->d_size)); } else { // text min_text_addr = (min_text_addr < shdr->sh_addr ? min_text_addr : shdr->sh_addr); max_text_addr = (max_text_addr > (shdr->sh_addr+data->d_size) ? max_text_addr : (shdr->sh_addr+data->d_size)); } if (data->d_buf) CopyMemSun2CM(INVALID, (unsigned long)data->d_buf, (unsigned long) shdr->sh_addr, (int) data->d_size); } } data_start = min_data_addr; data_end = max_data_addr; text_start = min_text_addr; text_end = max_text_addr; #if 0 /* Insert a ta TRAP_EXIT at address 8 */ i = 0x91d02024; GlobalMemoryOp(INVALID, WRITE_OP, 8, &i, S_WORD); #endif close(fp); return CM_OK; }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_68a.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml Template File: sources-sink-68a.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate memory for a string, but do not allocate space for NULL terminator * GoodSource: Allocate enough memory for a string and the NULL terminator * Sink: memcpy * BadSink : Copy string to data using memcpy() * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif /* MAINTENANCE NOTE: The length of this string should equal the 10 */ #define SRC_STRING "AAAAAAAAAA" char * CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_68_badData; char * CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_68_goodG2BData; namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_68 { #ifndef OMITBAD /* bad function declaration */ void badSink(); void bad() { char * data; data = NULL; /* FLAW: Did not leave space for a null terminator */ data = new char[10]; CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_68_badData = data; badSink(); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void goodG2BSink(); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { char * data; data = NULL; /* FIX: Allocate space for a null terminator */ data = new char[10+1]; CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_68_goodG2BData = data; goodG2BSink(); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_memcpy_68; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#include "filesystem.hpp" #include <fstream> #include <sstream> NOXIS_NS_BEGIN; bool isFileExist(const std::string &path) { std::ifstream testFile(path); auto isOk = testFile.good(); testFile.close(); return isOk; } std::string joinPath(std::initializer_list<std::string> paths) { std::ostringstream result; auto i = paths.begin(), end = paths.end(); if(i != end) { result << *i++; } while(i != end) { result << PATH_SEPARATOR << *i++; } return result.str(); } NOXIS_NS_END;
#pragma once #include <stdint.h> namespace bfos::terminal { using SizeUnit = uint16_t; using Attribute = uint8_t; const int WIDTH = 80; const int HEIGHT = 25; class RawOutput { public: void printChar(char character); void printString(const char *string); void clearScreen(); void setAttribute(Attribute attribute); Attribute getAttribute() const; void setCurrentPosition(SizeUnit positionX, SizeUnit positionY); inline void putEntity(SizeUnit positionX, SizeUnit positionY, char character, Attribute attribute); private: SizeUnit positionX = 0; SizeUnit positionY = 0; Attribute attribute = 0xF; uint16_t * const videoMemory = reinterpret_cast<uint16_t*>(0xB8000); }; }
#include <swizzle/ast/nodes/Enum.hpp> #include <swizzle/ast/VisitorInterface.hpp> namespace swizzle { namespace ast { namespace nodes { Enum::Enum(const lexer::TokenInfo& enumInfo, const lexer::TokenInfo& name, const std::string& containingNamespace) : enumInfo_(enumInfo) , nameInfo_(name) , name_(containingNamespace + "::" + nameInfo_.token().to_string()) { } const lexer::TokenInfo& Enum::enumInfo() const { return enumInfo_; } const lexer::TokenInfo& Enum::nameInfo() const { return nameInfo_; } std::string Enum::name() const { return name_; } void Enum::underlying(const lexer::TokenInfo& value) { underlyingType_ = value; } const lexer::TokenInfo& Enum::underlying() const { return underlyingType_; } void Enum::accept(VisitorInterface& visitor) { visitor(*this); for(auto& child : children()) { child->accept(visitor); } } }}}
class X { int i; public: X(int ii = 0) ; void modify(); }; X::X(int ii) { i = ii; } void X::modify() { i++; } int main() { X x; x.modify(); }
/**************************************************************************************** * @author: kzvd4729 created: Jan/21/2018 14:00 * solution_verdict: Accepted language: GNU C++14 * run_time: 764 ms memory_used: 9700 KB * problem: https://codeforces.com/contest/914/problem/D ****************************************************************************************/ #include<bits/stdc++.h> using namespace std; int n,x,q,ck,seg[4*500005],id,l,r,gcd,p; void upd(int node,int lo,int hi,int idx,int vl) { if(idx<lo||idx>hi)return ; if(lo==hi) { seg[node]=vl; return ; } int mid=(lo+hi)/2; upd(node*2,lo,mid,idx,vl); upd(node*2+1,mid+1,hi,idx,vl); seg[node]=__gcd(seg[node*2],seg[node*2+1]); } void query(int node,int lo,int hi,int l,int r,int gcd) { if(p>=2)return ; if(lo>r||hi<l)return ; if(lo>=l&&hi<=r) { if(seg[node]%gcd==0)return ; if(lo==hi) { p++; return ; } } int mid=(lo+hi)/2; query(node*2,lo,mid,l,r,gcd); query(node*2+1,mid+1,hi,l,r,gcd); } int main() { scanf("%ld",&n); for(int i=1;i<=n;i++) { scanf("%ld",&x); upd(1,1,n,i,x); } scanf("%ld",&q); while(q--) { scanf("%ld",&ck); if(ck==1) { scanf("%ld%ld%ld",&l,&r,&gcd); p=0; query(1,1,n,l,r,gcd); if(p<2)printf("YES\n"); else printf("NO\n"); } else { scanf("%ld%ld",&id,&x); upd(1,1,n,id,x); } } return 0; }
#include "base/colorutil.h" uint32_t whiteAlpha(float alpha) { if (alpha < 0.0f) alpha = 0.0f; if (alpha > 1.0f) alpha = 1.0f; uint32_t color = (int)(alpha*255) << 24; color |= 0xFFFFFF; return color; } uint32_t blackAlpha(float alpha) { if (alpha < 0.0f) alpha = 0.0f; if (alpha > 1.0f) alpha = 1.0f; return (int)(alpha*255)<<24; } uint32_t colorAlpha(uint32_t color, float alpha) { if (alpha < 0.0f) alpha = 0.0f; if (alpha > 1.0f) alpha = 1.0f; return ((int)(alpha*255)<<24) | (color & 0xFFFFFF); } uint32_t rgba(float r, float g, float b, float alpha) { uint32_t color = (int)(alpha*255)<<24; color |= (int)(b*255)<<16; color |= (int)(g*255)<<8; color |= (int)(r*255); return color; } uint32_t rgba_clamp(float r, float g, float b, float a) { if (r > 1.0f) r = 1.0f; if (g > 1.0f) g = 1.0f; if (b > 1.0f) b = 1.0f; if (a > 1.0f) a = 1.0f; if (r < 0.0f) r = 0.0f; if (g < 0.0f) g = 0.0f; if (b < 0.0f) b = 0.0f; if (a < 0.0f) a = 0.0f; return rgba(r,g,b,a); } /* hsv2rgb.c * Convert Hue Saturation Value to Red Green Blue * * P.J. 08-Aug-98 * * Reference: * D. F. Rogers * Procedural Elements for Computer Graphics * McGraw Hill 1985 */ uint32_t hsva(float H, float S, float V, float alpha) { /* * Purpose: * Convert HSV values to RGB values * All values are in the range [0.0 .. 1.0] */ float F, M, N, K; int I; if ( S == 0.0 ) { // Achromatic case, set level of grey return rgba(V, V, V, alpha); } else { /* * Determine levels of primary colours. */ if (H >= 1.0) { H = 0.0; } else { H = H * 6; } I = (int) H; /* should be in the range 0..5 */ F = H - I; /* fractional part */ M = V * (1 - S); N = V * (1 - S * F); K = V * (1 - S * (1 - F)); float r, g, b; if (I == 0) { r = V; g = K; b = M; } else if (I == 1) { r = N; g = V; b = M; } else if (I == 2) { r = M; g = V; b = K; } else if (I == 3) { r = M; g = N; b = V; } else if (I == 4) { r = K; g = M; b = V; } else if (I == 5) { r = V; g = M; b = N; } else return 0; return rgba(r, g, b, alpha); } }
// Author: Mingcheng Chen (linyufly@gmail.com) #include "watershed_extractor.h" #include "util.h" #include <vtkStructuredPointsReader.h> #include <vtkStructuredPointsWriter.h> #include <vtkStructuredPoints.h> #include <vtkSmartPointer.h> #include <vtkPointData.h> #include <vtkDataArray.h> #include <vtkIndent.h> #include <vtkImageData.h> #include <vtkXMLImageDataReader.h> #include <cstdio> #include <cstdlib> #include <iostream> // const char *kScalarFile = "data/one_sphere_ftle.vtk"; // const char *kScalarFile = "data/sphere_ftle.vtk"; // const char *kScalarFile = "data/gyre_half.vtk"; const char *kScalarFile = "smoothed_scalar.vtk"; // const char *kScalarFile = "/home/linyufly/Data/P96_bFTLE.vtk"; // const char *kScalarFile = "../WatershedSurface/data/sphere_ftle.vtk"; // const char *kScalarFile = "structured_points.vtk"; const char *kBasinFile = "basin_index.vtk"; const char *kDistFile = "dist_2_valley.vtk"; // const char *kScalarToSmoothFile = "data/gyre_half.vtk"; // const char *kScalarToSmoothFile = "data/output_200.vtk"; // const char *kScalarToSmoothFile = "/home/linyufly/Data/abcflow_200.vtk"; const char *kScalarToSmoothFile = "/home/linyufly/Data/P96_bFTLE.vtk"; // const char *kScalarToSmoothFile = "data/output.vtk"; // const char *kScalarToSmoothFile = "data/bkd_003125.230-binary.vtk"; // const char *kScalarToSmoothFile = "../../ExtraStorage/P96_bFTLE/P96_bFTLE.vti"; // const char *kScalarToSmoothFile = "structured_points.vtk"; const char *kSmoothedScalarFile = "smoothed_scalar.vtk"; const char *kFilteredBasinFile = "filtered_basin.vtk"; // const char *kImageDataFile = "../../ExtraStorage/P96_bFTLE/P96_bFTLE.vti"; const char *kImageDataFile = "/home/linyufly/Data/P96_bFTLE.vti"; const char *kStructuredPointsFile = "structured_points.vtk"; const int kNumberOfSmoothing = 1; // 1 for gyre_half.vtk // 10 for output_200.vtk void extract_watershed_test() { printf("extract_watershed_test {\n"); vtkSmartPointer<vtkStructuredPointsReader> reader = vtkSmartPointer<vtkStructuredPointsReader>::New(); reader->SetFileName(kScalarFile); reader->Update(); vtkSmartPointer<vtkStructuredPoints> scalar_field = vtkSmartPointer<vtkStructuredPoints>::New(); scalar_field->ShallowCopy(reader->GetOutput()); WatershedExtractor extractor; vtkStructuredPoints *basin_index = NULL, *dist_2_valley = NULL; std::vector<double> valley_height; extractor.extract_watershed( scalar_field, &basin_index, &dist_2_valley, &valley_height); vtkSmartPointer<vtkStructuredPointsWriter> writer = vtkSmartPointer<vtkStructuredPointsWriter>::New(); writer->SetFileName(kBasinFile); writer->SetInputData(basin_index); writer->Write(); writer->SetFileName(kDistFile); writer->SetInputData(dist_2_valley); writer->Write(); if (basin_index) { basin_index->Delete(); } if (dist_2_valley) { dist_2_valley->Delete(); } printf("} extract_watershed_test\n\n"); } void laplacian_smoothing_test() { printf("laplacian_smoothing_test {\n"); vtkSmartPointer<vtkStructuredPointsReader> reader = vtkSmartPointer<vtkStructuredPointsReader>::New(); reader->SetFileName(kScalarToSmoothFile); reader->Update(); vtkSmartPointer<vtkStructuredPoints> scalar_field = vtkSmartPointer<vtkStructuredPoints>::New(); scalar_field->ShallowCopy(reader->GetOutput()); int dimensions[3]; scalar_field->GetDimensions(dimensions); int nx = dimensions[0]; int ny = dimensions[1]; int nz = dimensions[2]; double ***scalar_array = create_3d_array<double>(nx, ny, nz); for (int x = 0; x < nx; x++) { for (int y = 0; y < ny; y++) { for (int z = 0; z < nz; z++) { int index = (z * ny + y) * nx + x; scalar_array[x][y][z] = scalar_field->GetPointData() ->GetScalars() ->GetTuple1(index); } } } WatershedExtractor extractor; for (int i = 0; i < kNumberOfSmoothing; i++) { extractor.laplacian_smoothing(scalar_array, nx, ny, nz); } for (int x = 0; x < nx; x++) { for (int y = 0; y < ny; y++) { for (int z = 0; z < nz; z++) { int index = (z * ny + y) * nx + x; scalar_field->GetPointData() ->GetScalars() ->SetTuple1(index, scalar_array[x][y][z]); } } } vtkSmartPointer<vtkStructuredPointsWriter> writer = vtkSmartPointer<vtkStructuredPointsWriter>::New(); writer->SetFileName(kSmoothedScalarFile); writer->SetInputData(scalar_field); writer->Write(); delete_3d_array(scalar_array); printf("} laplacian_smoothing_test\n\n"); } void filter_watershed_test() { printf("filter_watershed_test {\n"); vtkSmartPointer<vtkStructuredPointsReader> reader = vtkSmartPointer<vtkStructuredPointsReader>::New(); reader->SetFileName(kScalarFile); reader->Update(); vtkSmartPointer<vtkStructuredPoints> scalar_field = vtkSmartPointer<vtkStructuredPoints>::New(); scalar_field->ShallowCopy(reader->GetOutput()); /// DEBUG /// // Thresholding. for (int i = 0; i < scalar_field->GetPointData()->GetScalars()->GetNumberOfTuples(); i++) { double value = scalar_field->GetPointData()->GetScalars()->GetTuple1(i); if (value <= 3.0) { value = 0.0; } scalar_field->GetPointData()->GetScalars()->SetTuple1(i, value); } WatershedExtractor extractor; vtkStructuredPoints *basin_index = NULL, *dist_2_valley = NULL; std::vector<double> valley_height; extractor.extract_watershed( scalar_field, &basin_index, &dist_2_valley, &valley_height); vtkStructuredPoints *filtered_index = NULL; extractor.filter_watershed(scalar_field, basin_index, dist_2_valley, valley_height, 0.0, 0.0 /*0.000015*/, &filtered_index); // gyre_half // good height_threshold for 10 / 20 : 0.001, 0.002, 0.003, 0.004, 0.005 // good height_threshold for 1: 0.0005, 0.001 // output_200 // good height_threshold for 10: 0.006, 0.005 // output // good height_threshold for 10: // heart // good height_threshold for 10: 1.0, 0.5 // sphere_ftle // good height_threshold for 0: 0.1 // Patient 96 // good height_threshold for 10: 0.1, 0.05 vtkSmartPointer<vtkStructuredPointsWriter> writer = vtkSmartPointer<vtkStructuredPointsWriter>::New(); writer->SetFileName(kFilteredBasinFile); writer->SetInputData(filtered_index); writer->Write(); if (basin_index) { basin_index->Delete(); } if (dist_2_valley) { dist_2_valley->Delete(); } if (filtered_index) { filtered_index->Delete(); } printf("} filter_watershed_test\n\n"); } void image_data_2_structured_points_test() { printf("image_data_2_structured_points_test {\n"); vtkSmartPointer<vtkXMLImageDataReader> reader = vtkSmartPointer<vtkXMLImageDataReader>::New(); reader->SetFileName(kImageDataFile); reader->Update(); WatershedExtractor extractor; vtkStructuredPoints *structured = extractor.image_data_2_structured_points(reader->GetOutput()); vtkSmartPointer<vtkStructuredPointsWriter> writer = vtkSmartPointer<vtkStructuredPointsWriter>::New(); writer->SetInputData(structured); writer->SetFileName(kStructuredPointsFile); writer->Write(); if (!structured) { structured->Delete(); } printf("} image_data_2_structured_points_test\n\n"); } int main() { // extract_watershed_test(); laplacian_smoothing_test(); // filter_watershed_test(); // image_data_2_structured_points_test(); return 0; }
// Copyright (c) 2017 The University of Sydney #include "../device.h" #include "../orientus/traits.h" #include <comma/application/command_line_options.h> #include <comma/application/verbose.h> #include <comma/csv/options.h> #include <comma/csv/stream.h> #include <comma/io/select.h> using namespace snark::navigation::advanced_navigation; const unsigned default_baud_rate = 115200; const unsigned default_sleep = 10000; void usage( bool verbose ) { std::cerr << std::endl; std::cerr << "connect to Advanced Navigation Orientus device and output IMU data" << std::endl; std::cerr << std::endl; std::cerr << " output is (system) timestamped by the application" << std::endl; std::cerr << std::endl; std::cerr << "usage: " << comma::verbose.app_name() << " <what> [<options>]" << std::endl; std::cerr << std::endl; std::cerr << "what: " << std::endl; std::cerr << " system-state system state packet (omits reserved fields)" << std::endl; std::cerr << " raw-sensors output accelerometer, gryoscope, magnetometer, imu temperature" << std::endl; std::cerr << " header output packet headers only" << std::endl; std::cerr << " all combines system-state and raw-sensors, outputs on raw-sensors packet" << std::endl; std::cerr << std::endl; std::cerr << "options:" << std::endl; std::cerr << " --baud-rate=<n> baud rate for connection, default " << default_baud_rate << std::endl; std::cerr << " --binary-output output in binary" << std::endl; std::cerr << " --description=<field> print out one line description text for input values of <field>; csv options apply to input" << std::endl; std::cerr << " <field>: system_status | filter_status" << std::endl; std::cerr << " --device=<filename> filename for serial port e.g. /dev/usb/ttyUSB0" << std::endl; std::cerr << " --help,-h show help" << std::endl; std::cerr << " --output-fields print output fields and exit" << std::endl; std::cerr << " --output-format print output format and exit" << std::endl; std::cerr << " --raw output raw packets to stdout" << std::endl; std::cerr << " --sleep=<n> microsecond sleep between reading, default " << default_sleep << std::endl; std::cerr << " --stdin read packets from stdin, can't be used with options that need to write to device" << std::endl; std::cerr << " --verbose,-v verbose output" << std::endl; std::cerr << std::endl; if( verbose ) { std::cerr << "csv options:" << std::endl; std::cerr << comma::csv::options::usage() << std::endl; } else { std::cerr << "use -v or --verbose to see more detail" << std::endl; } std::cerr << std::endl; std::cerr << "examples:" << std::endl; std::cerr << " sudo mknod /dev/ttyUSB0 c 188 0" << std::endl; std::cerr << " " << comma::verbose.app_name() << " system-state --device /dev/ttyUSB0" << std::endl; std::cerr << " " << comma::verbose.app_name() << " raw-sensors --device /dev/ttyUSB0" << std::endl; std::cerr << " " << comma::verbose.app_name() << " all --device /dev/ttyUSB0" << std::endl; std::cerr << std::endl; std::cerr << " see description of system_status values" << std::endl; std::cerr << " " << comma::verbose.app_name() << " system-state --device /dev/ttyUSB0 | " << comma::verbose.app_name() << " --fields ,status --description system_status" << std::endl; std::cerr << " echo 128 | " << comma::verbose.app_name() << " --description system_status" << std::endl; std::cerr << std::endl; std::cerr << " see description of filter_status values" << std::endl; std::cerr << " " << comma::verbose.app_name() << " system-state --device /dev/ttyUSB0 | " << comma::verbose.app_name() << " --fields ,,status --description filter_status" << std::endl; std::cerr << " echo 1029 | " << comma::verbose.app_name() << " --description filter_status" << std::endl; std::cerr << std::endl; } struct output_all { messages::system_state system_state; messages::raw_sensors raw_sensors; }; struct status_data { uint16_t status; }; namespace comma { namespace visiting { template <> struct traits< output_all > { template < typename Key, class Visitor > static void visit( const Key&, const output_all& p, Visitor& v ) { v.apply( "", p.system_state ); v.apply( "", p.raw_sensors ); } }; template <> struct traits< status_data > { template < typename Key, class Visitor > static void visit( const Key&, const status_data& p, Visitor& v ) { v.apply( "status", p.status ); } template < typename Key, class Visitor > static void visit( const Key&, status_data& p, Visitor& v ) { v.apply( "status", p.status ); } }; template < unsigned int S, bool P, bool F, std::size_t N > struct traits< boost::array< comma::packed::detail::endian< comma::packed::detail::big, S, P, F >, N > > { template< typename K, typename V > static void visit( const K& k, const boost::array< comma::packed::detail::endian< comma::packed::detail::big, S, P, F >, N >& t, V& v ) { for( std::size_t i = 0; i < t.size(); i++ ) { v.apply( i, t[i]() ); } } }; } } // namespace comma { namespace visiting { struct app_i { virtual ~app_i() {} virtual void run() = 0; virtual void output_fields() = 0; }; struct app_base : protected device { unsigned us; comma::io::select select; public: app_base( const std::string& port, const comma::command_line_options& options ) : device( port, options.value< unsigned >( "--baud-rate", default_baud_rate ) ) , us( options.value< unsigned >( "--sleep", default_sleep ) ) { select.read().add( fd() ); } void process() { while( std::cout.good() ) { select.wait( boost::posix_time::microseconds( us ) ); if( select.read().ready( fd() ) ) { device::process(); } } } }; struct app_raw : public app_base { std::vector<char> obuf; app_raw( const std::string& port, const comma::command_line_options& options ) : app_base( port, options ), obuf( 260 ) {} static void output_fields() { std::cout << std::endl; } static void output_format() { std::cout << std::endl; } protected: void handle_raw( messages::header* msg_header, const char* msg_data, std::size_t msg_data_length ) { obuf.resize( messages::header::size + msg_data_length ); std::memcpy( &obuf[0], msg_header->data(), messages::header::size ); std::memcpy( &obuf[ messages::header::size ], msg_data, msg_data_length ); std::cout.write( &obuf[0], obuf.size() ); } }; template< typename T > struct app_t : public app_base { typedef snark::timestamped< T > output_t; comma::csv::output_stream< output_t > os; app_t( const std::string& port, const comma::command_line_options& options ) : app_base( port, options ) , os( std::cout, options.exists( "--binary-output" ), true, true ) // options.exists( "--flush" ) { } static void output_fields() { std::cout << comma::join( comma::csv::names< output_t >( true ), ',' ) << std::endl; } static void output_format() { std::cout << comma::csv::format::value< output_t >() << std::endl; } void write( const T& t ) { os.write( output_t( t ) ); } }; struct app_header : public app_t< messages::header > { app_header( const std::string& port, const comma::command_line_options& options ) : app_t( port, options ) {} void handle_raw( messages::header* msg_header, const char* msg_data, std::size_t msg_data_length ) { app_t< messages::header >::write( *msg_header ); } }; /// accumulate several packets into one big output record struct app_all : public app_t< output_all > { app_all( const std::string& port, const comma::command_line_options& options ) : app_t( port, options ) {} output_all output; void handle( const messages::system_state* msg ) { memcpy( output.system_state.data(), msg->data(), messages::system_state::size ); } void handle( const messages::raw_sensors* msg ) { std::memcpy( output.raw_sensors.data(), msg->data(), messages::raw_sensors::size ); write( output ); } }; template< typename T > struct app_packet : public app_t< T > { app_packet( const std::string& port, const comma::command_line_options& options ) : app_t< T >( port, options ) {} void handle( const T* msg ) { app_t< T >::write( *msg ); } }; struct factory_i { virtual ~factory_i() {} virtual void output_fields() = 0; virtual void output_format() = 0; virtual void run( const std::string& input, const comma::command_line_options& options ) = 0; }; template<typename T> struct factory_t : public factory_i { typedef T type; void output_fields() { T::output_fields(); } void output_format() { T::output_format(); } void run( const std::string& input, const comma::command_line_options& options ) { T app( input, options ); app.process(); } }; template< typename T > struct description { comma::csv::input_stream< status_data > is; description( const comma::command_line_options& options ) : is( std::cin, comma::csv::options( options ) ) {} void process() { while( std::cin.good() ) { const status_data* p = is.read(); if( !p ) { break; } std::cout << T::string( p->status ) << std::endl; } } }; static void bash_completion( int argc, char** argv ) { std::cout << "--help --verbose" << " all raw-sensors system-state header" << " --device --baud-rate --sleep --output-fields --output-format --raw --stdin --description --binary-output" << std::endl; } int main( int argc, char** argv ) { try { comma::command_line_options options( argc, argv, usage ); if( options.exists( "--bash-completion" ) ) { bash_completion( argc, argv ); return 0; } std::vector< std::string > unnamed = options.unnamed( comma::csv::options::valueless_options() + ",--verbose,-v,--output-fields,--output-format,--raw,--stdin,--binary-output", "-.*" ); auto opt_description = options.optional< std::string >( "--description" ); if( opt_description ) { if( *opt_description == "system_status" ) { description< messages::system_status_description >( options ).process(); } else if( *opt_description == "filter_status" ) { description< messages::filter_status_description >( options ).process(); } else { COMMA_THROW( comma::exception, "invalid field for description. expected 'system_status' or 'filter_status', got " << *opt_description ); } return 0; } std::unique_ptr<factory_i> factory; if( options.exists( "--raw" ) ) { factory.reset( new factory_t< app_raw >() ); } else if( unnamed.size() != 1 ) { COMMA_THROW( comma::exception, "expected one unnamed arguement; got: " << unnamed.size() ); } else if( unnamed[0] == "system-state" ) { factory.reset( new factory_t< app_packet< messages::system_state > >() ); } else if( unnamed[0] == "raw-sensors" ) { factory.reset( new factory_t< app_packet< messages::raw_sensors > >() ); } else if( unnamed[0] == "header" ) { factory.reset( new factory_t< app_header >() ); } else if( unnamed[0] == "all" ) { factory.reset( new factory_t< app_all >() ); } else { COMMA_THROW( comma::exception, "expected <what>: header | raw-sensors | system-state | all; got: " << unnamed[0] );} if( options.exists( "--output-fields" ) ) { factory->output_fields(); return 0; } if( options.exists( "--output-format" ) ) { factory->output_format(); return 0; } options.assert_mutually_exclusive( "--stdin,--device" ); std::string input = options.exists( "--stdin" ) ? "-" : options.value< std::string >( "--device" ); factory->run( input, options ); return 0; } catch( snark::navigation::advanced_navigation::eois_exception& e ) { // normal exit on end of input stream comma::verbose << comma::verbose.app_name() << ": " << e.what() << std::endl; return 0; } catch( std::exception& ex ) { std::cerr << comma::verbose.app_name() << ": " << ex.what() << std::endl; } catch( ... ) { std::cerr << comma::verbose.app_name() << ": " << "unknown exception" << std::endl; } return 1; }
#include "minerva.h" #include <GLFW/glfw3.h> #include "vulkan.h" #include "window/window.h" void MvUpdate() { glfwPollEvents(); Vulkan::Get().drawFrame(); } bool MvShouldWindowClose(Window w) { return glfwWindowShouldClose(w.window); }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fidl/json_generator.h" #include "fidl/names.h" #include "fidl/types.h" namespace fidl { void JSONGenerator::Generate(const flat::Decl* decl) { Generate(decl->name); } void JSONGenerator::Generate(SourceSpan value) { EmitString(value.data()); } void JSONGenerator::Generate(NameSpan value) { GenerateObject([&]() { GenerateObjectMember("filename", value.filename, Position::kFirst); GenerateObjectMember("line", (uint32_t)value.position.line); GenerateObjectMember("column", (uint32_t)value.position.column); GenerateObjectMember("length", (uint32_t)value.length); }); } void JSONGenerator::Generate(const flat::ConstantValue& value) { switch (value.kind) { case flat::ConstantValue::Kind::kUint8: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<uint8_t>&>(value); EmitNumeric(static_cast<uint64_t>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kUint16: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<uint16_t>&>(value); EmitNumeric(static_cast<uint16_t>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kUint32: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<uint32_t>&>(value); EmitNumeric(static_cast<uint32_t>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kUint64: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<uint64_t>&>(value); EmitNumeric(static_cast<uint64_t>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kInt8: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<int8_t>&>(value); EmitNumeric(static_cast<int64_t>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kInt16: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<int16_t>&>(value); EmitNumeric(static_cast<int16_t>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kInt32: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<int32_t>&>(value); EmitNumeric(static_cast<int32_t>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kInt64: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<int64_t>&>(value); EmitNumeric(static_cast<int64_t>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kFloat32: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<float>&>(value); EmitNumeric(static_cast<float>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kFloat64: { auto numeric_constant = reinterpret_cast<const flat::NumericConstantValue<double>&>(value); EmitNumeric(static_cast<double>(numeric_constant), kAsString); break; } case flat::ConstantValue::Kind::kBool: { auto bool_constant = reinterpret_cast<const flat::BoolConstantValue&>(value); EmitBoolean(static_cast<bool>(bool_constant), kAsString); break; } case flat::ConstantValue::Kind::kString: { auto string_constant = reinterpret_cast<const flat::StringConstantValue&>(value); EmitLiteral(string_constant.value); break; } } // switch } void JSONGenerator::Generate(types::HandleSubtype value) { EmitString(NameHandleSubtype(value)); } void JSONGenerator::Generate(types::Nullability value) { switch (value) { case types::Nullability::kNullable: EmitBoolean(true); break; case types::Nullability::kNonnullable: EmitBoolean(false); break; } } void JSONGenerator::Generate(const raw::Identifier& value) { EmitString(value.span().data()); } void JSONGenerator::Generate(const flat::LiteralConstant& value) { GenerateObject([&]() { GenerateObjectMember("kind", NameRawLiteralKind(value.literal->kind), Position::kFirst); GenerateObjectMember("value", value.Value()); GenerateObjectMember("expression", value.literal->span().data()); }); } void JSONGenerator::Generate(const flat::Constant& value) { GenerateObject([&]() { // TODO(pascallouis): We should explore exposing these in the JSON IR, such that the // implicit bounds are made explicit by fidlc, rather than sprinkled throughout all // backends. // // For now, do not emit synthesized constants if (value.kind == flat::Constant::Kind::kSynthesized) return; GenerateObjectMember("kind", NameFlatConstantKind(value.kind), Position::kFirst); GenerateObjectMember("value", value.Value()); GenerateObjectMember("expression", value.span); switch (value.kind) { case flat::Constant::Kind::kIdentifier: { auto type = static_cast<const flat::IdentifierConstant*>(&value); GenerateObjectMember("identifier", type->name); break; } case flat::Constant::Kind::kLiteral: { auto& type = static_cast<const flat::LiteralConstant&>(value); GenerateObjectMember("literal", type); break; } case flat::Constant::Kind::kBinaryOperator: { // Avoid emitting a structure for binary operators in favor of "expression". break; } case flat::Constant::Kind::kSynthesized: break; } }); } void JSONGenerator::Generate(const flat::Type* value) { GenerateObject([&]() { GenerateObjectMember("kind", NameFlatTypeKind(value->kind), Position::kFirst); switch (value->kind) { case flat::Type::Kind::kArray: { auto type = static_cast<const flat::ArrayType*>(value); GenerateObjectMember("element_type", type->element_type); GenerateObjectMember("element_count", type->element_count->value); break; } case flat::Type::Kind::kVector: { auto type = static_cast<const flat::VectorType*>(value); GenerateObjectMember("element_type", type->element_type); if (*type->element_count < flat::Size::Max()) GenerateObjectMember("maybe_element_count", type->element_count->value); GenerateObjectMember("nullable", type->nullability); break; } case flat::Type::Kind::kString: { auto type = static_cast<const flat::StringType*>(value); if (*type->max_size < flat::Size::Max()) GenerateObjectMember("maybe_element_count", type->max_size->value); GenerateObjectMember("nullable", type->nullability); break; } case flat::Type::Kind::kHandle: { auto type = static_cast<const flat::HandleType*>(value); GenerateObjectMember("subtype", type->subtype); GenerateObjectMember( "rights", static_cast<const flat::NumericConstantValue<uint32_t>&>(type->rights->Value()).value); GenerateObjectMember("nullable", type->nullability); break; } case flat::Type::Kind::kRequestHandle: { auto type = static_cast<const flat::RequestHandleType*>(value); GenerateObjectMember("subtype", type->protocol_type->name); // TODO(fxb/43803) Add required and optional rights. GenerateObjectMember("nullable", type->nullability); break; } case flat::Type::Kind::kPrimitive: { auto type = static_cast<const flat::PrimitiveType*>(value); GenerateObjectMember("subtype", type->name); break; } case flat::Type::Kind::kIdentifier: { auto type = static_cast<const flat::IdentifierType*>(value); GenerateObjectMember("identifier", type->name); GenerateObjectMember("nullable", type->nullability); break; } } }); } void JSONGenerator::Generate(const raw::Attribute& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); if (value.value != "") GenerateObjectMember("value", value.value); else GenerateObjectMember("value", std::string_view()); }); } void JSONGenerator::Generate(const raw::AttributeList& value) { Generate(value.attributes); } void JSONGenerator::Generate(const raw::Ordinal64& value) { EmitNumeric(value.value); } void JSONGenerator::Generate(const flat::Name& value) { // These look like (when there is a library) // { "LIB.LIB.LIB", "ID" } // or (when there is not) // { "ID" } Generate(NameFlatName(value)); } void JSONGenerator::Generate(const flat::Bits& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateTypeAndFromTypeAlias(*value.subtype_ctor); // TODO(FIDL-324): When all numbers are wrapped as string, we can simply // call GenerateObjectMember directly. GenerateObjectPunctuation(Position::kSubsequent); EmitObjectKey("mask"); EmitNumeric(value.mask, kAsString); GenerateObjectMember("members", value.members); GenerateObjectMember("strict", value.strictness == types::Strictness::kStrict); }); } void JSONGenerator::Generate(const flat::Bits::Member& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); GenerateObjectMember("value", value.value); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); }); } void JSONGenerator::Generate(const flat::Const& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateTypeAndFromTypeAlias(*value.type_ctor); GenerateObjectMember("value", value.value); }); } void JSONGenerator::Generate(const flat::Enum& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); // TODO(FIDL-324): Due to legacy reasons, the 'type' of enums is actually // the primitive subtype, and therefore cannot use // GenerateTypeAndFromTypeAlias here. GenerateObjectMember("type", value.type->name); if (value.subtype_ctor->from_type_alias) GenerateObjectMember("experimental_maybe_from_type_alias", value.subtype_ctor->from_type_alias.value()); GenerateObjectMember("members", value.members); GenerateObjectMember("strict", value.strictness == types::Strictness::kStrict); if (value.strictness == types::Strictness::kFlexible) { if (value.unknown_value_signed) { GenerateObjectMember("maybe_unknown_value", value.unknown_value_signed.value()); } else { GenerateObjectMember("maybe_unknown_value", value.unknown_value_unsigned.value()); } } }); } void JSONGenerator::Generate(const flat::Enum::Member& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); GenerateObjectMember("value", value.value); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); }); } void JSONGenerator::Generate(const flat::Protocol& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateObjectMember("methods", value.all_methods); }); } void JSONGenerator::Generate(const flat::Protocol::MethodWithInfo& method_with_info) { assert(method_with_info.method != nullptr); const auto& value = *method_with_info.method; GenerateObject([&]() { GenerateObjectMember("ordinal", value.generated_ordinal64, Position::kFirst); GenerateObjectMember("name", value.name); GenerateObjectMember("location", NameSpan(value.name)); GenerateObjectMember("has_request", value.maybe_request != nullptr); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); if (value.maybe_request != nullptr) { GenerateRequest("maybe_request", *value.maybe_request); } GenerateObjectMember("has_response", value.maybe_response != nullptr); if (value.maybe_response != nullptr) { GenerateRequest("maybe_response", *value.maybe_response); } GenerateObjectMember("is_composed", method_with_info.is_composed); }); } void JSONGenerator::GenerateTypeAndFromTypeAlias(const flat::TypeConstructor& value, Position position) { GenerateObjectMember("type", value.type, position); if (value.from_type_alias) GenerateObjectMember("experimental_maybe_from_type_alias", value.from_type_alias.value()); } void JSONGenerator::GenerateRequest(const std::string& prefix, const flat::Struct& value) { // Temporarily hardcode the generation of request/response struct members to use the old // wire format, in order to maintain compatibility during the transition for fxb/7704. // This block of code is copied from JsonWriter::GenerateArray (with the difference // noted below), and will be removed once backends are updated to use anonymous structs. GenerateObjectPunctuation(Position::kSubsequent); EmitObjectKey(prefix); EmitArrayBegin(); if (value.members.begin() != value.members.end()) { Indent(); EmitNewlineWithIndent(); } for (auto it = value.members.begin(); it != value.members.end(); ++it) { if (it != value.members.begin()) EmitArraySeparator(); // call Generate with is_request_response = true on each struct member Generate(*it, true); } if (value.members.begin() != value.members.end()) { Outdent(); EmitNewlineWithIndent(); } EmitArrayEnd(); if (!value.members.empty()) { GenerateObjectMember(prefix + "_payload", value.name); } GenerateTypeShapes(prefix, value, true); } void JSONGenerator::Generate(const flat::Resource::Property& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); GenerateTypeAndFromTypeAlias(*value.type_ctor); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); }); } void JSONGenerator::Generate(const flat::Resource& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateTypeAndFromTypeAlias(*value.subtype_ctor); GenerateObjectMember("properties", value.properties); }); } void JSONGenerator::Generate(const flat::Service& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateObjectMember("members", value.members); }); } void JSONGenerator::Generate(const flat::Service::Member& value) { GenerateObject([&]() { GenerateTypeAndFromTypeAlias(*value.type_ctor, Position::kFirst); GenerateObjectMember("name", value.name); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); }); } void JSONGenerator::Generate(const flat::Struct& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); GenerateObjectMember("anonymous", value.is_request_or_response); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateObjectMember("members", value.members); GenerateObjectMember("resource", value.resourceness == types::Resourceness::kResource); GenerateTypeShapes(value); }); } void JSONGenerator::Generate(const flat::Struct* value) { Generate(*value); } void JSONGenerator::Generate(const flat::Struct::Member& value, bool is_request_or_response) { GenerateObject([&]() { GenerateTypeAndFromTypeAlias(*value.type_ctor, Position::kFirst); GenerateObjectMember("name", value.name); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); if (value.maybe_default_value) GenerateObjectMember("maybe_default_value", value.maybe_default_value); GenerateFieldShapes(value, is_request_or_response); }); } void JSONGenerator::Generate(const flat::Table& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateObjectMember("members", value.members); GenerateObjectMember("strict", value.strictness == types::Strictness::kStrict); GenerateObjectMember("resource", value.resourceness == types::Resourceness::kResource); GenerateTypeShapes(value); }); } void JSONGenerator::Generate(const flat::Table::Member& value) { GenerateObject([&]() { GenerateObjectMember("ordinal", *value.ordinal, Position::kFirst); if (value.maybe_used) { assert(!value.span); GenerateObjectMember("reserved", false); GenerateTypeAndFromTypeAlias(*value.maybe_used->type_ctor); GenerateObjectMember("name", value.maybe_used->name); GenerateObjectMember("location", NameSpan(value.maybe_used->name)); if (value.maybe_used->attributes) GenerateObjectMember("maybe_attributes", value.maybe_used->attributes); // TODO(FIDL-609): Support defaults on tables. } else { assert(value.span); GenerateObjectMember("reserved", true); GenerateObjectMember("location", NameSpan(value.span.value())); } }); } void JSONGenerator::Generate(const TypeShape& type_shape) { GenerateObject([&]() { GenerateObjectMember("inline_size", type_shape.inline_size, Position::kFirst); GenerateObjectMember("alignment", type_shape.alignment); GenerateObjectMember("depth", type_shape.depth); GenerateObjectMember("max_handles", type_shape.max_handles); GenerateObjectMember("max_out_of_line", type_shape.max_out_of_line); GenerateObjectMember("has_padding", type_shape.has_padding); GenerateObjectMember("has_flexible_envelope", type_shape.has_flexible_envelope); GenerateObjectMember("is_resource", type_shape.is_resource); }); } void JSONGenerator::Generate(const FieldShape& field_shape) { GenerateObject([&]() { GenerateObjectMember("offset", field_shape.offset, Position::kFirst); GenerateObjectMember("padding", field_shape.padding); }); } void JSONGenerator::Generate(const flat::Union& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateObjectMember("members", value.members); GenerateObjectMember("strict", value.strictness == types::Strictness::kStrict); GenerateObjectMember("resource", value.resourceness == types::Resourceness::kResource); GenerateTypeShapes(value); }); } void JSONGenerator::Generate(const flat::Union::Member& value) { GenerateObject([&]() { GenerateObjectMember("ordinal", value.ordinal, Position::kFirst); if (value.maybe_used) { assert(!value.span); GenerateObjectMember("reserved", false); GenerateObjectMember("name", value.maybe_used->name); GenerateTypeAndFromTypeAlias(*value.maybe_used->type_ctor); GenerateObjectMember("location", NameSpan(value.maybe_used->name)); if (value.maybe_used->attributes) GenerateObjectMember("maybe_attributes", value.maybe_used->attributes); } else { GenerateObjectMember("reserved", true); GenerateObjectMember("location", NameSpan(value.span.value())); } }); } void JSONGenerator::Generate(const flat::TypeConstructor::FromTypeAlias& value) { GenerateObject([&]() { GenerateObjectMember("name", value.decl->name, Position::kFirst); GenerateObjectPunctuation(Position::kSubsequent); EmitObjectKey("args"); // In preparation of template support, it is better to expose a // heterogenous argument list to backends, rather than the currently // limited internal view. EmitArrayBegin(); if (value.maybe_arg_type) { Indent(); EmitNewlineWithIndent(); Generate(value.maybe_arg_type->name); Outdent(); EmitNewlineWithIndent(); } EmitArrayEnd(); GenerateObjectMember("nullable", value.nullability); if (value.maybe_size) GenerateObjectMember("maybe_size", *value.maybe_size); }); } void JSONGenerator::Generate(const flat::TypeConstructor& value) { GenerateObject([&]() { GenerateObjectMember("name", value.type ? value.type->name : value.name, Position::kFirst); GenerateObjectPunctuation(Position::kSubsequent); EmitObjectKey("args"); // In preparation of template support, it is better to expose a // heterogenous argument list to backends, rather than the currently // limited internal view. EmitArrayBegin(); if (value.maybe_arg_type_ctor) { Indent(); EmitNewlineWithIndent(); Generate(*value.maybe_arg_type_ctor); Outdent(); EmitNewlineWithIndent(); } EmitArrayEnd(); GenerateObjectMember("nullable", value.nullability); if (value.maybe_size) GenerateObjectMember("maybe_size", value.maybe_size); if (value.handle_subtype) GenerateObjectMember("maybe_handle_subtype", value.handle_subtype.value()); if (value.handle_rights) GenerateObjectMember("handle_rights", value.handle_rights); }); } void JSONGenerator::Generate(const flat::TypeAlias& value) { GenerateObject([&]() { GenerateObjectMember("name", value.name, Position::kFirst); GenerateObjectMember("location", NameSpan(value.name)); if (value.attributes) GenerateObjectMember("maybe_attributes", value.attributes); GenerateObjectMember("partial_type_ctor", *value.partial_type_ctor); }); } void JSONGenerator::Generate(const flat::Library* library) { GenerateObject([&]() { auto library_name = flat::LibraryName(library, "."); GenerateObjectMember("name", library_name, Position::kFirst); GenerateDeclarationsMember(library); }); } void JSONGenerator::GenerateTypeShapes(const flat::Object& object) { GenerateTypeShapes("", object); } void JSONGenerator::GenerateTypeShapes(std::string prefix, const flat::Object& object, bool is_request_or_response) { if (prefix.size() > 0) { prefix.push_back('_'); } // NOTE: while the transition for fxb/7024 is ongoing, we need to treat request/responses // specially as before, but this will be removed once the transition is complete const auto& v1 = is_request_or_response ? WireFormat::kV1NoEe : WireFormat::kV1Header; GenerateObjectMember(prefix + "type_shape_v1", TypeShape(object, v1)); } void JSONGenerator::GenerateFieldShapes(const flat::Struct::Member& struct_member, bool is_request_or_response) { // NOTE: while the transition for fxb/7024 is ongoing, we need to treat request/responses // specially as before, but this will be removed once the transition is complete const auto& v1 = is_request_or_response ? WireFormat::kV1NoEe : WireFormat::kV1Header; GenerateObjectMember("field_shape_v1", FieldShape(struct_member, v1)); } void JSONGenerator::GenerateDeclarationsEntry(int count, const flat::Name& name, std::string_view decl) { if (count == 0) { Indent(); EmitNewlineWithIndent(); } else { EmitObjectSeparator(); } EmitObjectKey(NameFlatName(name)); EmitString(decl); } void JSONGenerator::GenerateDeclarationsMember(const flat::Library* library, Position position) { GenerateObjectPunctuation(position); EmitObjectKey("declarations"); GenerateObject([&]() { int count = 0; for (const auto& decl : library->bits_declarations_) GenerateDeclarationsEntry(count++, decl->name, "bits"); for (const auto& decl : library->const_declarations_) GenerateDeclarationsEntry(count++, decl->name, "const"); for (const auto& decl : library->enum_declarations_) GenerateDeclarationsEntry(count++, decl->name, "enum"); for (const auto& decl : library->resource_declarations_) GenerateDeclarationsEntry(count++, decl->name, "experimental_resource"); for (const auto& decl : library->protocol_declarations_) GenerateDeclarationsEntry(count++, decl->name, "interface"); for (const auto& decl : library->service_declarations_) GenerateDeclarationsEntry(count++, decl->name, "service"); for (const auto& decl : library->struct_declarations_) GenerateDeclarationsEntry(count++, decl->name, "struct"); for (const auto& decl : library->table_declarations_) GenerateDeclarationsEntry(count++, decl->name, "table"); for (const auto& decl : library->union_declarations_) GenerateDeclarationsEntry(count++, decl->name, "union"); for (const auto& decl : library->type_alias_declarations_) GenerateDeclarationsEntry(count++, decl->name, "type_alias"); }); } namespace { struct LibraryComparator { bool operator()(const flat::Library* lhs, const flat::Library* rhs) const { assert(!lhs->name().empty()); assert(!rhs->name().empty()); return lhs->name() < rhs->name(); } }; std::set<const flat::Library*, LibraryComparator> TransitiveDependencies( const flat::Library* library) { std::set<const flat::Library*, LibraryComparator> dependencies; auto add_dependency = [&](const flat::Library* dep_library) { if (!dep_library->HasAttribute("Internal")) { dependencies.insert(dep_library); } }; for (const auto& dep_library : library->dependencies()) { add_dependency(dep_library); } // Discover additional dependencies that are required to support // cross-library protocol composition. for (const auto& protocol : library->protocol_declarations_) { for (const auto method_with_info : protocol->all_methods) { if (auto request = method_with_info.method->maybe_request) { for (const auto& member : request->members) { if (auto dep_library = member.type_ctor->name.library()) { add_dependency(dep_library); } } } if (auto response = method_with_info.method->maybe_response) { for (const auto& member : response->members) { if (auto dep_library = member.type_ctor->name.library()) { add_dependency(dep_library); } } } add_dependency(method_with_info.method->owning_protocol->name.library()); } } dependencies.erase(library); return dependencies; } // Return all structs that should be emitted in the JSON IR, which consists of // two parts: all structs from this library (which includes all struct definitions // and request/response payloads defined in this library), plus any request/response // payloads defined in other libraries that are composed into a protocol in this // library. std::vector<const flat::Struct*> AllStructs(const flat::Library* library) { std::vector<const flat::Struct*> all_structs; for (const auto& struct_decl : library->struct_declarations_) { if (struct_decl->is_request_or_response && struct_decl->members.empty()) continue; all_structs.push_back(struct_decl.get()); } for (const auto& protocol : library->protocol_declarations_) { for (const auto method_with_info : protocol->all_methods) { // these are already included in the library's struct declarations if (!method_with_info.is_composed) continue; const auto& method = method_with_info.method; if (method->maybe_request && !method->maybe_request->members.empty()) { all_structs.push_back(method->maybe_request); } if (method->maybe_response && !method->maybe_response->members.empty()) { all_structs.push_back(method->maybe_response); } } } return all_structs; } } // namespace std::ostringstream JSONGenerator::Produce() { ResetIndentLevel(); GenerateObject([&]() { GenerateObjectMember("version", std::string_view("0.0.1"), Position::kFirst); GenerateObjectMember("name", LibraryName(library_, ".")); if (auto attributes = library_->attributes(); attributes) { GenerateObjectMember("maybe_attributes", *attributes); } GenerateObjectPunctuation(Position::kSubsequent); EmitObjectKey("library_dependencies"); GenerateArray(TransitiveDependencies(library_)); GenerateObjectMember("bits_declarations", library_->bits_declarations_); GenerateObjectMember("const_declarations", library_->const_declarations_); GenerateObjectMember("enum_declarations", library_->enum_declarations_); GenerateObjectMember("experimental_resource_declarations", library_->resource_declarations_); GenerateObjectMember("interface_declarations", library_->protocol_declarations_); GenerateObjectMember("service_declarations", library_->service_declarations_); GenerateObjectMember("struct_declarations", AllStructs(library_)); GenerateObjectMember("table_declarations", library_->table_declarations_); GenerateObjectMember("union_declarations", library_->union_declarations_); GenerateObjectMember("type_alias_declarations", library_->type_alias_declarations_); // The library's declaration_order_ contains all the declarations for all // transitive dependencies. The backend only needs the declaration order // for this specific library. std::vector<std::string> declaration_order; for (flat::Decl* decl : library_->declaration_order_) { if (decl->kind == flat::Decl::Kind::kStruct) { auto struct_decl = static_cast<flat::Struct*>(decl); if (struct_decl->is_request_or_response) continue; } if (decl->name.library() == library_) declaration_order.push_back(NameFlatName(decl->name)); } GenerateObjectMember("declaration_order", declaration_order); GenerateDeclarationsMember(library_); }); GenerateEOF(); return std::move(json_file_); } } // namespace fidl
#include <iostream> using namespace std; using ll = int64_t; // Check Nim Game (I and II) readme files to understand the concept int main() { ll T; cin >> T; for (ll cas = 1; cas <= T; cas++) { ll n; cin >> n; ll ans = 0; for (ll i = 0; i < n; i++) { ll x; cin >> x; if (i % 2 == 1) { ans ^= x; } } cout << (ans == 0 ? "second" : "first") << endl; } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // // SequenceParser.cpp : Parses the UCI format using a custom state machine (for speed) // #include "stdafx.h" #include <stdexcept> #include <stdint.h> #include "Basics.h" #include "SequenceParser.h" #include "fileutil.h" using namespace Microsoft::MSR::CNTK; // SetState for a particular value template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::SetState(int value, ParseState current_state, ParseState next_state) { DWORD ul = (DWORD) next_state; int range_shift = ((int)current_state) << 8; m_stateTable[range_shift + value] = ul; } // SetStateRange - set states transitions for a range of values template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::SetStateRange(int value1, int value2, ParseState current_state, ParseState next_state) { DWORD ul = (DWORD) next_state; int range_shift = ((int)current_state) << 8; for (int value = value1; value <= value2; value++) { m_stateTable[range_shift + value] = ul; } } // SetupStateTables - setup state transition tables for each state // each state has a block of 256 states indexed by the incoming character template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::SetupStateTables() { // ========================= // STATE = WHITESPACE // ========================= SetStateRange(0, 255, Whitespace, Label); SetStateRange('0', '9', Whitespace, WholeNumber); SetState('-', Whitespace, Sign); SetState('+', Whitespace, Sign); // whitespace SetState(' ', Whitespace, Whitespace); SetState('\t', Whitespace, Whitespace); SetState('\r', Whitespace, Whitespace); SetState(':', Whitespace, Whitespace); // intepret ':' as white space because it's a divider SetState('\n', Whitespace, EndOfLine); // ========================= // STATE = NEGATIVE_SIGN // ========================= SetStateRange(0, 255, Sign, Label); SetStateRange('0', '9', Sign, WholeNumber); // whitespace SetState(' ', Sign, Whitespace); SetState('\t', Sign, Whitespace); SetState('\r', Sign, Whitespace); SetState('\n', Sign, EndOfLine); // ========================= // STATE = NUMBER // ========================= SetStateRange(0, 255, WholeNumber, Label); SetStateRange('0', '9', WholeNumber, WholeNumber); SetState('.', WholeNumber, Period); SetState('e', WholeNumber, TheLetterE); SetState('E', WholeNumber, TheLetterE); // whitespace SetState(' ', WholeNumber, Whitespace); SetState('\t', WholeNumber, Whitespace); SetState('\r', WholeNumber, Whitespace); SetState(':', WholeNumber, Whitespace); // Add for 1234:0.9 usage in Sequences SetState('\n', WholeNumber, EndOfLine); // ========================= // STATE = PERIOD // ========================= SetStateRange(0, 255, Period, Label); SetStateRange('0', '9', Period, Remainder); // whitespace SetState(' ', Period, Whitespace); SetState('\t', Period, Whitespace); SetState('\r', Period, Whitespace); SetState('\n', Period, EndOfLine); // ========================= // STATE = REMAINDER // ========================= SetStateRange(0, 255, Remainder, Label); SetStateRange('0', '9', Remainder, Remainder); SetState('e', Remainder, TheLetterE); SetState('E', Remainder, TheLetterE); // whitespace SetState(' ', Remainder, Whitespace); SetState('\t', Remainder, Whitespace); SetState('\r', Remainder, Whitespace); SetState(':', Remainder, Whitespace); // Add for 1234:0.9 usage in Sequences SetState('\n', Remainder, EndOfLine); // ========================= // STATE = THE_LETTER_E // ========================= SetStateRange(0, 255, TheLetterE, Label); SetStateRange('0', '9', TheLetterE, Exponent); SetState('-', TheLetterE, ExponentSign); SetState('+', TheLetterE, ExponentSign); // whitespace SetState(' ', TheLetterE, Whitespace); SetState('\t', TheLetterE, Whitespace); SetState('\r', TheLetterE, Whitespace); SetState('\n', TheLetterE, EndOfLine); // ========================= // STATE = EXPONENT_NEGATIVE_SIGN // ========================= SetStateRange(0, 255, ExponentSign, Label); SetStateRange('0', '9', ExponentSign, Exponent); // whitespace SetState(' ', ExponentSign, Whitespace); SetState('\t', ExponentSign, Whitespace); SetState('\r', ExponentSign, Whitespace); SetState('\n', ExponentSign, EndOfLine); // ========================= // STATE = EXPONENT // ========================= SetStateRange(0, 255, Exponent, Label); SetStateRange('0', '9', Exponent, Exponent); // whitespace SetState(' ', Exponent, Whitespace); SetState('\t', Exponent, Whitespace); SetState('\r', Exponent, Whitespace); SetState(':', Exponent, Whitespace); SetState('\n', Exponent, EndOfLine); // ========================= // STATE = END_OF_LINE // ========================= SetStateRange(0, 255, EndOfLine, Label); SetStateRange('0', '9', EndOfLine, WholeNumber); SetState('-', EndOfLine, Sign); SetState('\n', EndOfLine, EndOfLine); // whitespace SetState(' ', EndOfLine, Whitespace); SetState('\t', EndOfLine, Whitespace); SetState('\r', EndOfLine, Whitespace); // ========================= // STATE = LABEL // ========================= SetStateRange(0, 255, Label, Label); SetState('\n', Label, EndOfLine); // whitespace SetState(' ', Label, Whitespace); SetState('\t', Label, Whitespace); SetState('\r', Label, Whitespace); SetState(':', Label, Whitespace); // ========================= // STATE = LINE_COUNT_EOL // ========================= SetStateRange(0, 255, LineCountEOL, LineCountOther); SetState('\n', LineCountEOL, LineCountEOL); // ========================= // STATE = LINE_COUNT_OTHER // ========================= SetStateRange(0, 255, LineCountOther, LineCountOther); SetState('\n', LineCountOther, LineCountEOL); } // reset all line state variables template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::PrepareStartLine() { m_numbersConvertedThisLine = 0; m_labelsConvertedThisLine = 0; m_elementsConvertedThisLine = 0; m_spaceDelimitedStart = m_byteCounter; m_spaceDelimitedMax = m_byteCounter; m_lastLabelIsString = false; m_beginSequence = m_endSequence = false; } // reset all number accumulation variables template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::PrepareStartNumber() { m_partialResult = 0; m_builtUpNumber = 0; m_divider = 0; m_wholeNumberMultiplier = 1; m_exponentMultiplier = 1; } // reset all state variables to start reading at a new position template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::PrepareStartPosition(size_t position) { m_current_state = Whitespace; m_byteCounter = position; // must come before PrepareStartLine... m_bufferStart = position; // prepare state machine for new number and new line PrepareStartNumber(); PrepareStartLine(); m_totalNumbersConverted = 0; m_totalLabelsConverted = 0; } // SequenceParser constructor template <typename NumType, typename LabelType> SequenceParser<NumType, LabelType>::SequenceParser() { Init(); } // setup all the state variables and state tables for state machine template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::Init() { PrepareStartPosition(0); m_fileBuffer = NULL; m_pFile = NULL; m_stateTable = new DWORD[AllStateMax * 256]; SetupStateTables(); } // Parser destructor template <typename NumType, typename LabelType> SequenceParser<NumType, LabelType>::~SequenceParser() { delete m_stateTable; delete m_fileBuffer; if (m_pFile) fclose(m_pFile); } // DoneWithLabel - Called when a string label is found template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::DoneWithLabel() { // if we haven't set the max yet, use the current byte Counter if (m_spaceDelimitedMax <= m_spaceDelimitedStart) m_spaceDelimitedMax = m_byteCounter; { std::string label((LPCSTR) &m_fileBuffer[m_spaceDelimitedStart - m_bufferStart], m_spaceDelimitedMax - m_spaceDelimitedStart); m_labelsConvertedThisLine++; m_elementsConvertedThisLine++; m_lastLabelIsString = true; } PrepareStartNumber(); } // Called when a number is complete template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::DoneWithValue() { // if we are storing it if (m_numbers != NULL) { NumType FinalResult = 0; if (m_current_state == Exponent) { FinalResult = (NumType)(m_partialResult * pow(10.0, m_exponentMultiplier * m_builtUpNumber)); } else if (m_divider != 0) { FinalResult = (NumType)(m_partialResult + (m_builtUpNumber / m_divider)); } else { FinalResult = (NumType) m_builtUpNumber; } FinalResult = (NumType)(FinalResult * m_wholeNumberMultiplier); // TODO: In sequence reader we probably don't need to store numbers in labels (we'll see) // if it's a label, store in label location instead of number location // int index = m_elementsConvertedThisLine; // if (m_startLabels <= index && index < m_startLabels + m_dimLabels) // { // StoreLabel(FinalResult); // } // if (m_startFeatures <= index && index < m_startFeatures + m_dimFeatures) { m_numbers->push_back(FinalResult); m_totalNumbersConverted++; m_numbersConvertedThisLine++; m_elementsConvertedThisLine++; m_lastLabelIsString = false; } } PrepareStartNumber(); } // store label is specialized by LabelType template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::StoreLabel(NumType value) { m_labels->push_back((LabelType) value); m_totalNumbersConverted++; m_numbersConvertedThisLine++; m_elementsConvertedThisLine++; m_lastLabelIsString = false; } // StoreLastLabel - store the last label (for numeric types), tranfers to label vector // string label types handled in specialization template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::StoreLastLabel() { assert(!m_lastLabelIsString); // file format error, last label was a string... NumType value = m_numbers->back(); m_numbers->pop_back(); m_labels->push_back((LabelType) value); } // GetFilePosition - Get the current file position in the text file // returns current position in the file template <typename NumType, typename LabelType> int64_t SequenceParser<NumType, LabelType>::GetFilePosition() { int64_t position = _ftelli64(m_pFile); if (position == -1L) RuntimeError("SequenceParser::GetFilePosition - error retrieving file position in file"); return position; } // SetFilePosition - Set the current file position from the beginning of the file, and read in the first block of data // state machine mode will be initialized similar to the beginning of the file // it is recommended that only return values from GetFilePosition() known to be the start of a line // and zero be passed to this function // TODO: Is this ever called with anything other than 0? template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::SetFilePosition(int64_t position) { int rc = _fseeki64(m_pFile, position, SEEK_SET); if (rc) RuntimeError("SequenceParser::SetFilePosition - error seeking in file"); // setup state machine to start at this position PrepareStartPosition(position); // read in the first buffer of data from this position, first buffer is expected to be read after a reposition UpdateBuffer(); // FUTURE: in debug we could validate the value is either 0, or the previous character is a '\n' } // HasMoreData - test if the current dataset have more data, or just whitespace // returns - true if it has more data, false if not template <typename NumType, typename LabelType> bool SequenceParser<NumType, LabelType>::HasMoreData() { long long byteCounter = m_byteCounter; size_t bufferIndex = m_byteCounter - m_bufferStart; // test without moving parser state for (; byteCounter < m_fileSize; byteCounter++, bufferIndex++) { // if we reach the end of the buffer, just assume we have more data // won't be right 100% of the time, but close enough if (bufferIndex >= m_bufferSize) return true; char ch = m_fileBuffer[bufferIndex]; ParseState nextState = (ParseState) m_stateTable[(Whitespace << 8) + ch]; if (!(nextState == Whitespace || nextState == EndOfLine)) return true; } return false; } // UpdateBuffer - load the next buffer full of data // returns - number of records read template <typename NumType, typename LabelType> size_t SequenceParser<NumType, LabelType>::UpdateBuffer() { // state machine might want to look back this far, so copy to beginning size_t saveBytes = m_byteCounter - m_spaceDelimitedStart; assert(saveBytes < m_bufferSize); if (saveBytes) { memcpy_s(m_fileBuffer, m_bufferSize, &m_fileBuffer[m_byteCounter - m_bufferStart - saveBytes], saveBytes); m_bufferStart = m_byteCounter - saveBytes; } // read the next block size_t bytesToRead = min(m_bufferSize, m_fileSize - m_bufferStart) - saveBytes; size_t bytesRead = fread(m_fileBuffer + saveBytes, 1, bytesToRead, m_pFile); if (bytesRead == 0 && ferror(m_pFile)) RuntimeError("SequenceParser::UpdateBuffer - error reading file"); return bytesRead; } template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::SetParseMode(ParseMode mode) { // if already in this mode, nothing to do if (m_parseMode == mode) return; // switching modes if (mode == ParseLineCount) m_current_state = LineCountOther; else { m_current_state = Whitespace; PrepareStartLine(); PrepareStartNumber(); } m_parseMode = mode; } // SetTraceLevel - Set the level of screen output // traceLevel - traceLevel, zero means no output, 1 epoch related output, > 1 all output template <typename NumType, typename LabelType> void SequenceParser<NumType, LabelType>::SetTraceLevel(int traceLevel) { m_traceLevel = traceLevel; } // StoreLabel - string version gets last space delimited string and stores in labels vector template <> void SequenceParser<float, std::string>::StoreLabel(float /*finalResult*/) { // for LabelFirst, Max will not be set yet, but the current byte counter is the Max, so set it if (m_spaceDelimitedMax <= m_spaceDelimitedStart) m_spaceDelimitedMax = m_byteCounter; std::string label((LPCSTR) &m_fileBuffer[m_spaceDelimitedStart - m_bufferStart], m_spaceDelimitedMax - m_spaceDelimitedStart); if (!m_beginSequence && EqualCI(label, m_beginTag)) m_beginSequence = true; if (!m_endSequence && EqualCI(label, m_endTag)) m_endSequence = true; m_labels->push_back(move(label)); m_labelsConvertedThisLine++; m_elementsConvertedThisLine++; m_lastLabelIsString = true; } // DoneWithLabel - string version stores string label template <> void SequenceParser<float, std::string>::DoneWithLabel() { if (m_labels != NULL) StoreLabel(0); // store the string label PrepareStartNumber(); } // StoreLastLabel - string version template <> void SequenceParser<float, std::string>::StoreLastLabel() { // see if it was already stored as a string label if (m_lastLabelIsString) return; StoreLabel(0); // we already stored a numeric version of this label in the numbers array // so get rid of that, the user wants it as a string m_numbers->pop_back(); PrepareStartNumber(); } // NOTE: Current code is identical to float, don't know how to specialize with template parameter that only covers one parameter // StoreLabel - string version gets last space delimited string and stores in labels vector template <> void SequenceParser<double, std::string>::StoreLabel(double /*finalResult*/) { // for LabelFirst, Max will not be set yet, but the current byte counter is the Max, so set it if (m_spaceDelimitedMax <= m_spaceDelimitedStart) m_spaceDelimitedMax = m_byteCounter; std::string label((LPCSTR) &m_fileBuffer[m_spaceDelimitedStart - m_bufferStart], m_spaceDelimitedMax - m_spaceDelimitedStart); if (!m_beginSequence && EqualCI(label, m_beginTag)) m_beginSequence = true; if (!m_endSequence && EqualCI(label, m_endTag)) m_endSequence = true; m_labels->push_back(move(label)); m_labelsConvertedThisLine++; m_elementsConvertedThisLine++; m_lastLabelIsString = true; } // DoneWithLabel - string version stores string label template <> void SequenceParser<double, std::string>::DoneWithLabel() { if (m_labels != NULL) StoreLabel(0); // store the string label PrepareStartNumber(); } // StoreLastLabel - string version template <> void SequenceParser<double, std::string>::StoreLastLabel() { // see if it was already stored as a string label if (m_lastLabelIsString) return; StoreLabel(0); // we already stored a numeric version of this label in the numbers array // so get rid of that, the user wants it as a string m_numbers->pop_back(); PrepareStartNumber(); } #ifdef STANDALONE int wmain(int argc, wchar_t *argv[]) { SequenceParser<double, int> parser; std::vector<double> values; values.reserve(784000 * 6); std::vector<int> labels; labels.reserve(60000); parser.ParseInit(L"c:\\speech\\mnist\\mnist_train.txt", LabelFirst); // parser.ParseInit("c:\\speech\\parseTest.txt", LabelNone); int records = 0; do { int recordsRead = parser.Parse(10000, &values, &labels); if (recordsRead < 10000) parser.SetFilePosition(0); // go around again records += recordsRead; values.clear(); labels.clear(); } while (records < 150000); return records; } #endif // instantiate UCI parsers for supported types template class SequenceParser<float, int>; template class SequenceParser<float, float>; template class SequenceParser<float, std::string>; template class SequenceParser<double, int>; template class SequenceParser<double, double>; template class SequenceParser<double, std::string>; //template <typename NumType, typename LabelType> //void LMBatchSequenceParser<NumType, LabelType>::ParseInit(LPCWSTR fileName, size_t dimFeatures, size_t dimLabelsIn, size_t dimLabelsOut, std::string beginSequenceIn /*="<s>"*/, std::string endSequenceIn /*="</s>"*/, std::string beginSequenceOut /*="O"*/, std::string endSequenceOut /*="O"*/) //{ // ::LMSequenceParser<NumType, LabelType>::ParseInit(fileName, dimFeatures, dimLabelsIn, dimLabelsOut, beginSequenceIn, endSequenceIn, beginSequenceOut, endSequenceOut); //} template <typename NumType, typename LabelType> long LMBatchSequenceParser<NumType, LabelType>::Parse(size_t recordsRequested, std::vector<LabelType> *labels, std::vector<NumType> *numbers, std::vector<SequencePosition> *seqPos) { size_t linecnt = (size_t) ::LMSequenceParser<NumType, LabelType>::Parse(recordsRequested, labels, numbers, seqPos); // create array of SentenceInfo structures, one per read input line size_t prvat = 0; size_t i = 0; for (auto ptr = seqPos->begin(); ptr != seqPos->end(); ptr++, i++) { SentenceInfo stinfo; stinfo.sBegin = prvat; size_t sEnd = ptr->labelPos; stinfo.sLen = sEnd - stinfo.sBegin; mSentenceIndex2SentenceInfo.push_back(stinfo); prvat = ptr->labelPos; } assert(mSentenceIndex2SentenceInfo.size() == linecnt); return (long) linecnt; // TODO: change to size_t } template class LMBatchSequenceParser<float, std::string>; template class LMBatchSequenceParser<double, std::string>;
// Copyright 2021 Tamas Eisenberger <e.tamas@iwstudio.hu> // // 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. #ifndef __IWS_REACTOR_TYPED_CONTRACT_HPP__ #define __IWS_REACTOR_TYPED_CONTRACT_HPP__ #include "contract_base.hpp" namespace iws { namespace reactor { template<typename T> class typed_contract : public contract_base { public: typed_contract(); explicit typed_contract(reactor *r_inst); }; template<typename T> typed_contract<T>::typed_contract() : contract_base() { } template<typename T> typed_contract<T>::typed_contract(reactor *r_inst) : contract_base(r_inst) { } } // namespace reactor } // namespace iws #endif //__IWS_REACTOR_TYPED_CONTRACT_HPP__
#include <iostream> #include <cstdlib> #include <cmath> #include <complex> using std::complex; #ifdef _OPENMP #include <omp.h> #else int omp_get_num_threads() {return 1;} #endif bool almost_equal(complex<double> x, complex<double> gold, float tol) { return std::abs(gold) * (1-tol) <= std::abs(x) && std::abs(x) <= std::abs(gold) * (1 + tol); } #pragma omp declare reduction(+: complex<double>: omp_out += omp_in) void test_target_teams__distribute__parallel__simd() { const int N0 { 512 }; const int N1 { 512 }; const complex<double> expected_value { N0*N1 }; complex<double> counter_N0{}; #pragma omp target teams map(tofrom: counter_N0) reduction(+: counter_N0) #pragma omp distribute for (int i0 = 0 ; i0 < N0 ; i0++ ) { #pragma omp parallel reduction(+: counter_N0) { #pragma omp simd reduction(+: counter_N0) for (int i1 = 0 ; i1 < N1 ; i1++ ) { counter_N0 = counter_N0 + complex<double> { double { 1. } / omp_get_num_threads() }; } } } if (!almost_equal(counter_N0, expected_value, 0.1)) { std::cerr << "Expected: " << expected_value << " Got: " << counter_N0 << std::endl; std::exit(112); } } int main() { test_target_teams__distribute__parallel__simd(); }