text
stringlengths
500
20k
source
stringclasses
27 values
lang
stringclasses
3 values
char_count
int64
500
20k
word_count
int64
4
19.8k
#include <SDL_image.h> #include <SDL_mixer.h> #include <SDL_ttf.h> #include <iostream> #include "Game.h" #include "Scenes/LevelScene.h" #include "Scenes/MenuScene.h" namespace bomberman { Game::Game(const std::string& windowName, const int width, const int height) : windowWidth(width), windowHeight(height) { // let's init SDL2 if(SDL_Init(SDL_INIT_VIDEO) != 0) { std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl; return; } // let's init SDL2 TTF if(TTF_Init() != 0) { std::cout << "TTF_Init Error: " << TTF_GetError() << std::endl; return; } // let's init SDL2 Image if(!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) { std::cout << "IMG_Init Error: " << IMG_GetError() << std::endl; return; } // let's init SDL2 Mixer if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) { std::cout << "Mix_OpenAudio Error: " << Mix_GetError() << std::endl; return; } // create a window window = SDL_CreateWindow(windowName.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); if(!window) { std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; return; } // create a renderer for window renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(renderer == nullptr) { std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl; return; } // we need new size due to possible high resolution on mac and ios int w, h; SDL_GetRendererOutputSize(renderer, &w, &h); windowWidth = w; windowHeight = h; assetManager = new AssetManager(); sceneManager = new SceneManager(); } Game::~Game() { delete sceneManager; delete assetManager; // delete SDL2 C pointers SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); // SDL2 finish Mix_CloseAudio(); IMG_Quit(); TTF_Quit(); SDL_Quit(); } void Game::run() { if(isRunning) { return; } isRunning = true; // load assets assetManager->load(renderer); // create menu scene sceneManager->addScene("menu", std::make_shared<MenuScene>(this)); sceneManager->activateScene("menu"); SDL_Event event; while(isRunning) { // check SDL2 events while(SDL_PollEvent(&event)) { // send event to current scene sceneManager->onEvent(event); // stop loop on quit if(event.type == SDL_QUIT) { stop(); } } // calculate delta Uint32 tickTime = SDL_GetTicks(); Uint32 delta = tickTime - lastTickTime; lastTickTime = tickTime; // update current scene sceneManager->update(delta); // clear the screen SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderClear(renderer); // draw current scene sceneManager->draw(); // flip the backbuffer SDL_RenderPresent(renderer); } } void Game::stop() { isRunning = false; } int Game::getWindowWidth() const { return windowWidth; } int Game::getWindowHeight() const { return windowHeight; } SDL_Renderer* Game::getRenderer() const { return renderer; } SceneManager* Game::getSceneManager() const { return sceneManager; } AssetManager* Game::getAssetManager() const { return assetManager; } } // namespace bomberman
c++
code
4,180
746
#include <iostream> #include <string> #include <thread> #include <chrono> #include "rclcpp/node.hpp" #include "protocol/msg/test.hpp" int main(int argc, char ** argv) { std::cout << "hello, publisher!" << std::endl; rclcpp::init(argc, argv); auto node_ptr = rclcpp::Node::make_shared("test_publisher"); auto pub_ptr = node_ptr->create_publisher<protocol::msg::Test>("test_topic", 10); protocol::msg::Test test_msg; while (rclcpp::ok()) { test_msg.a++; // test_msg.b = 1; test_msg.c = std::string("hello, topic!"); pub_ptr->publish(test_msg); std::this_thread::sleep_for(std::chrono::seconds(1)); } rclcpp::shutdown(); }
c++
code
661
195
// // Copyright 2018 ZetaSQL Authors // Copyright 2017 The Abseil 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. // // This file contains string processing functions related to // numeric values. #include "zetasql/base/string_numbers.h" #include <cassert> #include <cstdint> #include <limits> #include <cstdint> #include "absl/strings/ascii.h" #include "absl/strings/string_view.h" namespace zetasql_base { namespace { // Represents integer values of digits. // Uses 36 to indicate an invalid character since we support // bases up to 36. static const int8_t kAsciiToInt[256] = { 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // 16 36s. 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 36, 36, 36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36, 36, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36}; // Parse the sign and optional hex or oct prefix in text. inline bool safe_parse_sign_and_base(absl::string_view* text /*inout*/, int* base_ptr /*inout*/, bool* negative_ptr /*output*/) { if (text->data() == nullptr) { return false; } const char* start = text->data(); const char* end = start + text->size(); int base = *base_ptr; // Consume whitespace. while (start < end && absl::ascii_isspace(start[0])) { ++start; } while (start < end && absl::ascii_isspace(end[-1])) { --end; } if (start >= end) { return false; } // Consume sign. *negative_ptr = (start[0] == '-'); if (*negative_ptr || start[0] == '+') { ++start; if (start >= end) { return false; } } // Consume base-dependent prefix. // base 0: "0x" -> base 16, "0" -> base 8, default -> base 10 // base 16: "0x" -> base 16 // Also validate the base. if (base == 0) { if (end - start >= 2 && start[0] == '0' && (start[1] == 'x' || start[1] == 'X')) { base = 16; start += 2; if (start >= end) { // "0x" with no digits after is invalid. return false; } } else if (end - start >= 1 && start[0] == '0') { base = 8; start += 1; } else { base = 10; } } else if (base == 16) { if (end - start >= 2 && start[0] == '0' && (start[1] == 'x' || start[1] == 'X')) { start += 2; if (start >= end) { // "0x" with no digits after is invalid. return false; } } } else if (base >= 2 && base <= 36) { // okay } else { return false; } *text = absl::string_view(start, end - start); *base_ptr = base; return true; } // Consume digits. // // The classic loop: // // for each digit // value = value * base + digit // value *= sign // // The classic loop needs overflow checking. It also fails on the most // negative integer, -2147483648 in 32-bit two's complement representation. // // My improved loop: // // if (!negative) // for each digit // value = value * base // value = value + digit // else // for each digit // value = value * base // value = value - digit // // Overflow checking becomes simple. // Lookup tables per IntType: // vmax/base and vmin/base are precomputed because division costs at least 8ns. // TODO: Doing this per base instead (i.e. an array of structs, not a // struct of arrays) would probably be better in terms of d-cache for the most // commonly used bases. template <typename IntType> struct LookupTables { static const IntType kVmaxOverBase[]; static const IntType kVminOverBase[]; }; // An array initializer macro for X/base where base in [0, 36]. // However, note that lookups for base in [0, 1] should never happen because // base has been validated to be in [2, 36] by safe_parse_sign_and_base(). #define X_OVER_BASE_INITIALIZER(X) \ { \ 0, 0, X / 2, X / 3, X / 4, X / 5, X / 6, X / 7, X / 8, X / 9, X / 10, \ X / 11, X / 12, X / 13, X / 14, X / 15, X / 16, X / 17, X / 18, \ X / 19, X / 20, X / 21, X / 22, X / 23, X / 24, X / 25, X / 26, \ X / 27, X / 28, X / 29, X / 30, X / 31, X / 32, X / 33, X / 34, \ X / 35, X / 36, \ } template <typename IntType> const IntType LookupTables<IntType>::kVmaxOverBase[] = X_OVER_BASE_INITIALIZER(std::numeric_limits<IntType>::max()); template <typename IntType> const IntType LookupTables<IntType>::kVminOverBase[] = X_OVER_BASE_INITIALIZER(std::numeric_limits<IntType>::min()); #undef X_OVER_BASE_INITIALIZER template <typename IntType> inline bool safe_parse_positive_int(absl::string_view text, int base, IntType* value_p) { IntType value = 0; const IntType vmax = std::numeric_limits<IntType>::max(); assert(vmax > 0); assert(base >= 0); assert(vmax >= static_cast<IntType>(base)); const IntType vmax_over_base = LookupTables<IntType>::kVmaxOverBase[base]; const char* start = text.data(); const char* end = start + text.size(); // loop over digits for (; start < end; ++start) { unsigned char c = static_cast<unsigned char>(start[0]); int digit = kAsciiToInt[c]; if (digit >= base) { *value_p = value; return false; } if (value > vmax_over_base) { *value_p = vmax; return false; } value *= base; if (value > vmax - digit) { *value_p = vmax; return false; } value += digit; } *value_p = value; return true; } template <typename IntType> inline bool safe_parse_negative_int(absl::string_view text, int base, IntType* value_p) { IntType value = 0; const IntType vmin = std::numeric_limits<IntType>::min(); assert(vmin < 0); assert(vmin <= 0 - base); IntType vmin_over_base = LookupTables<IntType>::kVminOverBase[base]; // 2003 c++ standard [expr.mul] // "... the sign of the remainder is implementation-defined." // Although (vmin/base)*base + vmin%base is always vmin. // 2011 c++ standard tightens the spec but we cannot rely on it. // TODO: Handle this in the lookup table generation. if (vmin % base > 0) { vmin_over_base += 1; } const char* start = text.data(); const char* end = start + text.size(); // loop over digits for (; start < end; ++start) { unsigned char c = static_cast<unsigned char>(start[0]); int digit = kAsciiToInt[c]; if (digit >= base) { *value_p = value; return false; } if (value < vmin_over_base) { *value_p = vmin; return false; } value *= base; if (value < vmin + digit) { *value_p = vmin; return false; } value -= digit; } *value_p = value; return true; } // Input format based on POSIX.1-2008 strtol // http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html template <typename IntType> inline bool safe_int_internal(absl::string_view text, IntType* value_p, int base) { *value_p = 0; bool negative; if (!safe_parse_sign_and_base(&text, &base, &negative)) { return false; } if (!negative) { return safe_parse_positive_int(text, base, value_p); } else { return safe_parse_negative_int(text, base, value_p); } } template <typename IntType> inline bool safe_uint_internal(absl::string_view text, IntType* value_p, int base) { *value_p = 0; bool negative; if (!safe_parse_sign_and_base(&text, &base, &negative) || negative) { return false; } return safe_parse_positive_int(text, base, value_p); } } // anonymous namespace bool safe_strto32_base(absl::string_view text, int32_t* value, int base) { return safe_int_internal<int32_t>(text, value, base); } bool safe_strto64_base(absl::string_view text, int64_t* value, int base) { return safe_int_internal<int64_t>(text, value, base); } bool safe_strtou32_base(absl::string_view text, uint32_t* value, int base) { return safe_uint_internal<uint32_t>(text, value, base); } bool safe_strtou64_base(absl::string_view text, uint64_t* value, int base) { return safe_uint_internal<uint64_t>(text, value, base); } } // namespace zetasql_base
c++
code
9,619
2,513
/* Copyright (c) 2005-2018, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford 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. */ #ifndef PCBLOCKDIAGONAL_HPP_ #define PCBLOCKDIAGONAL_HPP_ #include <cassert> #include <petscvec.h> #include <petscmat.h> #include <petscksp.h> #include <petscpc.h> #include "PetscTools.hpp" /** * PETSc will return the control to this function everytime it needs to precondition a vector (i.e. y = inv(M)*x) * * This function needs to be declared global, since I (migb) haven't found a way of defining it inside a class and * be able of passing it by reference. * * @param pc_context preconditioner context struct. Stores preconditioner state (i.e. PC, Mat, and Vec objects used) * @param x unpreconditioned residual. * @param y preconditioned residual. y = inv(M)*x */ #if (PETSC_VERSION_MAJOR == 3 && PETSC_VERSION_MINOR >= 1) //PETSc 3.1 or later PetscErrorCode PCBlockDiagonalApply(PC pc_context, Vec x, Vec y); #else PetscErrorCode PCBlockDiagonalApply(void* pc_context, Vec x, Vec y); #endif /** * This class defines a PETSc-compliant purpouse-build preconditioner. * * Let A be a matrix arising in the FEM discretisation of the bidomain * equations with the following block structure: * * A = (A11 B') * (B A22) * * By creating an instance of this class, one will define the following * preconditioner: * * inv(M) = inv( (A11 0) = (inv(A11) 0) * (0 A22) ) (0 inv(A22)) * * The inverses are approximate with one cycle of AMG. * * Note: This class requires PETSc to be build including HYPRE library. * If it's not available, it will show the following warning: Chaste warning: in file linalg/src/PCLDUFactorisation.cpp at line ???: PETSc HYPRE preconditioning library is not installed * and will approximate the inverse of the subblocks with PETSc's default * preconditioner (bjacobi at the time of writing this). */ class PCBlockDiagonal { public: /** * This struct defines the state of the preconditioner (initialised data and objects to be reused) */ typedef struct{ Mat A11_matrix_subblock; /**< Mat object that stores the A11 subblock*/ Mat A22_matrix_subblock; /**< Mat object that stores the A22 subblock*/ PC PC_amg_A11; /**< inv(A11) is approximated by an AMG cycle. We compute it with HYPRE via a PC object*/ PC PC_amg_A22; /**< inv(A22) is approximated by an AMG cycle. We compute it with HYPRE via a PC object*/ Vec x1_subvector;/**< Used to store the first half of the vector to be preconditioned*/ Vec x2_subvector;/**< Used to store the second half of the vector to be preconditioned*/ Vec y1_subvector;/**< Used to store the first half of the preconditioned vector*/ Vec y2_subvector;/**< Used to store the second half of the preconditioned vector*/ VecScatter A11_scatter_ctx;/**< Scattering context: gather x1 from x and scatter y1 back into y*/ VecScatter A22_scatter_ctx;/**< Scattering context: gather x2 from x and scatter y2 back into y*/ #ifdef TRACE_KSP double mScatterTime;/**< Time counter used for profiling scatter operations*/ double mA1PreconditionerTime;/**< Time counter used for profiling the application of the preconditioner on the A11 block*/ double mA2PreconditionerTime;/**< Time counter used for profiling the application of the preconditioner on the A22 block*/ double mGatherTime;/**< Time counter used for profiling gather operations*/ #endif } PCBlockDiagonalContext; PCBlockDiagonalContext mPCContext; /**< PC context, this will be passed to PCBlockDiagonalApply when PETSc returns control to our preconditioner subroutine. See PCShellSetContext().*/ PC mPetscPCObject;/**< Generic PETSc preconditioner object */ /** * Constructor. * * @param rKspObject KSP object where we want to install the block diagonal preconditioner. */ PCBlockDiagonal(KSP& rKspObject); ~PCBlockDiagonal(); private: /** * Creates all the state data required by the preconditioner. * * @param rKspObject KSP object where we want to install the block diagonal preconditioner. */ void PCBlockDiagonalCreate(KSP& rKspObject); /** * Setups preconditioner. */ void PCBlockDiagonalSetUp(); }; #endif /*PCBLOCKDIAGONAL_HPP_*/
c++
code
6,042
1,172
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2011-2013 The PPCoin developers // Copyright (c) 2013-2014 The NovaCoin Developers // Copyright (c) 2014-2018 The BlackCoin Developers // Copyright (c) 2015-2020 The PIVX developers // Copyright (c) 2020 The BTCU developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/btcu-config.h" #endif #include "init.h" #include "activemasternode.h" #include "addrman.h" #include "amount.h" #include "checkpoints.h" #include "compat/sanity.h" #include "httpserver.h" #include "httprpc.h" #include "invalid.h" #include "key.h" #include "main.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "messagesigner.h" #include "miner.h" #include "net.h" #include "rpc/server.h" #include "script/standard.h" #include "scheduler.h" #include "spork.h" #include "sporkdb.h" #include "txdb.h" #include "torcontrol.h" #include "guiinterface.h" #include "util.h" #include "utilmoneystr.h" #include "validationinterface.h" #include "zbtcuchain.h" #ifdef ENABLE_WALLET #include "wallet/db.h" #include "wallet/wallet.h" #include "wallet/walletdb.h" #endif #include <fstream> #include <stdint.h> #include <stdio.h> #ifndef WIN32 #include <signal.h> #endif #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/thread.hpp> #include <boost/foreach.hpp> #if ENABLE_ZMQ #include "zmq/zmqnotificationinterface.h" #endif #ifdef ENABLE_LEASING_MANAGER #include "leasing/leasingmanager.h" #endif #include "contract.h" #ifdef ENABLE_WALLET CWallet* pwalletMain = NULL; CzBTCUWallet* zwalletMain = NULL; int nWalletBackups = 10; #endif volatile bool fFeeEstimatesInitialized = false; volatile bool fRestartRequested = false; // true: restart false: shutdown #ifdef ENABLE_LEASING_MANAGER CLeasingManager* pleasingManagerMain = nullptr; #endif #if ENABLE_ZMQ static CZMQNotificationInterface* pzmqNotificationInterface = NULL; #endif #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files, don't count towards to fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif /** Used to pass flags to the Bind() function */ enum BindFlags { BF_NONE = 0, BF_EXPLICIT = (1U << 0), BF_REPORT_ERROR = (1U << 1), BF_WHITELIST = (1U << 2), }; static const char* FEE_ESTIMATES_FILENAME = "fee_estimates.dat"; CClientUIInterface uiInterface; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets fRequestShutdown, which triggers // the DetectShutdownThread(), which interrupts the main thread group. // DetectShutdownThread() then exits, which causes AppInit() to // continue (it .joins the shutdown thread). // Shutdown() is then // called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Note that if running -daemon the parent process returns from AppInit2 // before adding any threads to the threadGroup, so .join_all() returns // immediately and the parent exits from main(). // // Shutdown for Qt is very similar, only it uses a QTimer to detect // fRequestShutdown getting set, and then does the normal Qt // shutdown thing. // volatile bool fRequestShutdown = false; void StartShutdown() { fRequestShutdown = true; } bool ShutdownRequested() { return fRequestShutdown || fRestartRequested; } class CCoinsViewErrorCatcher : public CCoinsViewBacked { public: CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {} bool GetCoins(const uint256& txid, CCoins& coins) const { try { return CCoinsViewBacked::GetCoins(txid, coins); } catch (const std::runtime_error& e) { uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); LogPrintf("Error reading from database: %s\n", e.what()); // Starting the shutdown sequence and returning false to the caller would be // interpreted as 'entry not found' (as opposed to unable to read data), and // could lead to invalid interpration. Just exit immediately, as we can't // continue anyway, and all writes should be atomic. abort(); } } // Writes do not need similar protection, as failure to write is handled by the caller. }; static CCoinsViewDB* pcoinsdbview = NULL; static CCoinsViewErrorCatcher* pcoinscatcher = NULL; static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle; static boost::thread_group threadGroup; static CScheduler scheduler; void Interrupt() { InterruptHTTPServer(); InterruptHTTPRPC(); InterruptRPC(); InterruptREST(); InterruptTorControl(); } /** Preparing steps before shutting down or restarting the wallet */ void PrepareShutdown() { fRequestShutdown = true; // Needed when we shutdown the wallet fRestartRequested = true; // Needed when we restart the wallet LogPrintf("%s: In progress...\n", __func__); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way, /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. RenameThread("btcu-shutoff"); mempool.AddTransactionsUpdated(1); StopHTTPRPC(); StopREST(); StopRPC(); StopHTTPServer(); #ifdef ENABLE_WALLET if (pwalletMain) bitdb.Flush(false); GenerateBitcoins(false, NULL, 0); #endif StopNode(); DumpMasternodes(); DumpBudgets(); DumpMasternodePayments(); UnregisterNodeSignals(GetNodeSignals()); // After everything has been shut down, but before things get flushed, stop the // CScheduler/checkqueue threadGroup threadGroup.interrupt_all(); threadGroup.join_all(); if (fFeeEstimatesInitialized) { boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION); if (!est_fileout.IsNull()) mempool.WriteFeeEstimates(est_fileout); else LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string()); fFeeEstimatesInitialized = false; } { LOCK(cs_main); if (pcoinsTip != NULL) { FlushStateToDisk(); //record that client took the proper shutdown procedure pblocktree->WriteFlag("shutdown", true); } delete pcoinsTip; pcoinsTip = NULL; delete pcoinscatcher; pcoinscatcher = NULL; delete pcoinsdbview; pcoinsdbview = NULL; delete pblocktree; pblocktree = NULL; delete zerocoinDB; zerocoinDB = NULL; delete pSporkDB; pSporkDB = NULL; } #ifdef ENABLE_WALLET if (pwalletMain) bitdb.Flush(true); #endif #ifdef ENABLE_LEASING_MANAGER if (pleasingManagerMain) { if (pwalletMain) pwalletMain->pLeasingManager = nullptr; UnregisterValidationInterface(pleasingManagerMain); delete pleasingManagerMain; pleasingManagerMain = nullptr; } #endif // ENABLE_LEASING_MANAGER #if ENABLE_ZMQ if (pzmqNotificationInterface) { UnregisterValidationInterface(pzmqNotificationInterface); delete pzmqNotificationInterface; pzmqNotificationInterface = NULL; } #endif #ifndef WIN32 try { boost::filesystem::remove(GetPidFile()); } catch (const boost::filesystem::filesystem_error& e) { LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what()); } #endif UnregisterAllValidationInterfaces(); ContractStateShutdown(); } /** * Shutdown is split into 2 parts: * Part 1: shut down everything but the main wallet instance (done in PrepareShutdown() ) * Part 2: delete wallet instance * * In case of a restart PrepareShutdown() was already called before, but this method here gets * called implicitly when the parent object is deleted. In this case we have to skip the * PrepareShutdown() part because it was already executed and just delete the wallet instance. */ void Shutdown() { // Shutdown part 1: prepare shutdown if (!fRestartRequested) { PrepareShutdown(); } // Shutdown part 2: Stop TOR thread and delete wallet instance StopTorControl(); #ifdef ENABLE_WALLET delete pwalletMain; pwalletMain = NULL; delete zwalletMain; zwalletMain = NULL; #endif globalVerifyHandle.reset(); ECC_Stop(); LogPrintf("%s: done\n", __func__); } /** * Signal handlers are very limited in what they are allowed to do, so: */ void HandleSIGTERM(int) { StartShutdown(); } void HandleSIGHUP(int) { fReopenDebugLog = true; } #ifndef WIN32 static void registerSignalHandler(int signal, void(*handler)(int)) { struct sigaction sa; sa.sa_handler = handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(signal, &sa, nullptr); } #endif bool static InitError(const std::string& str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); return false; } bool static InitWarning(const std::string& str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING); return true; } bool static Bind(const CService& addr, unsigned int flags) { if (!(flags & BF_EXPLICIT) && IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) { if (flags & BF_REPORT_ERROR) return InitError(strError); return false; } return true; } void OnRPCStarted() { uiInterface.NotifyBlockTip.connect(RPCNotifyBlockChange); } void OnRPCStopped() { uiInterface.NotifyBlockTip.disconnect(RPCNotifyBlockChange); //RPCNotifyBlockChange(0); g_best_block_cv.notify_all(); LogPrint("rpc", "RPC stopped.\n"); } void OnRPCPreCommand(const CRPCCommand& cmd) { #ifdef ENABLE_WALLET if (cmd.reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); #endif // Observe safe mode std::string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", false) && !cmd.okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning); } std::string HelpMessage(HelpMessageMode mode) { // When adding new options to the categories, please keep and ensure alphabetical ordering. std::string strUsage = HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-version", _("Print version and exit")); strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)")); strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS)); strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)")); strUsage += HelpMessageOpt("-blocksizenotify=<cmd>", _("Execute command when the best block changes and its size is over (%s in cmd is replaced by block hash, %d with the block size)")); strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 500)); strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "btcu.conf")); if (mode == HMM_BITCOIND) { #if !defined(WIN32) strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands")); #endif } strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache)); strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup")); strUsage += HelpMessageOpt("-maxreorg=<n>", strprintf(_("Set the Maximum reorg depth (default: %u)"), Params(CBaseChainParams::MAIN).MaxReorganizationDepth())); strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS)); strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS)); #ifndef WIN32 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "btcud.pid")); #endif strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files") + " " + _("on startup")); strUsage += HelpMessageOpt("-reindexmoneysupply", _("Reindex the BTCU and zBTCU money supply statistics") + " " + _("on startup")); strUsage += HelpMessageOpt("-resync", _("Delete blockchain folders and resync from scratch") + " " + _("on startup")); #if !defined(WIN32) strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)")); #endif strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0)); strUsage += HelpMessageOpt("-forcestart", _("Attempt to force blockchain corruption recovery") + " " + _("on startup")); strUsage += HelpMessageGroup(_("Connection options:")); strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open")); strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100)); strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400)); strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6")); strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)")); strUsage += HelpMessageOpt("-discover", _("Discover own IP address (default: 1 when listening and no -externalip)")); strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)")); strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)")); strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address")); strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0)); strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)")); strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION)); strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), 125)); strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000)); strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000)); strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy")); strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)")); strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1)); strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS)); strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 3666, 13666)); strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy")); strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1)); strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect")); strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT)); strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL)); strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)")); #ifdef USE_UPNP #if USE_UPNP strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening)")); #else strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0)); #endif #endif strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6")); strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") + " " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway")); #ifdef ENABLE_WALLET strUsage += HelpMessageGroup(_("Wallet options:")); strUsage += HelpMessageOpt("-backuppath=<dir|file>", _("Specify custom backup path to add a copy of any wallet backup. If set as dir, every backup generates a timestamped file. If set as file, will rewrite to that file every backup.")); strUsage += HelpMessageOpt("-createwalletbackups=<n>", _("Number of automatic wallet backups (default: 10)")); strUsage += HelpMessageOpt("-custombackupthreshold=<n>", strprintf(_("Number of custom location backups to retain (default: %d)"), DEFAULT_CUSTOMBACKUPTHRESHOLD)); strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls")); strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100)); if (GetBoolArg("-help-debug", false)) strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in BTCU/Kb) smaller than this are considered zero fee for transaction creation (default: %s)
c++
code
20,000
4,402
// Copyright (c) 2012 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 <stddef.h> #include "base/command_line.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/sessions/tab_restore_service_factory.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/find_bar/find_notification_details.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/sessions/core/tab_restore_service.h" #include "components/sessions/core/tab_restore_service_observer.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "url/gurl.h" // Class used to run a message loop waiting for the TabRestoreService to finish // loading. Does nothing if the TabRestoreService was already loaded. class WaitForLoadObserver : public sessions::TabRestoreServiceObserver { public: explicit WaitForLoadObserver(Browser* browser) : tab_restore_service_( TabRestoreServiceFactory::GetForProfile(browser->profile())), do_wait_(!tab_restore_service_->IsLoaded()) { if (do_wait_) tab_restore_service_->AddObserver(this); } ~WaitForLoadObserver() override { if (do_wait_) tab_restore_service_->RemoveObserver(this); } void Wait() { if (do_wait_) run_loop_.Run(); } private: // Overridden from TabRestoreServiceObserver: void TabRestoreServiceChanged(sessions::TabRestoreService* service) override { } void TabRestoreServiceDestroyed( sessions::TabRestoreService* service) override {} void TabRestoreServiceLoaded(sessions::TabRestoreService* service) override { DCHECK(do_wait_); run_loop_.Quit(); } sessions::TabRestoreService* tab_restore_service_; const bool do_wait_; base::RunLoop run_loop_; DISALLOW_COPY_AND_ASSIGN(WaitForLoadObserver); }; class TabRestoreTest : public InProcessBrowserTest { public: TabRestoreTest() : active_browser_list_(NULL) { url1_ = ui_test_utils::GetTestUrl( base::FilePath().AppendASCII("session_history"), base::FilePath().AppendASCII("bot1.html")); url2_ = ui_test_utils::GetTestUrl( base::FilePath().AppendASCII("session_history"), base::FilePath().AppendASCII("bot2.html")); } protected: void SetUpOnMainThread() override { active_browser_list_ = BrowserList::GetInstance(); InProcessBrowserTest::SetUpOnMainThread(); } Browser* GetBrowser(int index) { CHECK(static_cast<int>(active_browser_list_->size()) > index); return active_browser_list_->get(index); } // Adds tabs to the given browser, all navigated to url1_. Returns // the final number of tabs. int AddSomeTabs(Browser* browser, int how_many) { int starting_tab_count = browser->tab_strip_model()->count(); for (int i = 0; i < how_many; ++i) { ui_test_utils::NavigateToURLWithDisposition( browser, url1_, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); } int tab_count = browser->tab_strip_model()->count(); EXPECT_EQ(starting_tab_count + how_many, tab_count); return tab_count; } void CloseTab(int index) { content::WebContentsDestroyedWatcher destroyed_watcher( browser()->tab_strip_model()->GetWebContentsAt(index)); browser()->tab_strip_model()->CloseWebContentsAt( index, TabStripModel::CLOSE_CREATE_HISTORICAL_TAB); destroyed_watcher.Wait(); } // Uses the undo-close-tab accelerator to undo a close-tab or close-window // operation. The newly restored tab is expected to appear in the // window at index |expected_window_index|, at the |expected_tabstrip_index|, // and to be active. If |expected_window_index| is equal to the number of // current windows, the restored tab is expected to be created in a new // window (since the index is 0-based). void RestoreTab(int expected_window_index, int expected_tabstrip_index) { int window_count = static_cast<int>(active_browser_list_->size()); ASSERT_GT(window_count, 0); bool expect_new_window = (expected_window_index == window_count); Browser* browser; if (expect_new_window) { browser = active_browser_list_->get(0); } else { browser = GetBrowser(expected_window_index); } int tab_count = browser->tab_strip_model()->count(); ASSERT_GT(tab_count, 0); // Restore the tab. content::WindowedNotificationObserver tab_added_observer( chrome::NOTIFICATION_TAB_PARENTED, content::NotificationService::AllSources()); content::WindowedNotificationObserver tab_loaded_observer( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); { WaitForLoadObserver waiter(browser); chrome::RestoreTab(browser); waiter.Wait(); } tab_added_observer.Wait(); tab_loaded_observer.Wait(); if (expect_new_window) { int new_window_count = static_cast<int>(active_browser_list_->size()); EXPECT_EQ(++window_count, new_window_count); browser = GetBrowser(expected_window_index); } else { EXPECT_EQ(++tab_count, browser->tab_strip_model()->count()); } // Get a handle to the restored tab. ASSERT_GT(browser->tab_strip_model()->count(), expected_tabstrip_index); // Ensure that the tab and window are active. EXPECT_EQ(expected_tabstrip_index, browser->tab_strip_model()->active_index()); } void GoBack(Browser* browser) { content::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); chrome::GoBack(browser, CURRENT_TAB); observer.Wait(); } void EnsureTabFinishedRestoring(content::WebContents* tab) { content::NavigationController* controller = &tab->GetController(); if (!controller->NeedsReload() && !controller->GetPendingEntry() && !controller->GetWebContents()->IsLoading()) return; content::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::Source<content::NavigationController>(controller)); observer.Wait(); } GURL url1_; GURL url2_; const BrowserList* active_browser_list_; private: DISALLOW_COPY_AND_ASSIGN(TabRestoreTest); }; // Close the end tab in the current window, then restore it. The tab should be // in its original position, and active. IN_PROC_BROWSER_TEST_F(TabRestoreTest, Basic) { int starting_tab_count = browser()->tab_strip_model()->count(); int tab_count = AddSomeTabs(browser(), 1); int closed_tab_index = tab_count - 1; CloseTab(closed_tab_index); EXPECT_EQ(starting_tab_count, browser()->tab_strip_model()->count()); ASSERT_NO_FATAL_FAILURE(RestoreTab(0, closed_tab_index)); // And make sure everything looks right. EXPECT_EQ(starting_tab_count + 1, browser()->tab_strip_model()->count()); EXPECT_EQ(closed_tab_index, browser()->tab_strip_model()->active_index()); EXPECT_EQ(url1_, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); } // Close a tab not at the end of the current window, then restore it. The tab // should be in its original position, and active. IN_PROC_BROWSER_TEST_F(TabRestoreTest, MiddleTab) { int starting_tab_count = browser()->tab_strip_model()->count(); AddSomeTabs(browser(), 3); // Close one in the middle int closed_tab_index = starting_tab_count + 1; CloseTab(closed_tab_index); EXPECT_EQ(starting_tab_count + 2, browser()->tab_strip_model()->count()); ASSERT_NO_FATAL_FAILURE(RestoreTab(0, closed_tab_index)); // And make sure everything looks right. EXPECT_EQ(starting_tab_count + 3, browser()->tab_strip_model()->count()); EXPECT_EQ(closed_tab_index, browser()->tab_strip_model()->active_index()); EXPECT_EQ(url1_, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); } // Close a tab, switch windows, then restore the tab. The tab should be in its // original window and position, and active. IN_PROC_BROWSER_TEST_F(TabRestoreTest, RestoreToDifferentWindow) { int starting_tab_count = browser()->tab_strip_model()->count(); AddSomeTabs(browser(), 3); // Close one in the middle int closed_tab_index = starting_tab_count + 1; CloseTab(closed_tab_index); EXPECT_EQ(starting_tab_count + 2, browser()->tab_strip_model()->count()); // Create a new browser. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), NEW_WINDOW, ui_test_utils::BROWSER_TEST_WAIT_FOR_BROWSER); EXPECT_EQ(2u, active_browser_list_->size()); // Restore tab into original browser. ASSERT_NO_FATAL_FAILURE(RestoreTab(0, closed_tab_index)); // And make sure everything looks right. EXPECT_EQ(starting_tab_count + 3, browser()->tab_strip_model()->count()); EXPECT_EQ(closed_tab_index, browser()->tab_strip_model()->active_index()); EXPECT_EQ(url1_, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); } // Close a tab, open a new window, close the first window, then restore the // tab. It should be in a new window. // If this becomes flaky, use http://crbug.com/14774 IN_PROC_BROWSER_TEST_F(TabRestoreTest, DISABLED_BasicRestoreFromClosedWindow) { // Navigate to url1 then url2. ui_test_utils::NavigateToURL(browser(), url1_); ui_test_utils::NavigateToURL(browser(), url2_); // Create a new browser. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), NEW_WINDOW, ui_test_utils::BROWSER_TEST_WAIT_FOR_BROWSER); EXPECT_EQ(2u, active_browser_list_->size()); // Close the final tab in the first browser. content::WindowedNotificationObserver window_observer( chrome::NOTIFICATION_BROWSER_CLOSED, content::NotificationService::AllSources()); CloseTab(0); window_observer.Wait(); ASSERT_NO_FATAL_FAILURE(RestoreTab(1, 0)); // Tab should be in a new window. Browser* browser = GetBrowser(1); content::WebContents* web_contents = browser->tab_strip_model()->GetActiveWebContents(); // And make sure the URLs match. EXPECT_EQ(url2_, web_contents->GetURL()); GoBack(browser); EXPECT_EQ(url1_, web_contents->GetURL()); } #if defined(OS_WIN) // Flakily times out: http://crbug.com/171503 #define MAYBE_DontLoadRestoredTab DISABLED_DontLoadRestoredTab #else #define MAYBE_DontLoadRestoredTab DontLoadRestoredTab #endif // Restore a tab then make sure it doesn't restore again. IN_PROC_BROWSER_TEST_F(TabRestoreTest, MAYBE_DontLoadRestoredTab) { // Add two tabs int starting_tab_count = browser()->tab_strip_model()->count(); AddSomeTabs(browser(), 2); ASSERT_EQ(browser()->tab_strip_model()->count(), starting_tab_count + 2); // Close one of them. CloseTab(0); ASSERT_EQ(browser()->tab_strip_model()->count(), starting_tab_count + 1); // Restore it. ASSERT_NO_FATAL_FAILURE(RestoreTab(0, 0)); ASSERT_EQ(browser()->tab_strip_model()->count(), starting_tab_count + 2); // Make sure that there's nothing else to restore. ASSERT_EQ(chrome::GetRestoreTabType(browser()), TabStripModelDelegate::RESTORE_NONE); } // Open a window with multiple tabs, close a tab, then close the window. // Restore both and make sure the tab goes back into the window. IN_PROC_BROWSER_TEST_F(TabRestoreTest, RestoreWindowAndTab) { int starting_tab_count = browser()->tab_strip_model()->count(); AddSomeTabs(browser(), 3); // Close one in the middle int closed_tab_index = starting_tab_count + 1; CloseTab(closed_tab_index); EXPECT_EQ(starting_tab_count + 2, browser()->tab_strip_model()->count()); // Create a new browser. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), NEW_WINDOW, ui_test_utils::BROWSER_TEST_WAIT_FOR_BROWSER); EXPECT_EQ(2u, active_browser_list_->size()); // Close the first browser. content::WindowedNotificationObserver observer( chrome::NOTIFICATION_BROWSER_CLOSED, content::NotificationService::AllSources()); chrome::CloseWindow(browser()); observer.Wait(); EXPECT_EQ(1u, active_browser_list_->size()); // Restore the first window. The expected_tabstrip_index (second argument) // indicates the expected active tab. ASSERT_NO_FATAL_FAILURE(RestoreTab(1, starting_tab_count + 1)); Browser* browser = GetBrowser(1); EXPECT_EQ(starting_tab_count + 2, browser->tab_strip_model()->count()); // Restore the closed tab. ASSERT_NO_FATAL_FAILURE(RestoreTab(1, closed_tab_index)); EXPECT_EQ(starting_tab_count + 3, browser->tab_strip_model()->count()); EXPECT_EQ(url1_, browser->tab_strip_model()->GetActiveWebContents()->GetURL()); } // Open a window with two tabs, close both (closing the window), then restore // both. Make sure both restored tabs are in the same window. IN_PROC_BROWSER_TEST_F(TabRestoreTest, RestoreIntoSameWindow) { ui_test_utils::NavigateToURLWithDisposition( browser(), url1_, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // Navigate the rightmost one to url2_ for easier identification. ui_test_utils::NavigateToURLWithDisposition( browser(), url2_, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // Create a new browser. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), NEW_WINDOW, ui_test_utils::BROWSER_TEST_WAIT_FOR_BROWSER); EXPECT_EQ(2u, active_browser_list_->size()); // Close all but one tab in the first browser, left to right. while (browser()->tab_strip_model()->count() > 1) CloseTab(0); // Close the last tab, closing the browser. content::WindowedNotificationObserver observer( chrome::NOTIFICATION_BROWSER_CLOSED, content::NotificationService::AllSources()); CloseTab(0); observer.Wait(); EXPECT_EQ(1u, active_browser_list_->size()); // Restore the last-closed tab into a new window. ASSERT_NO_FATAL_FAILURE(RestoreTab(1, 0)); Browser* browser = GetBrowser(1); EXPECT_EQ(1, browser->tab_strip_model()->count()); EXPECT_EQ(url2_, browser->tab_strip_model()->GetActiveWebContents()->GetURL()); // Restore the next-to-last-closed tab into the same window. ASSERT_NO_FATAL_FAILURE(RestoreTab(1, 0)); EXPECT_EQ(2, browser->tab_strip_model()->count()); EXPECT_EQ(url1_, browser->tab_strip_model()->GetActiveWebContents()->GetURL()); } // Tests that a duplicate history entry is not created when we restore a page // to an existing SiteInstance. (Bug 1230446) IN_PROC_BROWSER_TEST_F(TabRestoreTest, RestoreWithExistingSiteInstance) { ASSERT_TRUE(embedded_test_server()->Start()); GURL http_url1(embedded_test_server()->GetURL("/title1.html")); GURL http_url2(embedded_test_server()->GetURL("/title2.html")); int tab_count = browser()->tab_strip_model()->count(); // Add a tab ui_test_utils::NavigateToURLWithDisposition( browser(), http_url1, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); EXPECT_EQ(++tab_count, browser()->tab_strip_model()->count()); // Navigate to another same-site URL. content::WebContents* tab = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); content::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); static_cast<content::WebContentsDelegate*>(browser())->OpenURLFromTab( tab, content::OpenURLParams(http_url2, content::Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false)); observer.Wait(); // Close the tab. CloseTab(1); // Create a new tab to the original site. Assuming process-per-site is // enabled, this will ensure that the SiteInstance used by the restored tab // will already exist when the restore happens. ui_test_utils::NavigateToURLWithDisposition( browser(), http_url2, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // Restore the closed tab. ASSERT_NO_FATAL_FAILURE(RestoreTab(0, tab_count - 1)); // And make sure the URLs match. EXPECT_EQ(http_url2, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); GoBack(browser()); EXPECT_EQ(http_url1, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); } // See crbug.com/248574 #if defined(OS_WIN) #define MAYBE_RestoreCrossSiteWithExistingSiteInstance \ DISABLED_RestoreCrossSiteWithExistingSiteInstance #else #define MAYBE_RestoreCrossSiteWithExistingSiteInstance \ RestoreCrossSiteWithExistingSiteInstance #endif // Tests that the SiteInstances used for entries in a restored tab's history // are given appropriate max page IDs, even if the renderer for the entry // already exists. (Bug 1204135) IN_PROC_BROWSER_TEST_F(TabRestoreTest, MAYBE_RestoreCrossSiteWithExistingSiteInstance) { ASSERT_TRUE(embedded_test_server()->Start()); GURL http_url1(embedded_test_server()->GetURL("/title1.html")); GURL http_url2(embedded_test_server()->GetURL("/title2.html")); int tab_count = browser()->tab_strip_model()->count(); // Add a tab ui_test_utils::NavigateToURLWithDisposition( browser(), http_url1, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); EXPECT_EQ(++tab_count, browser()->tab_strip_model()->count()); // Navigate to more URLs, then a cross-site URL. ui_test_utils::NavigateToURL(browser(), http_url2); ui_test_utils::NavigateToURL(browser(), http_url1); ui_test_utils::NavigateToURL(browser(), url1_); // Close the tab. CloseTab(1); // Create a new tab to the original site. Assuming process-per-site is // enabled, this will ensure that the SiteInstance will already exist when // the user clicks Back in the restored tab. ui_test_utils::NavigateToURLWithDisposition( browser(), http_url2, NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); // Restore the closed tab. ASSERT_NO_FATAL_FAILURE(RestoreTab(0, tab_count - 1)); // And make sure the URLs match. EXPECT_EQ(url1_, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); GoBack(browser()); EXPECT_EQ(http_url1, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); // Navigating to a new URL should clear the forward list, because the max // page ID of the renderer should have been updated when we restored the tab. ui_test_utils::NavigateToURL(browser(), http_url2); EXPECT_FALSE(chrome::CanGoForward(browser())); EXPECT_EQ(http_url2, browser()->tab_strip_model()->GetActiveWebContents()->GetURL()); } IN_PROC_BROWSER_TEST_F(TabRestoreTest, RestoreWindow) { // Create a new window. size_t window_count = active_browser_list_->size(); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), NEW_WINDOW, ui_tes
c++
code
20,000
3,828
// Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #define PCL_NO_PRECOMPILE #include <gtest/gtest.h> #include <pcl/io/pcd_io.h> #include <string> #include <utility> #include <vector> #include <memory> #include "object_analytics_node/model/object_utils.hpp" #include "unittest_util.hpp" TEST(UnitTestObjectUtils, fill2DObjects_Empty) { ObjectsInBoxes::SharedPtr objects = std::make_shared<ObjectsInBoxes>(); std::vector<Object2D> objects2d; ObjectUtils::fill2DObjects(objects, objects2d); EXPECT_EQ(objects2d.size(), static_cast<size_t>(0)); } TEST(UnitTestObjectUtils, fill2DObjects_NormalCase) { ObjectsInBoxes::SharedPtr objects = std::make_shared<ObjectsInBoxes>(); ObjectInBox first = getObjectInBox(0, 0, 100, 100, "person", 0.9f); objects->objects_vector.push_back(first); ObjectInBox second = getObjectInBox(100, 100, 50, 50, "chair", 0.8f); objects->objects_vector.push_back(second); ObjectInBox third = getObjectInBox(320, 480, 1, 1, "key", 0.1f); objects->objects_vector.push_back(third); std::vector<Object2D> objects2d; ObjectUtils::fill2DObjects(objects, objects2d); EXPECT_EQ(objects2d.size(), static_cast<size_t>(3)); EXPECT_TRUE(first == objects2d[0]); EXPECT_TRUE(second == objects2d[1]); EXPECT_TRUE(third == objects2d[2]); } TEST(UnitTestObjectUtils, fill3DObjects_Empty) { ObjectsInBoxes3D::SharedPtr objects = std::make_shared<ObjectsInBoxes3D>(); std::vector<Object3D> objects3d; EXPECT_EQ(objects3d.size(), static_cast<size_t>(0)); } TEST(UnitTestObjectUtils, fill3DObjects_NormalCase) { ObjectsInBoxes3D::SharedPtr objects = std::make_shared<ObjectsInBoxes3D>(); ObjectInBox3D first = getObjectInBox3D(1, 1, 100, 100, 1, 2, 3, 4, 5, 6, "person", 0.99); objects->objects_in_boxes.push_back(first); ObjectInBox3D second = getObjectInBox3D(100, 100, 200, 200, 7, 8, 9, 10, 11, 12, "person", 0.80); objects->objects_in_boxes.push_back(second); ObjectInBox3D third = getObjectInBox3D(320, 480, 1, 1, 13, 14, 15, 16, 17, 18, "person", 0.90); objects->objects_in_boxes.push_back(third); std::vector<Object3D> objects3d; ObjectUtils::fill3DObjects(objects, objects3d); EXPECT_EQ(objects3d.size(), static_cast<size_t>(3)); EXPECT_TRUE(first == objects3d[0]); EXPECT_TRUE(second == objects3d[1]); EXPECT_TRUE(third == objects3d[2]); } TEST(UnitTestObjectUtils, findMaxIntersectionRelationships_NormalCase) { std::vector<Object3D> objects3d; std::vector<Object2D> objects2d; std::vector<std::pair<Object2D, Object3D>> relations; // build 3d objects Object3D first3d = Object3D(getObjectInBox3D(1, 1, 100, 100, 1, 2, 3, 4, 5, 6, "person", 0.90)); Object3D second3d = Object3D(getObjectInBox3D(1, 102, 100, 100, 1, 2, 3, 4, 5, 6, "person", 0.80)); Object3D third3d = Object3D(getObjectInBox3D(50, 50, 100, 100, 1, 2, 3, 4, 5, 6, "person", 0.70)); Object3D forth3d = Object3D(getObjectInBox3D(200, 0, 30, 40, 1, 2, 3, 4, 5, 6, "person", 0.60)); objects3d.push_back(first3d); objects3d.push_back(second3d); objects3d.push_back(third3d); objects3d.push_back(forth3d); // build 2d objects Object2D first2d = Object2D(getObjectInBox(0, 0, 100, 100, "person", 0.8f)); Object2D second2d = Object2D(getObjectInBox(0, 101, 100, 100, "dog", 0.9f)); Object2D third2d = Object2D(getObjectInBox(49, 49, 60, 60, "chair", 0.3f)); Object2D forth2d = Object2D(getObjectInBox(200, 200, 30, 40, "computer", 0.8f)); objects2d.push_back(first2d); objects2d.push_back(second2d); objects2d.push_back(third2d); objects2d.push_back(forth2d); ObjectUtils::findMaxIntersectionRelationships(objects2d, objects3d, relations); EXPECT_EQ(relations.size(), static_cast<size_t>(4)); std::pair<Object2D, Object3D> first = relations[0]; EXPECT_TRUE(first.first == first2d); EXPECT_TRUE(first.second == first3d); std::pair<Object2D, Object3D> second = relations[1]; EXPECT_TRUE(second.first == second2d); EXPECT_TRUE(second.second == second3d); std::pair<Object2D, Object3D> third = relations[2]; EXPECT_TRUE(third.first == third2d); EXPECT_TRUE(third.second == third3d); } TEST(UnitTestObjectUtils, getMinMaxPointsInXYZ) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/object3d.pcd", cloud); pcl::PointCloud<PointXYZPixel>::Ptr cloudPixel(new pcl::PointCloud<PointXYZPixel>); std::vector<int> indices; for (auto i = 0; i < static_cast<int>(cloud->size()); i++) { indices.push_back(i); } ObjectUtils::copyPointCloud(cloud, indices, cloudPixel); PointXYZPixel x_min, x_max; ObjectUtils::getMinMaxPointsInX(cloudPixel, x_min, x_max); EXPECT_TRUE(x_min == getPointT(1.1, 2.2, 3.3)); EXPECT_TRUE(x_max == getPointT(10.1, 8.2, 8.3)); PointXYZPixel y_min, y_max; ObjectUtils::getMinMaxPointsInY(cloudPixel, y_min, y_max); EXPECT_TRUE(y_min == getPointT(2.1, 1.2, 2.3)); EXPECT_TRUE(y_max == getPointT(9.1, 10.2, 9.3)); PointXYZPixel z_min, z_max; ObjectUtils::getMinMaxPointsInZ(cloudPixel, z_min, z_max); EXPECT_TRUE(z_min == getPointT(3.1, 3.2, 1.3)); EXPECT_TRUE(z_max == getPointT(8.1, 9.2, 10.3)); } TEST(UnitTestObjectUtils, copyPointCloud_All) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/copy.pcd", cloud); std::vector<int> indices; for (auto i = 0; i < static_cast<int>(cloud->size()); i++) { indices.push_back(i); } pcl::PointCloud<PointXYZPixel>::Ptr seg(new pcl::PointCloud<PointXYZPixel>); ObjectUtils::copyPointCloud(cloud, indices, seg); for (uint32_t y = 0; y < 5; ++y) { for (uint32_t x = 0; x < 5; ++x) { PointXYZPixel p = seg->points[y * 5 + x]; EXPECT_TRUE(p.pixel_x == x); EXPECT_TRUE(p.pixel_y == y); } } } TEST(UnitTestObjectUtils, copyPointCloud_Empty) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/copy.pcd", cloud); std::vector<int> indices; pcl::PointCloud<PointXYZPixel>::Ptr seg(new pcl::PointCloud<PointXYZPixel>); ObjectUtils::copyPointCloud(cloud, indices, seg); EXPECT_EQ(seg->size(), static_cast<size_t>(0)); } TEST(UnitTestObjectUtils, copyPointCloud_Diagonal) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/copy.pcd", cloud); int i[] = {0, 6, 12, 18, 24}; std::vector<int> indices(i, i + sizeof(i) / sizeof(uint32_t)); pcl::PointCloud<PointXYZPixel>::Ptr seg(new pcl::PointCloud<PointXYZPixel>); ObjectUtils::copyPointCloud(cloud, indices, seg); for (uint32_t i = 0; i < 5; ++i) { EXPECT_EQ(seg->points[i].pixel_x, i); EXPECT_EQ(seg->points[i].pixel_y, i); } } TEST(UnitTestObjectUtils, getProjectedROI_NormalShapeNoEdgeOnImageBorder) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/project.pcd", cloud); // NOLINTNEXTLINE int i[] = { 15, // y_offset is 1 23, 24, 25, 26, 27, 28, // no edge this row 32, 33, 34, 35, 36, 37, 38, // width is 8 - 1 = 7 42, 43, 44, // no edge this row 51, 52, 53, 54, // x_offset is 1 62, 63, 64, // no edge this row 72, 73, 74, 75, 76, 77, 78, // width is 8 - 1 = 7 86 // height is 8 - 1 = 7 }; std::vector<int> indices(i, i + sizeof(i) / sizeof(uint32_t)); pcl::PointCloud<PointXYZPixel>::Ptr seg(new pcl::PointCloud<PointXYZPixel>); ObjectUtils::copyPointCloud(cloud, indices, seg); sensor_msgs::msg::RegionOfInterest roi; ObjectUtils::getProjectedROI(seg, roi); EXPECT_EQ(roi.x_offset, static_cast<uint32_t>(1)); EXPECT_EQ(roi.y_offset, static_cast<uint32_t>(1)); EXPECT_EQ(roi.width, static_cast<uint32_t>(7)); EXPECT_EQ(roi.height, static_cast<uint32_t>(7)); } TEST(UnitTestObjectUtils, getProjectedROI_NormalShapeAllEdgesOnImageBorder) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/project.pcd", cloud); // NOLINTNEXTLINE int i[] = { 5, // y_offset is 0 23, 24, 25, 26, 27, 28, // no edge this row 32, 33, 34, 35, 36, 37, 38, 39, // width is 9 - 0 = 9 42, 43, 44, // no edge this row 51, 52, 53, 54, // no edge this row 60, 61, 62, 63, 64, // x_offset is 0 73, 74, 75, 76, 77, 78, // no edge this row 85, 86, // no edge this row 96 // height is 9 - 0 = 9 }; std::vector<int> indices(i, i + sizeof(i) / sizeof(uint32_t)); pcl::PointCloud<PointXYZPixel>::Ptr seg(new pcl::PointCloud<PointXYZPixel>); ObjectUtils::copyPointCloud(cloud, indices, seg); sensor_msgs::msg::RegionOfInterest roi; ObjectUtils::getProjectedROI(seg, roi); EXPECT_EQ(roi.x_offset, static_cast<uint32_t>(0)); EXPECT_EQ(roi.y_offset, static_cast<uint32_t>(0)); EXPECT_EQ(roi.width, static_cast<uint32_t>(9)); EXPECT_EQ(roi.height, static_cast<uint32_t>(9)); } TEST(UnitTestObjectUtils, getProjectedROI_ShapeIsFullOfImage) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/project.pcd", cloud); std::vector<int> indices; for (int i = 0; i < 100; i++) { indices.push_back(i); } pcl::PointCloud<PointXYZPixel>::Ptr seg(new pcl::PointCloud<PointXYZPixel>); ObjectUtils::copyPointCloud(cloud, indices, seg); sensor_msgs::msg::RegionOfInterest roi; ObjectUtils::getProjectedROI(seg, roi); EXPECT_EQ(roi.x_offset, static_cast<uint32_t>(0)); EXPECT_EQ(roi.y_offset, static_cast<uint32_t>(0)); EXPECT_EQ(roi.width, static_cast<uint32_t>(9)); EXPECT_EQ(roi.height, static_cast<uint32_t>(9)); } TEST(UnitTestObjectUtils, getProjectedROI_ShapeIsOneRow) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/project.pcd", cloud); int i[] = {23, 24, 25, 26, 27, 28}; std::vector<int> indices(i, i + sizeof(i) / sizeof(uint32_t)); pcl::PointCloud<PointXYZPixel>::Ptr seg(new pcl::PointCloud<PointXYZPixel>); ObjectUtils::copyPointCloud(cloud, indices, seg); sensor_msgs::msg::RegionOfInterest roi; ObjectUtils::getProjectedROI(seg, roi); EXPECT_EQ(roi.x_offset, static_cast<uint32_t>(3)); EXPECT_EQ(roi.y_offset, static_cast<uint32_t>(2)); EXPECT_EQ(roi.width, static_cast<uint32_t>(5)); EXPECT_EQ(roi.height, static_cast<uint32_t>(0)); } TEST(UnitTestObjectUtils, getProjectedROI_ShapeIsOneColumn) { PointCloudT::Ptr cloud(new PointCloudT); readPointCloudFromPCD(std::string(RESOURCE_DIR) + "/project.pcd", cloud); int i[] = {23, 33, 43, 53, 63, 73}; std::vector<int> indices(i, i + sizeof(i) / sizeof(uint32_t)); pcl::PointCloud<PointXYZPixel>::Ptr seg(new pcl::PointCloud<PointXYZPixel>); ObjectUtils::copyPointCloud(cloud, indices, seg); sensor_msgs::msg::RegionOfInterest roi; ObjectUtils::getProjectedROI(seg, roi); EXPECT_EQ(roi.x_offset, static_cast<uint32_t>(3)); EXPECT_EQ(roi.y_offset, static_cast<uint32_t>(2)); EXPECT_EQ(roi.width, static_cast<uint32_t>(0)); EXPECT_EQ(roi.height, static_cast<uint32_t>(5)); } TEST(UnitTestObjectUtils, getMatch_NoMatch) { cv::Rect2d left(0, 0, 100, 100); cv::Rect2d right(101, 101, 100, 100); EXPECT_EQ(ObjectUtils::getMatch(left, right), 0); } TEST(UnitTestObjectUtils, getMatch_ExactMatchBetterThanBiggerMatch) { cv::Rect2d origin(50, 50, 100, 100); cv::Rect2d exact(50, 50, 100, 100); cv::Rect2d bigger(40, 40, 110, 110); EXPECT_GT(ObjectUtils::getMatch(origin, exact), ObjectUtils::getMatch(origin, bigger)); } TEST(UnitTestObjectUtils, getMatch_SameOverlapBetterDiviation) { cv::Rect2d origin(0, 0, 100, 100); cv::Rect2d bigDiviation(0, 0, 50, 50); cv::Rect2d smallDiviation(20, 20, 70, 70); EXPECT_GT( ObjectUtils::getMatch(origin, smallDiviation), ObjectUtils::getMatch(origin, bigDiviation)); } int main(int argc, char ** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
c++
code
12,570
3,225
/*************************************************************************** * Copyright (C) 2004 by Matthias Reif * * [email protected] * * * * 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "useritem.h" UserItem::UserItem( const QString& id, QTreeWidget *parent ) : Item( parent, id ) { init(); } UserItem::UserItem( const QString& id, QTreeWidgetItem *parent ) : Item( parent, id ) { init(); } UserItem::~UserItem() {} void UserItem::init() { speed = 0; fileNameSet = false; status_ = NEW_SOURCE; setFlags( Qt::ItemIsEnabled ); } void UserItem::setSpeed( const QString& newSpeedString, const QTime& /*time*/ ) { speed = newSpeedString.toInt(); if ( status_ == ACTIVE_SOURCE ) setText( DownloadItem::SPEED_COL, QConvert::bytes(newSpeedString) + "/s" ); else setText( DownloadItem::SPEED_COL, "" ); } void UserItem::update( const QString& fileName, const QString& nickname, const QString& speed, const QString& status, const QString& power, const QString& queuePos, const QString& statusString, QIcon& osIcon, const QString& downloadfrom, const QString& downloadto, const QString& actualdownloadposition, const QTime& time ) { this->fileName = fileName; status_ = status; this->power = power; this->queuePos = queuePos.toInt(); setSpeed( speed, time ); if ( status_ == QUEUED_SOURCE ) { // queueing? print position setText( DownloadItem::STATUS_COL, statusString + " (" + queuePos + ")" ); } else { setText( DownloadItem::STATUS_COL, statusString ); } setText( DownloadItem::POWER_COL, QConvert::power( power ) ); setText( DownloadItem::SOURCES_COL, nickname ); if ( !fileNameSet && !fileName.isEmpty() ) { setText( DownloadItem::FILENAME_COL, fileName ); fileNameSet = true; } if ( this->icon(DownloadItem::SOURCES_COL).isNull() ) { setIcon( DownloadItem::SOURCES_COL, osIcon ); } if(actualdownloadposition != "-1") { double dFrom = downloadfrom.toULongLong(); double dTo = downloadto.toULongLong(); double dPosition = actualdownloadposition.toULongLong(); setText(DownloadItem::SIZE_COL, QConvert::bytes(dTo - dFrom + 1.0, 2)); setText(DownloadItem::REMAIN_SIZE_COL, QConvert::bytes(dTo - dPosition + 1.0, 2)); setText(DownloadItem::FINISHED_SIZE_COL, QConvert::bytes(dPosition - dFrom, 2)); } else { setText(DownloadItem::SIZE_COL, ""); setText(DownloadItem::REMAIN_SIZE_COL, ""); setText(DownloadItem::FINISHED_SIZE_COL, ""); } }
c++
code
4,158
867
/** * SPDX-License-Identifier: Apache-2.0 * * @file instruction.hpp * @brief header file for instruction class of 8085 microprocessor * instructions */ #ifndef INSTRUCTION_HPP_ #define INSTRUCTION_HPP_ #include <iostream> #include <map> #include <string> #include <vector> #include "utils.hpp" using namespace std; void ADD(string arg1, string registers[], bool flag[], map<string, string> &memory, string &); void ADI(string arg, string registers[], bool flag[], string &); void SUB(string arg1, string registers[], bool flag[], map<string, string> &memory, string &); void SUI(string arg, string registers[], bool flag[], string &); void MOV(string argument1, string argument2, string registers[], bool flag[], map<string, string> &memory, string &); void MVI(string arg1, string arg2, string registers[], bool flags[], map<string, string> &memory, string &); void INR(string arg, string registers[], bool flag[], map<string, string> &memory, string &); void INX(string arg, string registers[], bool flag[], string &); void DCR(string arg, string registers[], bool flag[], map<string, string> &memory, string &); void DCX(string arg, string registers[], bool flag[], string &); void DAD(string arg, string registers[], bool flag[], string &); void CMP (string arg1,string registers[],bool flag[],map<string,string> &memory, string &); #endif // INSTRUCTION_HPP_
c++
code
1,433
375
// Copyright (c) 2018-2019, The TurtleCoin Developers // // Please see the included LICENSE file for more information. #include <atomic> #include <chrono> #include <common/SignalHandler.h> #include <config/CliHeader.h> #include <iostream> #include <logger/Logger.h> #include <thread> #include <walletapi/ApiDispatcher.h> #include <walletapi/ParseArguments.h> int main(int argc, char **argv) { ApiConfig config = parseArguments(argc, argv); Logger::logger.setLogLevel(config.logLevel); std::ofstream logFile; if (config.loggingFilePath) { logFile.open(*config.loggingFilePath, std::ios_base::app); } Logger::logger.setLogCallback( [&config, &logFile]( const std::string prettyMessage, const std::string message, const Logger::LogLevel level, const std::vector<Logger::LogCategory> categories) { std::cout << prettyMessage << std::endl; if (config.loggingFilePath) { logFile << prettyMessage << std::endl; } }); std::cout << CryptoNote::getProjectCLIHeader() << std::endl; std::thread apiThread; std::atomic<bool> ctrl_c(false); std::shared_ptr<ApiDispatcher> api(nullptr); try { /* Trigger the shutdown signal if ctrl+c is used */ Tools::SignalHandler::install([&ctrl_c] { ctrl_c = true; }); /* Init the API */ api = std::make_shared<ApiDispatcher>( config.port, config.rpcBindIp, config.rpcPassword, config.corsHeader, config.threads); /* Launch the API */ apiThread = std::thread(&ApiDispatcher::start, api.get()); /* Give the underlying ApiDispatcher time to start and possibly fail before continuing on and confusing users */ std::this_thread::sleep_for(std::chrono::milliseconds(250)); std::cout << "Want documentation on how to use the wallet-api?\n" "See https://turtlecoin.github.io/wallet-api-docs/\n\n"; std::string address = "http://" + config.rpcBindIp + ":" + std::to_string(config.port); std::cout << "The api has been launched on " << address << "." << std::endl; if (!config.noConsole) { std::cout << "Type exit to save and shutdown." << std::endl; } while (!ctrl_c) { /* If we are providing an interactive console we will do so here. */ if (!config.noConsole) { std::string input; if (!std::getline(std::cin, input) || input == "exit" || input == "quit") { break; } if (input == "help") { std::cout << "Type exit to save and shutdown." << std::endl; } } else /* If not, then a brief sleep helps stop the thread from running away */ { std::this_thread::sleep_for(std::chrono::milliseconds(250)); } } } catch (const std::exception &e) { std::cout << "Unexpected error: " << e.what() << "\nPlease report this error, and what you were doing to " "cause it.\n"; } std::cout << ("\nSaving and shutting down...\n"); if (api != nullptr) { api->stop(); } if (apiThread.joinable()) { apiThread.join(); } }
c++
code
3,483
778
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2026-01-04 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ /** * @file avro_schema.c - Avro schema related functions */ #include "avrorouter.hh" #include <maxscale/mysql_utils.hh> #include <jansson.h> #include <stdio.h> #include <limits.h> #include <unistd.h> #include <sys/stat.h> #include <errno.h> #include <string.h> #include <strings.h> #include <maxbase/alloc.h> /** * @brief Check whether the field is one that was generated by the avrorouter * * @param name Name of the field in the Avro schema * @return True if field was not generated by the avrorouter */ static inline bool not_generated_field(const char* name) { return strcmp(name, avro_domain) && strcmp(name, avro_server_id) && strcmp(name, avro_sequence) && strcmp(name, avro_event_number) && strcmp(name, avro_event_type) && strcmp(name, avro_timestamp); } /** * @brief Extract the field names from a JSON Avro schema file * * This function extracts the names of the columns from the JSON format Avro * schema in the file @c filename. This function assumes that the field definitions * in @c filename are in the same order as they are in the CREATE TABLE statement. * * @param filename The Avro schema in JSON format * @param table The TABLE_CREATE object to populate * @return True on success successfully, false on error */ bool json_extract_field_names(const char* filename, std::vector<Column>& columns) { bool rval = false; json_error_t err; err.text[0] = '\0'; json_t* obj; json_t* arr = nullptr; if ((obj = json_load_file(filename, 0, &err)) && (arr = json_object_get(obj, "fields"))) { if (json_is_array(arr)) { int array_size = json_array_size(arr); rval = true; for (int i = 0; i < array_size; i++) { json_t* val = json_array_get(arr, i); if (json_is_object(val)) { json_t* name = json_object_get(val, "name"); if (name && json_is_string(name)) { const char* name_str = json_string_value(name); if (not_generated_field(name_str)) { columns.emplace_back(name_str); json_t* value; if ((value = json_object_get(val, "real_type")) && json_is_string(value)) { columns.back().type = json_string_value(value); } else { MXS_WARNING("No \"real_type\" value defined. Treating as unknown type field."); } if ((value = json_object_get(val, "length")) && json_is_integer(value)) { columns.back().length = json_integer_value(value); } else { MXS_WARNING("No \"length\" value defined. Treating as default length field."); } if ((value = json_object_get(val, "unsigned")) && json_is_boolean(value)) { columns.back().is_unsigned = json_boolean_value(value); } } } else { MXS_ERROR("JSON value for \"name\" was not a string in " "file '%s'.", filename); rval = false; } } else { MXS_ERROR("JSON value for \"fields\" was not an array of objects in " "file '%s'.", filename); rval = false; } } } else { MXS_ERROR("JSON value for \"fields\" was not an array in file '%s'.", filename); } json_decref(obj); } else { MXS_ERROR("Failed to load JSON from file '%s': %s", filename, obj && !arr ? "No 'fields' value in object." : err.text); } return rval; } TableCreateEvent* table_create_from_schema(const char* file, const char* db, const char* table, int version) { TableCreateEvent* newtable = NULL; std::vector<Column> columns; if (json_extract_field_names(file, columns)) { newtable = new(std::nothrow) TableCreateEvent(db, table, version, std::move(columns)); } return newtable; }
c++
code
5,307
935
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include "atlas/grid/Iterator.h" //--------------------------------------------------------------------------------------------------------------------- namespace atlas { namespace grid { IterateXY::iterator IterateXY::begin() const { return use_p_ ? grid_.xy_begin( p_ ) : grid_.xy_begin(); } IterateXY::iterator IterateXY::end() const { return use_p_ ? grid_.xy_end( p_ ) : grid_.xy_end(); } IterateLonLat::iterator IterateLonLat::begin() const { return grid_.lonlat_begin(); } IterateLonLat::iterator IterateLonLat::end() const { return grid_.lonlat_end(); } } // namespace grid } // namespace atlas
c++
code
1,019
238
// // Copyright © 2017 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include "PadLayer.hpp" #include "LayerCloneBase.hpp" #include <armnn/backends/TensorHandle.hpp> #include <armnn/backends/WorkloadData.hpp> #include <armnn/backends/WorkloadFactory.hpp> #include <cstring> namespace armnn { PadLayer::PadLayer(const armnn::PadDescriptor& param, const char* name) : LayerWithParameters(1, 1, LayerType::Pad, param, name) {} std::unique_ptr<IWorkload> PadLayer::CreateWorkload(const armnn::IWorkloadFactory& factory) const { PadQueueDescriptor descriptor; descriptor.m_Parameters.m_PadList = m_Param.m_PadList; descriptor.m_Parameters.m_PaddingMode = m_Param.m_PaddingMode; SetAdditionalInfo(descriptor); return factory.CreateWorkload(LayerType::Pad, descriptor, PrepInfoAndDesc(descriptor)); } PadLayer* PadLayer::Clone(Graph& graph) const { auto layer = CloneBase<PadLayer>(graph, m_Param, GetName()); layer->m_Param.m_PadList = m_Param.m_PadList; layer->m_Param.m_PaddingMode = m_Param.m_PaddingMode; return std::move(layer); } std::vector<TensorShape> PadLayer::InferOutputShapes(const std::vector<TensorShape>& inputShapes) const { ARMNN_ASSERT(inputShapes.size() == 1); const TensorShape& inputShape = inputShapes[0]; unsigned int rank = inputShape.GetNumDimensions(); ARMNN_ASSERT(m_Param.m_PadList.size() == rank); ARMNN_ASSERT(rank != 0); std::vector<unsigned int> outputDimensionSizes(rank); for (unsigned int i = 0; i < rank; ++i) { outputDimensionSizes[i] = inputShape[i] + m_Param.m_PadList[i].first + m_Param.m_PadList[i].second; } TensorShape tensorShape = TensorShape( rank, outputDimensionSizes.data()); return std::vector<TensorShape>({ tensorShape }); } void PadLayer::ValidateTensorShapesFromInputs() { VerifyLayerConnections(1, CHECK_LOCATION()); const TensorShape& outputShape = GetOutputSlot(0).GetTensorInfo().GetShape(); VerifyShapeInferenceType(outputShape, m_ShapeInferenceMethod); auto inferredShapes = InferOutputShapes({ GetInputSlot(0).GetConnection()->GetTensorInfo().GetShape() }); ARMNN_ASSERT(inferredShapes.size() == 1); ValidateAndCopyShape(outputShape, inferredShapes[0], m_ShapeInferenceMethod, "PadLayer"); } ARMNN_NO_DEPRECATE_WARN_BEGIN void PadLayer::Accept(ILayerVisitor& visitor) const { visitor.VisitPadLayer(this, GetParameters(), GetName()); } ARMNN_NO_DEPRECATE_WARN_END } // namespace armnn
c++
code
2,517
517
#include "parse/node_expr_index.hpp" #include "utilities.hpp" namespace parse { IndexExprNode::IndexExprNode( NodePtr lhs, lex::Token open, std::vector<NodePtr> args, std::vector<lex::Token> commas, lex::Token close) : m_lhs{std::move(lhs)}, m_open{std::move(open)}, m_args{std::move(args)}, m_commas{std::move(commas)}, m_close{std::move(close)} {} auto IndexExprNode::operator==(const Node& rhs) const noexcept -> bool { const auto r = dynamic_cast<const IndexExprNode*>(&rhs); return r != nullptr && *m_lhs == *r->m_lhs && nodesEqual(m_args, r->m_args); } auto IndexExprNode::operator!=(const Node& rhs) const noexcept -> bool { return !IndexExprNode::operator==(rhs); } auto IndexExprNode::operator[](unsigned int i) const -> const Node& { if (i == 0) { return *m_lhs; } if (i > m_args.size()) { throw std::out_of_range{"No child at given index"}; } return *m_args[i - 1]; } auto IndexExprNode::getChildCount() const -> unsigned int { return m_args.size() + 1; } auto IndexExprNode::getSpan() const -> input::Span { return input::Span::combine(m_lhs->getSpan(), m_close.getSpan()); } auto IndexExprNode::accept(NodeVisitor* visitor) const -> void { visitor->visit(*this); } auto IndexExprNode::print(std::ostream& out) const -> std::ostream& { return out << "[]"; } // Factories. auto indexExprNode( NodePtr lhs, lex::Token open, std::vector<NodePtr> args, std::vector<lex::Token> commas, lex::Token close) -> NodePtr { if (lhs == nullptr) { throw std::invalid_argument{"lhs cannot be null"}; } if (args.empty()) { throw std::invalid_argument{"args cannot be empty"}; } if (anyNodeNull(args)) { throw std::invalid_argument{"args cannot contain a nullptr"}; } if (commas.size() != args.size() - 1) { throw std::invalid_argument{"Incorrect number of commas"}; } return std::unique_ptr<IndexExprNode>{new IndexExprNode{ std::move(lhs), std::move(open), std::move(args), std::move(commas), std::move(close)}}; } } // namespace parse
c++
code
2,069
606
#include "CStreamer.h" #include "CRtspSession.h" #include <stdio.h> CStreamer::CStreamer(u_short width, u_short height) : m_Clients() { printf("Creating RTSP streamer\n"); m_RtpServerPort = 0; m_RtcpServerPort = 0; m_SequenceNumber = 0; m_Timestamp = 0; m_SendIdx = 0; m_RtpSocket = NULLSOCKET; m_RtcpSocket = NULLSOCKET; m_width = width; m_height = height; m_prevMsec = 0; m_udpRefCount = 0; }; CStreamer::~CStreamer() { LinkedListElement* element = m_Clients.m_Next; CRtspSession* session = NULL; while (element != &m_Clients) { session = static_cast<CRtspSession*>(element); element = element->m_Next; delete session; } }; void CStreamer::addSession(WiFiClient& aClient) { // printf("CStreamer::addSession\n"); CRtspSession* session = new CRtspSession(aClient, this); // our threads RTSP session and state // we have it stored in m_Clients } int CStreamer::SendRtpPacket(unsigned const char * jpeg, int jpegLen, int fragmentOffset, BufPtr quant0tbl, BufPtr quant1tbl) { // printf("CStreamer::SendRtpPacket offset:%d - begin\n", fragmentOffset); #define KRtpHeaderSize 12 // size of the RTP header #define KJpegHeaderSize 8 // size of the special JPEG payload header #define MAX_FRAGMENT_SIZE 1100 // FIXME, pick more carefully int fragmentLen = MAX_FRAGMENT_SIZE; if(fragmentLen + fragmentOffset > jpegLen) // Shrink last fragment if needed fragmentLen = jpegLen - fragmentOffset; bool isLastFragment = (fragmentOffset + fragmentLen) == jpegLen; if (!m_Clients.NotEmpty()) { return isLastFragment ? 0 : fragmentOffset; } // Do we have custom quant tables? If so include them per RFC bool includeQuantTbl = quant0tbl && quant1tbl && fragmentOffset == 0; uint8_t q = includeQuantTbl ? 128 : 0x5e; static char RtpBuf[2048]; // Note: we assume single threaded, this large buf we keep off of the tiny stack int RtpPacketSize = fragmentLen + KRtpHeaderSize + KJpegHeaderSize + (includeQuantTbl ? (4 + 64 * 2) : 0); memset(RtpBuf,0x00,sizeof(RtpBuf)); // Prepare the first 4 byte of the packet. This is the Rtp over Rtsp header in case of TCP based transport RtpBuf[0] = '$'; // magic number RtpBuf[1] = 0; // number of multiplexed subchannel on RTPS connection - here the RTP channel RtpBuf[2] = (RtpPacketSize & 0x0000FF00) >> 8; RtpBuf[3] = (RtpPacketSize & 0x000000FF); // Prepare the 12 byte RTP header RtpBuf[4] = 0x80; // RTP version RtpBuf[5] = 0x1a | (isLastFragment ? 0x80 : 0x00); // JPEG payload (26) and marker bit RtpBuf[7] = m_SequenceNumber & 0x0FF; // each packet is counted with a sequence counter RtpBuf[6] = m_SequenceNumber >> 8; RtpBuf[8] = (m_Timestamp & 0xFF000000) >> 24; // each image gets a timestamp RtpBuf[9] = (m_Timestamp & 0x00FF0000) >> 16; RtpBuf[10] = (m_Timestamp & 0x0000FF00) >> 8; RtpBuf[11] = (m_Timestamp & 0x000000FF); RtpBuf[12] = 0x13; // 4 byte SSRC (sychronization source identifier) RtpBuf[13] = 0xf9; // we just an arbitrary number here to keep it simple RtpBuf[14] = 0x7e; RtpBuf[15] = 0x67; // Prepare the 8 byte payload JPEG header RtpBuf[16] = 0x00; // type specific RtpBuf[17] = (fragmentOffset & 0x00FF0000) >> 16; // 3 byte fragmentation offset for fragmented images RtpBuf[18] = (fragmentOffset & 0x0000FF00) >> 8; RtpBuf[19] = (fragmentOffset & 0x000000FF); /* These sampling factors indicate that the chrominance components of type 0 video is downsampled horizontally by 2 (often called 4:2:2) while the chrominance components of type 1 video are downsampled both horizontally and vertically by 2 (often called 4:2:0). */ RtpBuf[20] = 0x00; // type (fixme might be wrong for camera data) https://tools.ietf.org/html/rfc2435 RtpBuf[21] = q; // quality scale factor was 0x5e RtpBuf[22] = m_width / 8; // width / 8 RtpBuf[23] = m_height / 8; // height / 8 int headerLen = 24; // Inlcuding jpeg header but not qant table header if(includeQuantTbl) { // we need a quant header - but only in first packet of the frame //printf("inserting quanttbl\n"); RtpBuf[24] = 0; // MBZ RtpBuf[25] = 0; // 8 bit precision RtpBuf[26] = 0; // MSB of lentgh int numQantBytes = 64; // Two 64 byte tables RtpBuf[27] = 2 * numQantBytes; // LSB of length headerLen += 4; memcpy(RtpBuf + headerLen, quant0tbl, numQantBytes); headerLen += numQantBytes; memcpy(RtpBuf + headerLen, quant1tbl, numQantBytes); headerLen += numQantBytes; } // printf("Sending timestamp %d, seq %d, fragoff %d, fraglen %d, jpegLen %d\n", m_Timestamp, m_SequenceNumber, fragmentOffset, fragmentLen, jpegLen); // append the JPEG scan data to the RTP buffer memcpy(RtpBuf + headerLen,jpeg + fragmentOffset, fragmentLen); fragmentOffset += fragmentLen; m_SequenceNumber++; // prepare the packet counter for the next packet IPADDRESS otherip; IPPORT otherport; // RTP marker bit must be set on last fragment LinkedListElement* element = m_Clients.m_Next; CRtspSession* session = NULL; while (element != &m_Clients) { session = static_cast<CRtspSession*>(element); if (session->m_streaming && !session->m_stopped) { if (session->isTcpTransport()) // RTP over RTSP - we send the buffer + 4 byte additional header socketsend(session->getClient(),RtpBuf,RtpPacketSize + 4); else // UDP - we send just the buffer by skipping the 4 byte RTP over RTSP header { socketpeeraddr(session->getClient(), &otherip, &otherport); udpsocketsend(m_RtpSocket,&RtpBuf[4],RtpPacketSize, otherip, session->getRtpClientPort()); } } element = element->m_Next; } // printf("CStreamer::SendRtpPacket offset:%d - end\n", fragmentOffset); return isLastFragment ? 0 : fragmentOffset; }; u_short CStreamer::GetRtpServerPort() { return m_RtpServerPort; }; u_short CStreamer::GetRtcpServerPort() { return m_RtcpServerPort; }; bool CStreamer::InitUdpTransport(void) { if (m_udpRefCount != 0) { ++m_udpRefCount; return true; } for (u_short P = 6970; P < 0xFFFE; P += 2) { m_RtpSocket = udpsocketcreate(P); if (m_RtpSocket) { // Rtp socket was bound successfully. Lets try to bind the consecutive Rtsp socket m_RtcpSocket = udpsocketcreate(P + 1); if (m_RtcpSocket) { m_RtpServerPort = P; m_RtcpServerPort = P+1; break; } else { udpsocketclose(m_RtpSocket); udpsocketclose(m_RtcpSocket); }; } }; ++m_udpRefCount; return true; } void CStreamer::ReleaseUdpTransport(void) { --m_udpRefCount; if (m_udpRefCount == 0) { m_RtpServerPort = 0; m_RtcpServerPort = 0; udpsocketclose(m_RtpSocket); udpsocketclose(m_RtcpSocket); m_RtpSocket = NULLSOCKET; m_RtcpSocket = NULLSOCKET; } } /** Call handleRequests on all sessions */ bool CStreamer::handleRequests(uint32_t readTimeoutMs) { bool retVal = true; LinkedListElement* element = m_Clients.m_Next; while(element != &m_Clients) { CRtspSession* session = static_cast<CRtspSession*>(element); retVal &= session->handleRequests(readTimeoutMs); element = element->m_Next; if (session->m_stopped) { // remove session here, so we wont have to send to it delete session; } } return retVal; } void CStreamer::streamFrame(unsigned const char *data, uint32_t dataLen, uint32_t curMsec) { if(m_prevMsec == 0) // first frame init our timestamp m_prevMsec = curMsec; // compute deltat (being careful to handle clock rollover with a little lie) uint32_t deltams = (curMsec >= m_prevMsec) ? curMsec - m_prevMsec : 100; m_prevMsec = curMsec; // locate quant tables if possible BufPtr qtable0, qtable1; if(!decodeJPEGfile(&data, &dataLen, &qtable0, &qtable1)) { printf("can't decode jpeg data\n"); return; } int offset = 0; do { offset = SendRtpPacket(data, dataLen, offset, qtable0, qtable1); } while(offset != 0); // Increment ONLY after a full frame uint32_t units = 90000; // Hz per RFC 2435 m_Timestamp += (units * deltams / 1000); // fixed timestamp increment for a frame rate of 25fps m_SendIdx++; if (m_SendIdx > 1) m_SendIdx = 0; }; #include <assert.h> // search for a particular JPEG marker, moves *start to just after that marker // This function fixes up the provided start ptr to point to the // actual JPEG stream data and returns the number of bytes skipped // APP0 e0 // DQT db // DQT db // DHT c4 // DHT c4 // DHT c4 // DHT c4 // SOF0 c0 baseline (not progressive) 3 color 0x01 Y, 0x21 2h1v, 0x00 tbl0 // - 0x02 Cb, 0x11 1h1v, 0x01 tbl1 - 0x03 Cr, 0x11 1h1v, 0x01 tbl1 // therefore 4:2:2, with two separate quant tables (0 and 1) // SOS da // EOI d9 (no need to strip data after this RFC says client will discard) bool findJPEGheader(BufPtr *start, uint32_t *len, uint8_t marker) { // per https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format unsigned const char *bytes = *start; // kinda skanky, will break if unlucky and the headers inxlucde 0xffda // might fall off array if jpeg is invalid // FIXME - return false instead while(bytes - *start < *len) { uint8_t framing = *bytes++; // better be 0xff if(framing != 0xff) { printf("malformed jpeg, framing=%x\n", framing); return false; } uint8_t typecode = *bytes++; if(typecode == marker) { unsigned skipped = bytes - *start; //printf("found marker 0x%x, skipped %d\n", marker, skipped); *start = bytes; // shrink len for the bytes we just skipped *len -= skipped; return true; } else { // not the section we were looking for, skip the entire section switch(typecode) { case 0xd8: // start of image { break; // no data to skip } case 0xe0: // app0 case 0xdb: // dqt case 0xc4: // dht case 0xc0: // sof0 case 0xda: // sos { // standard format section with 2 bytes for len. skip that many bytes uint32_t len = bytes[0] * 256 + bytes[1]; //printf("skipping section 0x%x, %d bytes\n", typecode, len); bytes += len; break; } default: printf("unexpected jpeg typecode 0x%x\n", typecode); break; } } } printf("failed to find jpeg marker 0x%x", marker); return false; } // the scan data uses byte stuffing to guarantee anything that starts with 0xff // followed by something not zero, is a new section. Look for that marker and return the ptr // pointing there void skipScanBytes(BufPtr *start) { BufPtr bytes = *start; while(true) { // FIXME, check against length while(*bytes++ != 0xff); if(*bytes++ != 0) { *start = bytes - 2; // back up to the 0xff marker we just found return; } } } void nextJpegBlock(BufPtr *bytes) { uint32_t len = (*bytes)[0] * 256 + (*bytes)[1]; //printf("going to next jpeg block %d bytes\n", len); *bytes += len; } // When JPEG is stored as a file it is wrapped in a container // This function fixes up the provided start ptr to point to the // actual JPEG stream data and returns the number of bytes skipped bool decodeJPEGfile(BufPtr *start, uint32_t *len, BufPtr *qtable0, BufPtr *qtable1) { // per https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format unsigned const char *bytes = *start; if(!findJPEGheader(&bytes, len, 0xd8)) // better at least look like a jpeg file return false; // FAILED! // Look for quant tables if they are present *qtable0 = NULL; *qtable1 = NULL; BufPtr quantstart = *start; uint32_t quantlen = *len; if(!findJPEGheader(&quantstart, &quantlen, 0xdb)) { printf("error can't find quant table 0\n"); } else { // printf("found quant table %x\n", quantstart[2]); *qtable0 = quantstart + 3; // 3 bytes of header skipped nextJpegBlock(&quantstart); if(!findJPEGheader(&quantstart, &quantlen, 0xdb)) { printf("error can't find quant table 1\n"); } else { // printf("found quant table %x\n", quantstart[2]); } *qtable1 = quantstart + 3; nextJpegBlock(&quantstart); } if(!findJPEGheader(start, len, 0xda)) return false; // FAILED! // Skip the header bytes of the SOS marker FIXME why doesn't this work? uint32_t soslen = (*start)[0] * 256 + (*start)[1]; *start += soslen; *len -= soslen; // start scanning the data portion of the scan to find the end marker BufPtr endmarkerptr = *start; uint32_t endlen = *len; skipScanBytes(&endmarkerptr); if(!findJPEGheader(&endmarkerptr, &endlen, 0xd9)) return false; // FAILED! // endlen must now be the # of bytes between the start of our scan and // the end marker, tell the caller to ignore bytes afterwards *len = endmarkerptr - *start; return true; }
c++
code
14,649
2,785
/* * Copyright (c) 2020, The SerenityOS developers. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Kernel/ACPI/Parser.h> #include <Kernel/Devices/KeyboardDevice.h> #include <Kernel/Devices/PS2MouseDevice.h> #include <Kernel/IO.h> namespace Kernel { static I8042Controller* s_the; void I8042Controller::initialize() { if (ACPI::Parser::the()->have_8042()) new I8042Controller; } I8042Controller& I8042Controller::the() { ASSERT(s_the); return *s_the; } I8042Controller::I8042Controller() { ASSERT(!s_the); s_the = this; u8 configuration; { ScopedSpinLock lock(m_lock); // Disable devices do_wait_then_write(I8042_STATUS, 0xad); do_wait_then_write(I8042_STATUS, 0xa7); // ignored if it doesn't exist // Drain buffers do_drain(); do_wait_then_write(I8042_STATUS, 0x20); configuration = do_wait_then_read(I8042_BUFFER); do_wait_then_write(I8042_STATUS, 0x60); configuration &= ~3; // Disable IRQs for all do_wait_then_write(I8042_BUFFER, configuration); m_is_dual_channel = (configuration & (1 << 5)) != 0; dbg() << "I8042: " << (m_is_dual_channel ? "Dual" : "Single") << " channel controller"; // Perform controller self-test do_wait_then_write(I8042_STATUS, 0xaa); if (do_wait_then_read(I8042_BUFFER) == 0x55) { // Restore configuration in case the controller reset do_wait_then_write(I8042_STATUS, 0x60); do_wait_then_write(I8042_BUFFER, configuration); } else { dbgln("I8042: Controller self test failed"); } // Test ports and enable them if available do_wait_then_write(I8042_STATUS, 0xab); // test m_devices[0].available = (do_wait_then_read(I8042_BUFFER) == 0); if (m_devices[0].available) { do_wait_then_write(I8042_STATUS, 0xae); //enable configuration |= 1; configuration &= ~(1 << 4); } else { dbgln("I8042: Keyboard port not available"); } if (m_is_dual_channel) { do_wait_then_write(I8042_STATUS, 0xa9); // test m_devices[1].available = (do_wait_then_read(I8042_BUFFER) == 0); if (m_devices[1].available) { do_wait_then_write(I8042_STATUS, 0xa8); // enable configuration |= 2; configuration &= ~(1 << 5); } else { dbgln("I8042: Mouse port not available"); } } // Enable IRQs for the ports that are usable if (m_devices[0].available || m_devices[1].available) { configuration &= ~0x30; // renable clocks do_wait_then_write(I8042_STATUS, 0x60); do_wait_then_write(I8042_BUFFER, configuration); } } // Try to detect and initialize the devices if (m_devices[0].available) { if (KeyboardDevice::the().initialize()) { m_devices[0].device = &KeyboardDevice::the(); } else { dbgln("I8042: Keyboard device failed to initialize, disable"); m_devices[0].available = false; configuration &= ~1; configuration |= 1 << 4; ScopedSpinLock lock(m_lock); do_wait_then_write(I8042_STATUS, 0x60); do_wait_then_write(I8042_BUFFER, configuration); } } if (m_devices[1].available) { if (PS2MouseDevice::the().initialize()) { m_devices[1].device = &PS2MouseDevice::the(); } else { dbgln("I8042: Mouse device failed to initialize, disable"); m_devices[1].available = false; configuration |= 1 << 5; ScopedSpinLock lock(m_lock); do_wait_then_write(I8042_STATUS, 0x60); do_wait_then_write(I8042_BUFFER, configuration); } } // Enable IRQs after both are detected and initialized if (m_devices[0].device) m_devices[0].device->enable_interrupts(); if (m_devices[1].device) m_devices[1].device->enable_interrupts(); } void I8042Controller::irq_process_input_buffer(Device) { ASSERT(Processor::current().in_irq()); u8 status = IO::in8(I8042_STATUS); if (!(status & I8042_BUFFER_FULL)) return; Device data_for_device = ((status & I8042_WHICH_BUFFER) == I8042_MOUSE_BUFFER) ? Device::Mouse : Device::Keyboard; u8 byte = IO::in8(I8042_BUFFER); if (auto* device = m_devices[data_for_device == Device::Keyboard ? 0 : 1].device) device->irq_handle_byte_read(byte); } void I8042Controller::do_drain() { for (;;) { u8 status = IO::in8(I8042_STATUS); if (!(status & I8042_BUFFER_FULL)) return; IO::in8(I8042_BUFFER); } } bool I8042Controller::do_reset_device(Device device) { ASSERT(device != Device::None); ASSERT(m_lock.is_locked()); ASSERT(!Processor::current().in_irq()); if (do_send_command(device, 0xff) != I8042_ACK) return false; // Wait until we get the self-test result return do_wait_then_read(I8042_BUFFER) == 0xaa; } u8 I8042Controller::do_send_command(Device device, u8 command) { ASSERT(device != Device::None); ASSERT(m_lock.is_locked()); ASSERT(!Processor::current().in_irq()); return do_write_to_device(device, command); } u8 I8042Controller::do_send_command(Device device, u8 command, u8 data) { ASSERT(device != Device::None); ASSERT(m_lock.is_locked()); ASSERT(!Processor::current().in_irq()); u8 response = do_write_to_device(device, command); if (response == I8042_ACK) response = do_write_to_device(device, data); return response; } u8 I8042Controller::do_write_to_device(Device device, u8 data) { ASSERT(device != Device::None); ASSERT(m_lock.is_locked()); ASSERT(!Processor::current().in_irq()); int attempts = 0; u8 response; do { if (device != Device::Keyboard) { prepare_for_output(); IO::out8(I8042_STATUS, 0xd4); } prepare_for_output(); IO::out8(I8042_BUFFER, data); response = do_wait_then_read(I8042_BUFFER); } while (response == I8042_RESEND && ++attempts < 3); if (attempts >= 3) dbgln("Failed to write byte to device, gave up"); return response; } u8 I8042Controller::do_read_from_device(Device device) { ASSERT(device != Device::None); prepare_for_input(device); return IO::in8(I8042_BUFFER); } void I8042Controller::prepare_for_input(Device device) { ASSERT(m_lock.is_locked()); const u8 buffer_type = device == Device::Keyboard ? I8042_KEYBOARD_BUFFER : I8042_MOUSE_BUFFER; for (;;) { u8 status = IO::in8(I8042_STATUS); if ((status & I8042_BUFFER_FULL) && (device == Device::None || ((status & I8042_WHICH_BUFFER) == buffer_type))) return; } } void I8042Controller::prepare_for_output() { ASSERT(m_lock.is_locked()); for (;;) { if (!(IO::in8(I8042_STATUS) & 2)) return; } } void I8042Controller::do_wait_then_write(u8 port, u8 data) { ASSERT(m_lock.is_locked()); prepare_for_output(); IO::out8(port, data); } u8 I8042Controller::do_wait_then_read(u8 port) { ASSERT(m_lock.is_locked()); prepare_for_input(Device::None); return IO::in8(port); } }
c++
code
8,675
1,771
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <config.h> #include "Util.hpp" #include <csignal> #include <sys/poll.h> #ifdef __linux__ # include <sys/prctl.h> # include <sys/syscall.h> # include <sys/vfs.h> # include <sys/resource.h> #elif defined __FreeBSD__ # include <sys/resource.h> # include <sys/thr.h> #elif defined IOS #import <Foundation/Foundation.h> #endif #include <sys/stat.h> #include <sys/uio.h> #include <sys/types.h> #include <unistd.h> #include <dirent.h> #include <fcntl.h> #include <atomic> #include <cassert> #include <chrono> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iomanip> #include <iostream> #include <mutex> #include <unordered_map> #include <random> #include <sstream> #include <string> #include <thread> #include <limits> #include <Poco/Base64Encoder.h> #include <Poco/HexBinaryEncoder.h> #include <Poco/ConsoleChannel.h> #include <Poco/Exception.h> #include <Poco/Format.h> #include <Poco/JSON/JSON.h> #include <Poco/JSON/Object.h> #include <Poco/JSON/Parser.h> #include <Poco/RandomStream.h> #include <Poco/TemporaryFile.h> #include <Poco/Util/Application.h> #include "Common.hpp" #include "Log.hpp" #include "Protocol.hpp" #include "TraceEvent.hpp" namespace Util { namespace rng { static std::random_device _rd; static std::mutex _rngMutex; static Poco::RandomBuf _randBuf; // Create the prng with a random-device for seed. // If we don't have a hardware random-device, we will get the same seed. // In that case we are better off with an arbitrary, but changing, seed. static std::mt19937_64 _rng = std::mt19937_64(_rd.entropy() ? _rd() : (clock() + getpid())); // A new seed is used to shuffle the sequence. // N.B. Always reseed after getting forked! void reseed() { _rng.seed(_rd.entropy() ? _rd() : (clock() + getpid())); } // Returns a new random number. unsigned getNext() { std::unique_lock<std::mutex> lock(_rngMutex); return _rng(); } std::vector<char> getBytes(const std::size_t length) { std::vector<char> v(length); _randBuf.readFromDevice(v.data(), v.size()); return v; } /// Generate a string of random characters. std::string getHexString(const std::size_t length) { std::stringstream ss; Poco::HexBinaryEncoder hex(ss); hex.rdbuf()->setLineLength(0); // Don't insert line breaks. hex.write(getBytes(length).data(), length); hex.close(); // Flush. return ss.str().substr(0, length); } /// Generate a string of harder random characters. std::string getHardRandomHexString(const std::size_t length) { std::stringstream ss; Poco::HexBinaryEncoder hex(ss); // a poor fallback but something. std::vector<char> random = getBytes(length); int fd = open("/dev/urandom", O_RDONLY); int len = 0; if (fd < 0 || (len = read(fd, random.data(), length)) < 0 || std::size_t(len) < length) { LOG_ERR("failed to read " << length << " hard random bytes, got " << len << " for hash: " << errno); } close(fd); hex.rdbuf()->setLineLength(0); // Don't insert line breaks. hex.write(random.data(), length); hex.close(); // Flush. return ss.str().substr(0, length); } /// Generates a random string in Base64. /// Note: May contain '/' characters. std::string getB64String(const std::size_t length) { std::stringstream ss; Poco::Base64Encoder b64(ss); b64.write(getBytes(length).data(), length); return ss.str().substr(0, length); } std::string getFilename(const std::size_t length) { std::string s = getB64String(length * 2); s.erase(std::remove_if(s.begin(), s.end(), [](const std::string::value_type& c) { // Remove undesirable characters in a filename. return c == '/' || c == ' ' || c == '+'; }), s.end()); return s.substr(0, length); } } #if !MOBILEAPP int getProcessThreadCount() { DIR *fdDir = opendir("/proc/self/task"); if (!fdDir) { LOG_ERR("No proc mounted"); return -1; } int tasks = 0; struct dirent *i; while ((i = readdir(fdDir))) { if (i->d_name[0] != '.') tasks++; } closedir(fdDir); return tasks; } // close what we have - far faster than going up to a 1m open_max eg. static bool closeFdsFromProc(std::map<int, int> *mapFdsToKeep = nullptr) { DIR *fdDir = opendir("/proc/self/fd"); if (!fdDir) return false; struct dirent *i; while ((i = readdir(fdDir))) { if (i->d_name[0] == '.') continue; char *e = NULL; errno = 0; long fd = strtol(i->d_name, &e, 10); if (errno != 0 || !e || *e) continue; if (fd == dirfd(fdDir)) continue; if (fd < 3) continue; if (mapFdsToKeep && mapFdsToKeep->find(fd) != mapFdsToKeep->end()) continue; if (close(fd) < 0) std::cerr << "Unexpected failure to close fd " << fd << std::endl; } closedir(fdDir); return true; } static void closeFds(std::map<int, int> *mapFdsToKeep = nullptr) { if (!closeFdsFromProc(mapFdsToKeep)) { std::cerr << "Couldn't close fds efficiently from /proc" << std::endl; for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd) if (mapFdsToKeep->find(fd) != mapFdsToKeep->end()) close(fd); } } int spawnProcess(const std::string &cmd, const StringVector &args, const std::vector<int>* fdsToKeep, int *stdInput) { int pipeFds[2] = { -1, -1 }; if (stdInput) { if (pipe2(pipeFds, O_NONBLOCK) < 0) { LOG_ERR("Out of file descriptors spawning " << cmd); throw Poco::SystemException("Out of file descriptors"); } } // Create a vector of zero-terminated strings. std::vector<std::string> argStrings; for (const auto& arg : args) argStrings.push_back(args.getParam(arg)); std::vector<char *> params; params.push_back(const_cast<char *>(cmd.c_str())); for (const auto& i : argStrings) params.push_back(const_cast<char *>(i.c_str())); params.push_back(nullptr); std::map<int, int> mapFdsToKeep; if (fdsToKeep) for (const auto& i : *fdsToKeep) mapFdsToKeep[i] = i; int pid = fork(); if (pid < 0) { LOG_ERR("Failed to fork for command '" << cmd); throw Poco::SystemException("Failed to fork for command ", cmd); } else if (pid == 0) // child { if (stdInput) dup2(pipeFds[0], STDIN_FILENO); closeFds(&mapFdsToKeep); int ret = execvp(params[0], &params[0]); if (ret < 0) LOG_SFL("Failed to exec command '" << cmd << '\''); Log::shutdown(); _exit(42); } // else spawning process still if (stdInput) { close(pipeFds[0]); *stdInput = pipeFds[1]; } return pid; } #endif std::string encodeId(const std::uint64_t number, const int padding) { std::ostringstream oss; oss << std::hex << std::setw(padding) << std::setfill('0') << number; return oss.str(); } std::uint64_t decodeId(const std::string& str) { std::uint64_t id = 0; std::stringstream ss; ss << std::hex << str; ss >> id; return id; } bool windowingAvailable() { return std::getenv("DISPLAY") != nullptr; } #if !MOBILEAPP static const char *startsWith(const char *line, const char *tag) { std::size_t len = std::strlen(tag); if (!strncmp(line, tag, len)) { while (!isdigit(line[len]) && line[len] != '\0') ++len; return line + len; } return nullptr; } std::string getHumanizedBytes(unsigned long nBytes) { constexpr unsigned factor = 1024; short count = 0; float val = nBytes; while (val >= factor && count < 4) { val /= factor; count++; } std::string unit; switch (count) { case 0: unit = ""; break; case 1: unit = "ki"; break; case 2: unit = "Mi"; break; case 3: unit = "Gi"; break; case 4: unit = "Ti"; break; default: assert(false); } unit += 'B'; std::stringstream ss; ss << std::fixed << std::setprecision(1) << val << ' ' << unit; return ss.str(); } std::size_t getTotalSystemMemoryKb() { std::size_t totalMemKb = 0; FILE* file = fopen("/proc/meminfo", "r"); if (file != nullptr) { char line[4096] = { 0 }; while (fgets(line, sizeof(line), file)) { const char* value; if ((value = startsWith(line, "MemTotal:"))) { totalMemKb = atoi(value); break; } } } return totalMemKb; } std::pair<std::size_t, std::size_t> getPssAndDirtyFromSMaps(FILE* file) { std::size_t numPSSKb = 0; std::size_t numDirtyKb = 0; if (file) { rewind(file); char line[4096] = { 0 }; while (fgets(line, sizeof (line), file)) { const char *value; // Shared_Dirty is accounted for by forkit's RSS if ((value = startsWith(line, "Private_Dirty:"))) { numDirtyKb += atoi(value); } else if ((value = startsWith(line, "Pss:"))) { numPSSKb += atoi(value); } } } return std::make_pair(numPSSKb, numDirtyKb); } std::string getMemoryStats(FILE* file) { const std::pair<std::size_t, std::size_t> pssAndDirtyKb = getPssAndDirtyFromSMaps(file); std::ostringstream oss; oss << "procmemstats: pid=" << getpid() << " pss=" << pssAndDirtyKb.first << " dirty=" << pssAndDirtyKb.second; LOG_TRC("Collected " << oss.str()); return oss.str(); } std::size_t getMemoryUsagePSS(const pid_t pid) { if (pid > 0) { const auto cmd = "/proc/" + std::to_string(pid) + "/smaps"; FILE* fp = fopen(cmd.c_str(), "r"); if (fp != nullptr) { const std::size_t pss = getPssAndDirtyFromSMaps(fp).first; fclose(fp); return pss; } } return 0; } std::size_t getMemoryUsageRSS(const pid_t pid) { static const int pageSizeBytes = getpagesize(); std::size_t rss = 0; if (pid > 0) { rss = getStatFromPid(pid, 23); rss *= pageSizeBytes; rss /= 1024; return rss; } return 0; } std::size_t getCpuUsage(const pid_t pid) { if (pid > 0) { std::size_t totalJiffies = 0; totalJiffies += getStatFromPid(pid, 13); totalJiffies += getStatFromPid(pid, 14); return totalJiffies; } return 0; } std::size_t getStatFromPid(const pid_t pid, int ind) { if (pid > 0) { const auto cmd = "/proc/" + std::to_string(pid) + "/stat"; FILE* fp = fopen(cmd.c_str(), "r"); if (fp != nullptr) { char line[4096] = { 0 }; if (fgets(line, sizeof (line), fp)) { const std::string s(line); int index = 1; std::size_t pos = s.find(' '); while (pos != std::string::npos) { if (index == ind) { fclose(fp); return strtol(&s[pos], nullptr, 10); } ++index; pos = s.find(' ', pos + 1); } } } } return 0; } void setProcessAndThreadPriorities(const pid_t pid, int prio) { int res = setpriority(PRIO_PROCESS, pid, prio); LOG_TRC("Lowered kit [" << (int)pid << "] priority: " << prio << " with result: " << res); #ifdef __linux__ // rely on Linux thread-id priority setting to drop this thread' priority pid_t tid = getThreadId(); res = setpriority(PRIO_PROCESS, tid, prio); LOG_TRC("Lowered own thread [" << (int)tid << "] priority: " << prio << " with result: " << res); #endif } #endif // !MOBILEAPP std::string replace(std::string result, const std::string& a, const std::string& b) { const std::size_t aSize = a.size(); if (aSize > 0) { const std::size_t bSize = b.size(); std::string::size_type pos = 0; while ((pos = result.find(a, pos)) != std::string::npos) { result = result.replace(pos, aSize, b); pos += bSize; // Skip the replacee to avoid endless recursion. } } return result; } std::string formatLinesForLog(const std::string& s) { std::string r; std::string::size_type n = s.size(); if (n > 0 && s.back() == '\n') r = s.substr(0, n-1); else r = s; return replace(r, "\n", " / "); } // prctl(2) supports names of up to 16 characters, including null-termination. // Although in practice on linux more than 16 chars is supported. static thread_local char ThreadName[32] = {0}; static_assert(sizeof(ThreadName) >= 16, "ThreadName should have a statically known size, and not be a pointer."); void setThreadName(const std::string& s) { // Copy the current name. const std::string knownAs = ThreadName[0] ? "known as [" + std::string(ThreadName) + ']' : "unnamed"; // Set the new name. strncpy(ThreadName, s.c_str(), sizeof(ThreadName) - 1); ThreadName[sizeof(ThreadName) - 1] = '\0'; #ifdef __linux__ if (prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(s.c_str()), 0, 0, 0) != 0) LOG_SYS("Cannot set thread name of " << getThreadId() << " (" << std::hex << std::this_thread::get_id() << std::dec << ") of process " << getpid() << " currently " << knownAs << " to [" << s << ']'); else LOG_INF("Thread " << getThreadId() << " (" << std::hex << std::this_thread::get_id() << std::dec << ") of process " << getpid() << " formerly " << knownAs << " is now called [" << s << ']'); #elif defined IOS [[NSThread currentThread] setName:[NSString stringWithUTF8String:ThreadName]]; LOG_INF("Thread " << getThreadId() << ") is now called [" << s << ']'); #endif // Emit a metadata Trace Event identifying this thread. This will invoke a different function // depending on which executable this is in. TraceEvent::emitOneRecordingIfEnabled("{\"name\":\"thread_name\",\"ph\":\"M\",\"args\":{\"name\":\"" + s + "\"},\"pid\":" + std::to_string(getpid()) + ",\"tid\":" + std::to_string(Util::getThreadId()) + "},\n"); } const char *getThreadName() { // Main process and/or not set yet. if (ThreadName[0] == '\0') { #ifdef __linux__ // prctl(2): The buffer should allow space for up to 16 bytes; the returned string will be null-terminated. if (prctl(PR_GET_NAME, reinterpret_cast<unsigned long>(ThreadName), 0, 0, 0) != 0) strncpy(ThreadName, "<noid>", sizeof(ThreadName) - 1); #elif defined IOS const char *const name = [[[NSThread currentThread] name] UTF8String]; strncpy(ThreadName, name, sizeof(ThreadName) - 1); #endif ThreadName[sizeof(ThreadName) - 1] = '\0'; } // Avoid so many redundant system calls return ThreadName; } #if defined __linux__ static thread_local pid_t ThreadTid = 0; pid_t getThreadId() #else static thread_local long ThreadTid = 0; long getThreadId() #endif { // Avoid so many redundant system calls #if defined __linux__ if (!ThreadTid) ThreadTid = ::syscall(SYS_gettid); return ThreadTid; #elif defined __FreeBSD__ if (!ThreadTid) thr_self(&ThreadTid); return ThreadTid; #else static long threadCounter = 1; if (!ThreadTid) ThreadTid = threadCounter++; return ThreadTid; #endif } void getVersionInfo(std::string& version, std::string& hash) { version = std::string(COOLWSD_VERSION); hash = std::string(COOLWSD_VERSION_HASH); hash.resize(std::min(8, (int)hash.length())); } std::string getProcessIdentifier() { static std::string id = Util::rng::getHexString(8); return id; } std::string getVersionJSON() { std::string version, hash; Util::getVersionInfo(version, hash); return "{ \"Version\": \"" + version + "\", " "\"Hash\": \"" + hash + "\", " "\"Protocol\": \"" + COOLProtocol::GetProtocolVersion() + "\", " "\"Id\": \"" + Util::getProcessIdentifier() + "\" }"; } std::string UniqueId() { static std::atomic_int counter(0); return std::to_string(getpid()) + '/' + std::to_string(counter++); } std::map<std::string, std::string> JsonToMap(const std::string& jsonString) { std::map<std::string, std::string> map; if (jsonString.empty()) return map; Poco::JSON::Parser parser; const Poco::Dynamic::Var result = parser.parse(jsonString); const auto& json = result.extract<Poco::JSON::Object::Ptr>(); st
c++
code
20,000
4,493
// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> #include <stdio.h> #include <iostream> #include <gtest/gtest.h> #include "common/logging.h" #include "util/url-coding.h" using namespace std; namespace impala { // Tests encoding/decoding of input. If expected_encoded is non-empty, the // encoded string is validated against it. void TestUrl(const string& input, const string& expected_encoded, bool hive_compat) { string intermediate; UrlEncode(input, &intermediate, hive_compat); string output; if (!expected_encoded.empty()) { EXPECT_EQ(intermediate, expected_encoded); } EXPECT_TRUE(UrlDecode(intermediate, &output, hive_compat)); EXPECT_EQ(input, output); // Convert string to vector and try that also vector<uint8_t> input_vector; input_vector.resize(input.size()); memcpy(&input_vector[0], input.c_str(), input.size()); string intermediate2; UrlEncode(input_vector, &intermediate2, hive_compat); EXPECT_EQ(intermediate, intermediate2); } void TestBase64(const string& input, const string& expected_encoded) { string intermediate; Base64Encode(input, &intermediate); string output; if (!expected_encoded.empty()) { EXPECT_EQ(intermediate, expected_encoded); } EXPECT_TRUE(Base64Decode(intermediate, &output)); EXPECT_EQ(input, output); // Convert string to vector and try that also vector<uint8_t> input_vector; input_vector.resize(input.size()); memcpy(&input_vector[0], input.c_str(), input.size()); string intermediate2; Base64Encode(input_vector, &intermediate2); EXPECT_EQ(intermediate, intermediate2); } // Test URL encoding. Check that the values that are put in are the // same that come out. TEST(UrlCodingTest, Basic) { string input = "ABCDEFGHIJKLMNOPQRSTUWXYZ1234567890~!@#$%^&*()<>?,./:\";'{}|[]\\_+-="; TestUrl(input, "", false); TestUrl(input, "", true); } TEST(UrlCodingTest, HiveExceptions) { TestUrl(" +", " +", true); } TEST(UrlCodingTest, BlankString) { TestUrl("", "", false); TestUrl("", "", true); } TEST(UrlCodingTest, PathSeparators) { TestUrl("/home/impala/directory/", "%2Fhome%2Fimpala%2Fdirectory%2F", false); TestUrl("/home/impala/directory/", "%2Fhome%2Fimpala%2Fdirectory%2F", true); } TEST(Base64Test, Basic) { TestBase64("a", "YQ=="); TestBase64("ab", "YWI="); TestBase64("abc", "YWJj"); TestBase64("abcd", "YWJjZA=="); TestBase64("abcde", "YWJjZGU="); TestBase64("abcdef", "YWJjZGVm"); } TEST(HtmlEscapingTest, Basic) { string before = "<html><body>&amp"; stringstream after; EscapeForHtml(before, &after); EXPECT_EQ(after.str(), "&lt;html&gt;&lt;body&gt;&amp;amp"); } } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
c++
code
3,288
789
/// @ref gtx_raw_data /// @file glm/gtx/raw_data.hpp /// /// @see core (dependence) /// /// @defgroup gtx_raw_data GLM_GTX_raw_data /// @ingroup gtx /// /// Include <glm/gtx/raw_data.hpp> to use the features of this extension. /// /// Projection of a vector to other one #pragma once // external #include "../ext/scalar_uint_sized.hpp" #include "../detail/setup.hpp" #if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED) # ifndef GLM_ENABLE_EXPERIMENTAL # pragma message("GLM: GLM_GTX_raw_data is an experimental extension and may change in the future. Use #define GLM_ENABLE_EXPERIMENTAL before including it, if you really want to use it.") # else # pragma message("GLM: GLM_GTX_raw_data extension included") # endif #endif namespace glm { /// @addtogroup gtx_raw_data /// @{ //! Type for byte numbers. //! From GLM_GTX_raw_data extension. typedef detail::uint8 byte; //! Type for word numbers. //! From GLM_GTX_raw_data extension. typedef detail::uint16 word; //! Type for dword numbers. //! From GLM_GTX_raw_data extension. typedef detail::uint32 dword; //! Type for qword numbers. //! From GLM_GTX_raw_data extension. typedef detail::uint64 qword; /// @} }// namespace glm #include "raw_data.inl"
c++
code
1,238
238
#include <iostream> using namespace std; int main() { int low, high, i; bool isPrime = true; cout << "Enter two numbers (intervals): "; cin >> low >> high; cout << "\nPrime numbers between " << low << " and " << high << " are: " << endl; while (low < high) { isPrime = true; if (low == 0 || low == 1) { isPrime = false; } else { for (i = 2; i <= low / 2; ++i) { if (low % i == 0) { isPrime = false; break; } } } if (isPrime) cout << low << " "; ++low; } return 0; }
c++
code
688
168
#include "gtest/gtest.h" #include "PBMin.h" #include <vector> namespace { TEST(Constructors, constructor){ std::vector< PBConstraint > e_constraints = { PBConstraint(PBFormula({1,2},{1,2}),1), PBConstraint(PBFormula({3,4},{2,3}),1), PBConstraint(PBFormula({3,7},{1,3}),1) }; PBMin m = PBMin(e_constraints, PBFormula({3,-5},{-1,2})); std::vector< PBConstraint > constraints = m.getConstraints(); PBFormula costFunction = m.getCostFunction(); for (size_t i = 0; i < e_constraints.size(); i++) { EXPECT_EQ(constraints[i].getK(),e_constraints[i].getK()); for (size_t k = 0; k < constraints[i].getPBFormula().getWeights().size(); k++) { EXPECT_EQ(e_constraints[i].getPBFormula().getWeights()[k], constraints[i].getPBFormula().getWeights()[k]); EXPECT_EQ(e_constraints[i].getPBFormula().getLiterals()[k], constraints[i].getPBFormula().getLiterals()[k]); } } } TEST(GetFirstFreshVariable,getFirstFreshVariable){ std::vector< PBConstraint > e_constraints = { PBConstraint(PBFormula({1,2},{1,2}),1), PBConstraint(PBFormula({3,4},{2,3}),1), PBConstraint(PBFormula({3,7},{1,3}),1) }; PBMin m = PBMin(e_constraints, PBFormula({3,-5},{-1,2})); EXPECT_EQ(m.getFirstFreshVariable(), 4); } TEST(GetFirstFreshVariable,getFirstFreshVariable2){ std::vector< PBConstraint > e_constraints = { PBConstraint(PBFormula({1,2},{-1,-2}),1), PBConstraint(PBFormula({3,4},{2,-3}),1), PBConstraint(PBFormula({3,7},{1,-3}),1) }; PBMin m = PBMin(e_constraints, PBFormula({3,-5},{-1,2})); EXPECT_EQ(m.getFirstFreshVariable(), 4); } TEST(GetFirstFreshVariable,getFirstFreshVariable3){ std::vector< PBConstraint > e_constraints = { PBConstraint(PBFormula({1,2},{-1,-2}),1), PBConstraint(PBFormula({3,4},{2,-3}),1), PBConstraint(PBFormula({3,7},{1,-3}),1) }; PBMin m = PBMin(e_constraints, PBFormula({3,-5},{4,5})); EXPECT_EQ(m.getFirstFreshVariable(), 6); } TEST(GetCostFunctionMax,getCostFunctionMax){ PBMin m = PBMin({}, PBFormula({1,1},{1,2})); EXPECT_EQ(m.getCostFunctionMax(), 2); } TEST(GetCostFunctionMax,getCostFunctionMax2){ PBMin m = PBMin({}, PBFormula({1,1},{1,-1})); EXPECT_EQ(m.getCostFunctionMax(), 1); } TEST(GetCostFunctionMax,getCostFunctionMax3){ PBMin m = PBMin({}, PBFormula({1,2,3},{1,2,3})); EXPECT_EQ(m.getCostFunctionMax(), 6); } TEST(GetCostFunctionMax,getCostFunctionMax4){ PBMin m = PBMin({}, PBFormula({-1,-2,3},{1,2,3})); EXPECT_EQ(m.getCostFunctionMax(), 3); } TEST(GetCostFunctionMax,getCostFunctionMax5){ PBMin m = PBMin({}, PBFormula({-1,-3},{1,-1})); EXPECT_EQ(m.getCostFunctionMax(), -1); } TEST(GetCostFunctionMax,getCostFunctionMax6){ PBMin m = PBMin({}, PBFormula({-1,-3,7,-5},{1,-1,2,-2})); EXPECT_EQ(m.getCostFunctionMax(), 6); } TEST(GetCostFunctionMin,getCostFunctionMin){ PBMin m = PBMin({}, PBFormula({1,1},{1,2})); EXPECT_EQ(m.getCostFunctionMin(), 0); } TEST(GetCostFunctionMin,getCostFunctionMin2){ PBMin m = PBMin({}, PBFormula({1,1},{1,-1})); EXPECT_EQ(m.getCostFunctionMin(), 1); } TEST(GetCostFunctionMin,getCostFunctionMin3){ PBMin m = PBMin({}, PBFormula({-1,-2,-3},{1,2,3})); EXPECT_EQ(m.getCostFunctionMin(), -6); } TEST(GetCostFunctionMin,getCostFunctionMin4){ PBMin m = PBMin({}, PBFormula({-1,-2,3},{1,2,3})); EXPECT_EQ(m.getCostFunctionMin(), -3); } TEST(GetCostFunctionMin,getCostFunctionMin5){ PBMin m = PBMin({}, PBFormula({-1,-3},{1,-1})); EXPECT_EQ(m.getCostFunctionMin(), -3); } TEST(GetCostFunctionMin,getCostFunctionMin6){ PBMin m = PBMin({}, PBFormula({-1,-3,7,-5},{1,-1,2,-2})); EXPECT_EQ(m.getCostFunctionMin(), -8); } }
c++
code
4,164
1,175
// Copyright (c) 2012 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/renderer_host/web_input_event_aura.h" #include "content/browser/renderer_host/ui_events_helper.h" #include "ui/aura/window.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #if defined(USE_OZONE) #include "ui/events/keycodes/keyboard_code_conversion.h" #endif namespace content { #if defined(USE_X11) || defined(USE_OZONE) // From third_party/WebKit/Source/web/gtk/WebInputEventFactory.cpp: blink::WebUChar GetControlCharacter(int windows_key_code, bool shift) { if (windows_key_code >= ui::VKEY_A && windows_key_code <= ui::VKEY_Z) { // ctrl-A ~ ctrl-Z map to \x01 ~ \x1A return windows_key_code - ui::VKEY_A + 1; } if (shift) { // following graphics chars require shift key to input. switch (windows_key_code) { // ctrl-@ maps to \x00 (Null byte) case ui::VKEY_2: return 0; // ctrl-^ maps to \x1E (Record separator, Information separator two) case ui::VKEY_6: return 0x1E; // ctrl-_ maps to \x1F (Unit separator, Information separator one) case ui::VKEY_OEM_MINUS: return 0x1F; // Returns 0 for all other keys to avoid inputting unexpected chars. default: break; } } else { switch (windows_key_code) { // ctrl-[ maps to \x1B (Escape) case ui::VKEY_OEM_4: return 0x1B; // ctrl-\ maps to \x1C (File separator, Information separator four) case ui::VKEY_OEM_5: return 0x1C; // ctrl-] maps to \x1D (Group separator, Information separator three) case ui::VKEY_OEM_6: return 0x1D; // ctrl-Enter maps to \x0A (Line feed) case ui::VKEY_RETURN: return 0x0A; // Returns 0 for all other keys to avoid inputting unexpected chars. default: break; } } return 0; } #endif #if defined(OS_WIN) blink::WebMouseEvent MakeUntranslatedWebMouseEventFromNativeEvent( base::NativeEvent native_event); blink::WebMouseWheelEvent MakeUntranslatedWebMouseWheelEventFromNativeEvent( base::NativeEvent native_event); blink::WebKeyboardEvent MakeWebKeyboardEventFromNativeEvent( base::NativeEvent native_event); blink::WebGestureEvent MakeWebGestureEventFromNativeEvent( base::NativeEvent native_event); #elif defined(USE_X11) blink::WebKeyboardEvent MakeWebKeyboardEventFromAuraEvent( ui::KeyEvent* event); #elif defined(USE_OZONE) blink::WebKeyboardEvent MakeWebKeyboardEventFromAuraEvent( ui::KeyEvent* event) { const base::NativeEvent& native_event = event->native_event(); ui::EventType type = ui::EventTypeFromNative(native_event); blink::WebKeyboardEvent webkit_event; webkit_event.timeStampSeconds = event->time_stamp().InSecondsF(); webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags()); switch (type) { case ui::ET_KEY_PRESSED: webkit_event.type = event->is_char() ? blink::WebInputEvent::Char : blink::WebInputEvent::RawKeyDown; break; case ui::ET_KEY_RELEASED: webkit_event.type = blink::WebInputEvent::KeyUp; break; default: NOTREACHED(); } if (webkit_event.modifiers & blink::WebInputEvent::AltKey) webkit_event.isSystemKey = true; wchar_t character = ui::KeyboardCodeFromNative(native_event); webkit_event.windowsKeyCode = character; webkit_event.nativeKeyCode = character; if (webkit_event.windowsKeyCode == ui::VKEY_RETURN) webkit_event.unmodifiedText[0] = '\r'; else webkit_event.unmodifiedText[0] = ui::GetCharacterFromKeyCode( ui::KeyboardCodeFromNative(native_event), ui::EventFlagsFromNative(native_event)); if (webkit_event.modifiers & blink::WebInputEvent::ControlKey) { webkit_event.text[0] = GetControlCharacter( webkit_event.windowsKeyCode, webkit_event.modifiers & blink::WebInputEvent::ShiftKey); } else { webkit_event.text[0] = webkit_event.unmodifiedText[0]; } webkit_event.setKeyIdentifierFromWindowsKeyCode(); return webkit_event; } #endif #if defined(USE_X11) || defined(USE_OZONE) blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent( ui::ScrollEvent* event) { blink::WebMouseWheelEvent webkit_event; webkit_event.type = blink::WebInputEvent::MouseWheel; webkit_event.button = blink::WebMouseEvent::ButtonNone; webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags()); webkit_event.timeStampSeconds = event->time_stamp().InSecondsF(); webkit_event.hasPreciseScrollingDeltas = true; float offset_ordinal_x = 0.f; float offset_ordinal_y = 0.f; if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 && event->x_offset() == 0) { webkit_event.deltaX = event->y_offset(); webkit_event.deltaY = 0; offset_ordinal_x = event->y_offset_ordinal(); offset_ordinal_y = event->x_offset_ordinal(); } else { webkit_event.deltaX = event->x_offset(); webkit_event.deltaY = event->y_offset(); offset_ordinal_x = event->x_offset_ordinal(); offset_ordinal_y = event->y_offset_ordinal(); } if (offset_ordinal_x != 0.f && webkit_event.deltaX != 0.f) webkit_event.accelerationRatioX = offset_ordinal_x / webkit_event.deltaX; webkit_event.wheelTicksX = webkit_event.deltaX / kPixelsPerTick; webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick; if (offset_ordinal_y != 0.f && webkit_event.deltaY != 0.f) webkit_event.accelerationRatioY = offset_ordinal_y / webkit_event.deltaY; return webkit_event; } blink::WebGestureEvent MakeWebGestureEventFromAuraEvent( ui::ScrollEvent* event) { blink::WebGestureEvent webkit_event; switch (event->type()) { case ui::ET_SCROLL_FLING_START: webkit_event.type = blink::WebInputEvent::GestureFlingStart; webkit_event.data.flingStart.velocityX = event->x_offset(); webkit_event.data.flingStart.velocityY = event->y_offset(); break; case ui::ET_SCROLL_FLING_CANCEL: webkit_event.type = blink::WebInputEvent::GestureFlingCancel; break; case ui::ET_SCROLL: NOTREACHED() << "Invalid gesture type: " << event->type(); break; default: NOTREACHED() << "Unknown gesture type: " << event->type(); } webkit_event.sourceDevice = blink::WebGestureEvent::Touchpad; webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags()); webkit_event.timeStampSeconds = event->time_stamp().InSecondsF(); return webkit_event; } #endif blink::WebMouseEvent MakeWebMouseEventFromAuraEvent( ui::MouseEvent* event); blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent( ui::MouseWheelEvent* event); // General approach: // // ui::Event only carries a subset of possible event data provided to Aura by // the host platform. WebKit utilizes a larger subset of that information than // Aura itself. WebKit includes some built in cracking functionality that we // rely on to obtain this information cleanly and consistently. // // The only place where an ui::Event's data differs from what the underlying // base::NativeEvent would provide is position data, since we would like to // provide coordinates relative to the aura::Window that is hosting the // renderer, not the top level platform window. // // The approach is to fully construct a blink::WebInputEvent from the // ui::Event's base::NativeEvent, and then replace the coordinate fields with // the translated values from the ui::Event. // // The exception is mouse events on linux. The ui::MouseEvent contains enough // necessary information to construct a WebMouseEvent. So instead of extracting // the information from the XEvent, which can be tricky when supporting both // XInput2 and XInput, the WebMouseEvent is constructed from the // ui::MouseEvent. This will not be necessary once only XInput2 is supported. // blink::WebMouseEvent MakeWebMouseEvent(ui::MouseEvent* event) { // Construct an untranslated event from the platform event data. blink::WebMouseEvent webkit_event = #if defined(OS_WIN) // On Windows we have WM_ events comming from desktop and pure aura // events comming from metro mode. event->native_event().message ? MakeUntranslatedWebMouseEventFromNativeEvent(event->native_event()) : MakeWebMouseEventFromAuraEvent(event); #else MakeWebMouseEventFromAuraEvent(event); #endif // Replace the event's coordinate fields with translated position data from // |event|. webkit_event.windowX = webkit_event.x = event->x(); webkit_event.windowY = webkit_event.y = event->y(); #if defined(OS_WIN) if (event->native_event().message) return webkit_event; #endif const gfx::Point root_point = event->root_location(); webkit_event.globalX = root_point.x(); webkit_event.globalY = root_point.y(); return webkit_event; } blink::WebMouseWheelEvent MakeWebMouseWheelEvent(ui::MouseWheelEvent* event) { #if defined(OS_WIN) // Construct an untranslated event from the platform event data. blink::WebMouseWheelEvent webkit_event = event->native_event().message ? MakeUntranslatedWebMouseWheelEventFromNativeEvent(event->native_event()) : MakeWebMouseWheelEventFromAuraEvent(event); #else blink::WebMouseWheelEvent webkit_event = MakeWebMouseWheelEventFromAuraEvent(event); #endif // Replace the event's coordinate fields with translated position data from // |event|. webkit_event.windowX = webkit_event.x = event->x(); webkit_event.windowY = webkit_event.y = event->y(); const gfx::Point root_point = event->root_location(); webkit_event.globalX = root_point.x(); webkit_event.globalY = root_point.y(); return webkit_event; } blink::WebMouseWheelEvent MakeWebMouseWheelEvent(ui::ScrollEvent* event) { #if defined(OS_WIN) // Construct an untranslated event from the platform event data. blink::WebMouseWheelEvent webkit_event = MakeUntranslatedWebMouseWheelEventFromNativeEvent(event->native_event()); #else blink::WebMouseWheelEvent webkit_event = MakeWebMouseWheelEventFromAuraEvent(event); #endif // Replace the event's coordinate fields with translated position data from // |event|. webkit_event.windowX = webkit_event.x = event->x(); webkit_event.windowY = webkit_event.y = event->y(); const gfx::Point root_point = event->root_location(); webkit_event.globalX = root_point.x(); webkit_event.globalY = root_point.y(); return webkit_event; } blink::WebKeyboardEvent MakeWebKeyboardEvent(ui::KeyEvent* event) { if (!event->HasNativeEvent()) return blink::WebKeyboardEvent(); // Windows can figure out whether or not to construct a RawKeyDown or a Char // WebInputEvent based on the type of message carried in // event->native_event(). X11 is not so fortunate, there is no separate // translated event type, so DesktopHostLinux sends an extra KeyEvent with // is_char() == true. We need to pass the ui::KeyEvent to the X11 function // to detect this case so the right event type can be constructed. #if defined(OS_WIN) // Key events require no translation by the aura system. return MakeWebKeyboardEventFromNativeEvent(event->native_event()); #else return MakeWebKeyboardEventFromAuraEvent(event); #endif } blink::WebGestureEvent MakeWebGestureEvent(ui::GestureEvent* event) { blink::WebGestureEvent gesture_event; #if defined(OS_WIN) if (event->HasNativeEvent()) gesture_event = MakeWebGestureEventFromNativeEvent(event->native_event()); else gesture_event = MakeWebGestureEventFromUIEvent(*event); #else gesture_event = MakeWebGestureEventFromUIEvent(*event); #endif gesture_event.x = event->x(); gesture_event.y = event->y(); const gfx::Point root_point = event->root_location(); gesture_event.globalX = root_point.x(); gesture_event.globalY = root_point.y(); return gesture_event; } blink::WebGestureEvent MakeWebGestureEvent(ui::ScrollEvent* event) { blink::WebGestureEvent gesture_event; #if defined(OS_WIN) gesture_event = MakeWebGestureEventFromNativeEvent(event->native_event()); #else gesture_event = MakeWebGestureEventFromAuraEvent(event); #endif gesture_event.x = event->x(); gesture_event.y = event->y(); const gfx::Point root_point = event->root_location(); gesture_event.globalX = root_point.x(); gesture_event.globalY = root_point.y(); return gesture_event; } blink::WebGestureEvent MakeWebGestureEventFlingCancel() { blink::WebGestureEvent gesture_event; // All other fields are ignored on a GestureFlingCancel event. gesture_event.type = blink::WebInputEvent::GestureFlingCancel; gesture_event.sourceDevice = blink::WebGestureEvent::Touchpad; return gesture_event; } blink::WebMouseEvent MakeWebMouseEventFromAuraEvent(ui::MouseEvent* event) { blink::WebMouseEvent webkit_event; webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags()); webkit_event.timeStampSeconds = event->time_stamp().InSecondsF(); webkit_event.button = blink::WebMouseEvent::ButtonNone; if (event->flags() & ui::EF_LEFT_MOUSE_BUTTON) webkit_event.button = blink::WebMouseEvent::ButtonLeft; if (event->flags() & ui::EF_MIDDLE_MOUSE_BUTTON) webkit_event.button = blink::WebMouseEvent::ButtonMiddle; if (event->flags() & ui::EF_RIGHT_MOUSE_BUTTON) webkit_event.button = blink::WebMouseEvent::ButtonRight; switch (event->type()) { case ui::ET_MOUSE_PRESSED: webkit_event.type = blink::WebInputEvent::MouseDown; webkit_event.clickCount = event->GetClickCount(); break; case ui::ET_MOUSE_RELEASED: webkit_event.type = blink::WebInputEvent::MouseUp; webkit_event.clickCount = event->GetClickCount(); break; case ui::ET_MOUSE_ENTERED: case ui::ET_MOUSE_EXITED: case ui::ET_MOUSE_MOVED: case ui::ET_MOUSE_DRAGGED: webkit_event.type = blink::WebInputEvent::MouseMove; break; default: NOTIMPLEMENTED() << "Received unexpected event: " << event->type(); break; } return webkit_event; } blink::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent( ui::MouseWheelEvent* event) { blink::WebMouseWheelEvent webkit_event; webkit_event.type = blink::WebInputEvent::MouseWheel; webkit_event.button = blink::WebMouseEvent::ButtonNone; webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags()); webkit_event.timeStampSeconds = event->time_stamp().InSecondsF(); if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 && event->x_offset() == 0) { webkit_event.deltaX = event->y_offset(); webkit_event.deltaY = 0; } else { webkit_event.deltaX = event->x_offset(); webkit_event.deltaY = event->y_offset(); } webkit_event.wheelTicksX = webkit_event.deltaX / kPixelsPerTick; webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick; return webkit_event; } } // namespace content
c++
code
14,889
2,890
/* Copyright 2015 The TensorFlow 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. ==============================================================================*/ // See docs in ../ops/math_ops.cc. #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/sparse_tensor_dense_matmul_op.h" #include "tensorflow/core/framework/bounds_check.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/kernels/fill_functor.h" #include "tensorflow/core/platform/bfloat16.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; template <typename Device, typename T, typename Tindices> class SparseTensorDenseMatMulOp : public OpKernel { public: explicit SparseTensorDenseMatMulOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint_a", &adjoint_a_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint_b", &adjoint_b_)); } void Compute(OpKernelContext* ctx) override { const Tensor* a_indices; const Tensor* a_values; const Tensor* a_shape; const Tensor* b; OP_REQUIRES_OK(ctx, ctx->input("a_indices", &a_indices)); OP_REQUIRES_OK(ctx, ctx->input("a_values", &a_values)); OP_REQUIRES_OK(ctx, ctx->input("a_shape", &a_shape)); OP_REQUIRES_OK(ctx, ctx->input("b", &b)); // Check that the dimensions of the two matrices are valid. OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b->shape()), errors::InvalidArgument("Tensor 'b' is not a matrix")); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_shape->shape()), errors::InvalidArgument("Tensor 'a_shape' is not a vector")); OP_REQUIRES( ctx, a_shape->NumElements() == 2, errors::InvalidArgument("Tensor 'a_shape' must have 2 elements")); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(a_values->shape()), errors::InvalidArgument("Tensor 'a_values' is not a vector")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a_indices->shape()), errors::InvalidArgument("Tensor 'a_indices' is not a matrix")); const int64 nnz = a_indices->shape().dim_size(0); OP_REQUIRES(ctx, nnz == a_values->NumElements(), errors::InvalidArgument("Number of rows of a_indices does not " "match number of entries in a_values")); OP_REQUIRES( ctx, a_indices->shape().dim_size(1) == a_shape->NumElements(), errors::InvalidArgument("Number of columns of a_indices does not match " "number of entries in a_shape")); auto a_shape_t = a_shape->vec<int64>(); const int64 outer_left = (adjoint_a_) ? a_shape_t(1) : a_shape_t(0); const int64 outer_right = (adjoint_b_) ? b->shape().dim_size(0) : b->shape().dim_size(1); const int64 inner_left = (adjoint_a_) ? a_shape_t(0) : a_shape_t(1); const int64 inner_right = (adjoint_b_) ? b->shape().dim_size(1) : b->shape().dim_size(0); OP_REQUIRES( ctx, inner_right == inner_left, errors::InvalidArgument( "Cannot multiply A and B because inner dimension does not match: ", inner_left, " vs. ", inner_right, ". Did you forget a transpose? " "Dimensions of A: [", a_shape_t(0), ", ", a_shape_t(1), "). Dimensions of B: ", b->shape().DebugString())); if (std::is_same<Device, GPUDevice>::value) { // The GPU implementation is optimized to use 32 bit indexing, so // give a friendly error to the programmer early on if they // exceed. const int int32max = std::numeric_limits<int>::max(); OP_REQUIRES( ctx, (FastBoundsCheck(inner_left, int32max) && FastBoundsCheck(inner_right, int32max) && FastBoundsCheck(outer_left, int32max) && FastBoundsCheck(outer_right, int32max) && FastBoundsCheck(b->NumElements(), int32max) && FastBoundsCheck(outer_left * outer_right, int32max) && FastBoundsCheck(a_values->NumElements(), int32max)), errors::InvalidArgument("Cannot use GPU for > 2^31 entry inputs")); OP_REQUIRES(ctx, FastBoundsCheck(nnz * outer_right, int32max), errors::InvalidArgument( "Cannot use GPU when output.shape[1] * nnz(a) > 2^31")); } TensorShape out_shape({outer_left, outer_right}); Tensor* out = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out)); if (out->NumElements() == 0) { // If a has shape [0, x] or b has shape [x, 0], the output shape // is a 0-element matrix, so there is nothing to do. return; } if (a_values->NumElements() == 0 || b->NumElements() == 0) { // If a has shape [x, 0] and b has shape [0, y], the // output shape is [x, y] where x and y are non-zero, so we fill // the output with zeros. functor::SetZeroFunctor<Device, T> f; f(ctx->eigen_device<Device>(), out->flat<T>()); return; } #define MAYBE_ADJOINT(ADJ_A, ADJ_B) \ if (adjoint_a_ == ADJ_A && adjoint_b_ == ADJ_B) { \ Status functor_status = functor::SparseTensorDenseMatMulFunctor< \ Device, T, Tindices, ADJ_A, \ ADJ_B>::Compute(ctx->eigen_device<Device>(), out->matrix<T>(), \ a_indices->matrix<Tindices>(), a_values->vec<T>(), \ b->matrix<T>()); \ OP_REQUIRES_OK(ctx, functor_status); \ } MAYBE_ADJOINT(false, false); MAYBE_ADJOINT(false, true); MAYBE_ADJOINT(true, false); MAYBE_ADJOINT(true, true); #undef MAYBE_ADJOINT } private: bool adjoint_a_; bool adjoint_b_; }; #define REGISTER_CPU(TypeT, TypeIndex) \ REGISTER_KERNEL_BUILDER( \ Name("SparseTensorDenseMatMul") \ .Device(DEVICE_CPU) \ .TypeConstraint<TypeT>("T") \ .TypeConstraint<TypeIndex>("Tindices") \ .HostMemory("a_shape"), \ SparseTensorDenseMatMulOp<CPUDevice, TypeT, TypeIndex>); #define REGISTER_KERNELS_CPU(T) \ REGISTER_CPU(T, int64); \ REGISTER_CPU(T, int32) REGISTER_KERNELS_CPU(float); REGISTER_KERNELS_CPU(double); REGISTER_KERNELS_CPU(int32); REGISTER_KERNELS_CPU(complex64); REGISTER_KERNELS_CPU(complex128); REGISTER_KERNELS_CPU(bfloat16); #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM namespace functor { #define DECLARE_GPU_SPEC(T, Tindices, ADJ_A, ADJ_B) \ template <> \ Status SparseTensorDenseMatMulFunctor< \ GPUDevice, T, Tindices, ADJ_A, \ ADJ_B>::Compute(const GPUDevice& d, typename TTypes<T>::Matrix out, \ TTypes<Tindices>::ConstMatrix a_indices, \ typename TTypes<T>::ConstVec a_values, \ typename TTypes<T>::ConstMatrix b); \ extern template struct SparseTensorDenseMatMulFunctor< \ GPUDevice, T, Tindices, ADJ_A, ADJ_B>; #define REGISTER_GPU_SPEC(T, ADJ_A, ADJ_B) \ DECLARE_GPU_SPEC(T, int32, ADJ_A, ADJ_B); \ DECLARE_GPU_SPEC(T, int64, ADJ_A, ADJ_B) #define DECLARE_ADJOINT_GPU_SPEC(T) \ REGISTER_GPU_SPEC(T, false, false) \ REGISTER_GPU_SPEC(T, false, true) \ REGISTER_GPU_SPEC(T, true, false) \ REGISTER_GPU_SPEC(T, true, true) DECLARE_ADJOINT_GPU_SPEC(float); #undef DECLARE_ADJOINT_GPU_SPEC #undef DECLARE_GPU_SPEC #undef REGISTER_GPU_SPEC } // namespace functor #define REGISTER_GPU(TypeT, TypeIndex) \ REGISTER_KERNEL_BUILDER( \ Name("SparseTensorDenseMatMul") \ .Device(DEVICE_GPU) \ .TypeConstraint<TypeT>("T") \ .TypeConstraint<TypeIndex>("Tindices") \ .HostMemory("a_shape"), \ SparseTensorDenseMatMulOp<GPUDevice, TypeT, TypeIndex>); #define REGISTER_KERNELS_GPU(T) \ REGISTER_GPU(T, int64); \ REGISTER_GPU(T, int32) REGISTER_KERNELS_GPU(float); #undef REGISTER_GPU #undef REGISTER_KERNELS_GPU #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM namespace functor { namespace { Status KOutOfBoundsError(int64 k, std::size_t i, int rhs_index_a, std::size_t lhs_right) { return errors::InvalidArgument("k (", k, ") from index[", i, ",", rhs_index_a, "] out of bounds (>=", lhs_right, ")"); } Status MOutOfBoundsError(int64 m, std::size_t i, int lhs_index_a, int64 out_dim0) { return errors::InvalidArgument("m (", m, ") from index[", i, ",", lhs_index_a, "] out of bounds (>=", out_dim0, ")"); } } // namespace template <typename T, typename Tindices, bool ADJ_A, bool ADJ_B> struct SparseTensorDenseMatMulFunctor<CPUDevice, T, Tindices, ADJ_A, ADJ_B> { // Vectorize certain operations above this size. static constexpr std::size_t kNumVectorize = 32; static Status Compute(const CPUDevice& d, typename TTypes<T>::Matrix out, typename TTypes<Tindices>::ConstMatrix a_indices, typename TTypes<T>::ConstVec a_values, typename TTypes<T>::ConstMatrix b) { const std::size_t nnz = a_values.size(); const std::size_t rhs_right = (ADJ_B ? b.dimension(0) : b.dimension(1)); const std::size_t lhs_right = (ADJ_B ? b.dimension(1) : b.dimension(0)); const int lhs_index_a = ADJ_A ? 1 : 0; const int rhs_index_a = ADJ_A ? 0 : 1; out.setZero(); // TODO(ebrevdo): After many failed experiments, can't find a multi-threaded // approach that achieves the performance of the single threaded // one. Perhaps Eigen threadpool implementation is just too slow? if (rhs_right < kNumVectorize) { // Disable vectorization if the RHS of output is too small auto maybe_adjoint_b = MaybeAdjoint<decltype(b), ADJ_B>(b); for (std::size_t i = 0; i < nnz; ++i) { const Tindices m = internal::SubtleMustCopy(a_indices(i, lhs_index_a)); const Tindices k = internal::SubtleMustCopy(a_indices(i, rhs_index_a)); if (!FastBoundsCheck(k, lhs_right)) { return KOutOfBoundsError(k, i, rhs_index_a, lhs_right); } if (!FastBoundsCheck(m, out.dimension(0))) { return MOutOfBoundsError(m, i, lhs_index_a, out.dimension(0)); } const T a_value = ADJ_A ? MaybeConj(a_values(i)) : a_values(i); for (std::size_t n = 0; n < rhs_right; ++n) { const T b_value = maybe_adjoint_b(k, n); out(m, n) += a_value * b_value; } } } else { // Vectorization via Eigen. const int b_chip_index = ADJ_B ? 1 : 0; #define LOOP_NNZ(b_passed) \ for (std::size_t i = 0; i < nnz; ++i) { \ const Tindices m = internal::SubtleMustCopy(a_indices(i, lhs_index_a)); \ const Tindices k = internal::SubtleMustCopy(a_indices(i, rhs_index_a)); \ const T a_value = (ADJ_A) ? MaybeConj(a_values(i)) : a_values(i); \ if (!FastBoundsCheck(k, lhs_right)) { \ return KOutOfBoundsError(k, i, rhs_index_a, lhs_right); \ } \ if (!FastBoundsCheck(m, out.dimension(0))) { \ return MOutOfBoundsError(m, i, lhs_index_a, out.dimension(0)); \ } \ out.template chip<0>(m) += \ b_passed.template chip<b_chip_index>(k) * a_value; \ } if (ADJ_B) { // Perform transpose and conjugation on B once, since we chip out B's // columns in the nnz loop. Eigen::array<int, 2> shuffle(1, 0); // preserve dimension order Eigen::Tensor<T, 2, Eigen::ColMajor> col_major_conj_b = b.swap_layout().shuffle(shuffle).conjugate(); LOOP_NNZ(col_major_conj_b); } else { LOOP_NNZ(b); } #undef LOOP_NNZ } return Status::OK(); } }; } // namespace functor } // namespace tensorflow
c++
code
13,168
2,634
#include "software/ai/passing/pass.h" Pass::Pass(Point passer_point, Point receiver_point, double pass_speed_m_per_s) : passer_point(passer_point), receiver_point(receiver_point), pass_speed_m_per_s(pass_speed_m_per_s) { if (pass_speed_m_per_s < 0.0) { throw std::invalid_argument("Passes cannot have a negative pass speed"); } } Point Pass::receiverPoint() const { return receiver_point; } Angle Pass::receiverOrientation() const { return (passerPoint() - receiverPoint()).orientation(); } Angle Pass::passerOrientation() const { return (receiverPoint() - passerPoint()).orientation(); } Point Pass::passerPoint() const { return passer_point; } double Pass::speed() const { return pass_speed_m_per_s; } Pass Pass::fromPassArray(Point passer_point, const std::array<double, NUM_PARAMS_TO_OPTIMIZE>& array) { return Pass(passer_point, Point(array.at(0), array.at(1)), array.at(2)); } std::array<double, NUM_PARAMS_TO_OPTIMIZE> Pass::toPassArray() const { return {receiver_point.x(), receiver_point.y(), pass_speed_m_per_s}; } Duration Pass::estimatePassDuration() const { return Duration::fromSeconds((receiver_point - passer_point).length() / pass_speed_m_per_s); } std::ostream& operator<<(std::ostream& output_stream, const Pass& pass) { output_stream << "Receiver Point: " << pass.receiver_point << " w/ Speed (m/s): " << pass.pass_speed_m_per_s; return output_stream; }
c++
code
1,538
324
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-83_bad.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Use a fixed file name * Sinks: ifstream * BadSink : Open the file named in data using ifstream::open() * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #include <fstream> using namespace std; namespace CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83 { CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad::CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad(char * dataCopy) { data = dataCopy; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; char *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = strlen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (FILENAME_MAX - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(char)] = '\0'; /* Eliminate CRLF */ replace = strchr(data, '\r'); if (replace) { *replace = '\0'; } replace = strchr(data, '\n'); if (replace) { *replace = '\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } } CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad::~CWE23_Relative_Path_Traversal__char_connect_socket_ifstream_83_bad() { { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } } } #endif /* OMITBAD */
c++
code
4,107
676
// // $Id$ // // // Original author: Darren Kessner <[email protected]> // // Copyright 2008 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // 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 "RAMPAdapter.hpp" #include "MSDataFile.hpp" #include "examples.hpp" #include "pwiz/utility/misc/unit.hpp" #include "pwiz/utility/misc/Filesystem.hpp" #include "pwiz/utility/misc/Std.hpp" #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/copy.hpp> using namespace pwiz::cv; using namespace pwiz::msdata; using namespace pwiz::util; ostream* os_ = 0; /* RAMP will need to instantiate an msdata::RAMPAdapter object, and call it to fill in the appropriate RAMP structures: using namespace pwiz; using namespace pwiz::msdata; RAMPAdapter adapter("something.mzML"); unsigned int scanIndex = rampAdapter.index(19); // get index for scan 19 ScanHeaderStruct temp; adapter.getScanHeader(scanIndex, temp); vector<double> buffer; adapter.getScanPeaks(scanIndex, buffer); RunHeaderStruct temp2; adapter.getRunHeader(temp2); InstrumentHeaderStruct temp3; adapter.getInstrumentHeader(temp3); Note that the MSData library can throw exceptions, so the RAMP code will have to be able to handle these gracefully. Another option is to have these RAMPAdapter functions catch any exceptions and return an error code if something goes wrong. */ string writeTempFile() { const string& filename = "temp.RAMPAdapterTest.tiny.mzML"; MSData tiny; examples::initializeTiny(tiny); MSDataFile::write(tiny, filename); return filename; } ostream& operator<<(ostream& os, const ScanHeaderStruct& header) { os << "seqNum: " << header.seqNum << endl; os << "acquisitionNum: " << header.acquisitionNum << endl; os << "msLevel: " << header.msLevel << endl; os << "activationMethod: " << header.activationMethod << endl; os << "peaksCount: " << header.peaksCount << endl; os << "totIonCurrent: " << header.totIonCurrent << endl; os << "retentionTime: " << header.retentionTime << endl; os << "basePeakMZ: " << header.basePeakMZ << endl; os << "basePeakIntensity: " << header.basePeakIntensity << endl; os << "collisionEnergy: " << header.collisionEnergy << endl; os << "ionisationEnergy: " << header.ionisationEnergy << endl; os << "lowMZ: " << header.lowMZ << endl; os << "highMZ: " << header.highMZ << endl; os << "precursorScanNum: " << header.precursorScanNum << endl; os << "precursorMZ: " << header.precursorMZ << endl; os << "precursorCharge: " << header.precursorCharge << endl; os << "precursorIntensity: " << header.precursorIntensity << endl; os << "scanType: " << header.scanType << endl; os << "mergedScan: " << header.mergedScan << endl; os << "mergedResultScanNum: " << header.mergedResultScanNum << endl; os << "mergedResultStartScanNum: " << header.mergedResultStartScanNum << endl; os << "mergedResultEndScanNum: " << header.mergedResultEndScanNum << endl; os << "filePosition: " << header.filePosition << endl; return os; } ostream& operator<<(ostream& os, const RunHeaderStruct& header) { os << "scanCount: " << header.scanCount << endl; os << "lowMZ: " << header.lowMZ << endl; os << "highMZ: " << header.highMZ << endl; os << "startMZ: " << header.startMZ << endl; os << "endMZ: " << header.endMZ << endl; os << "dStartTime: " << header.dStartTime << endl; os << "dEndTime: " << header.dEndTime << endl; return os; } ostream& operator<<(ostream& os, const InstrumentStruct& instrument) { os << "manufacturer: " << instrument.manufacturer << endl; os << "model: " << instrument.model << endl; os << "ionisation: " << instrument.ionisation << endl; os << "analyzer: " << instrument.analyzer << endl; os << "detector: " << instrument.detector << endl; return os; } void test(const string& filename) { RAMPAdapter adapter(filename); size_t scanCount = adapter.scanCount(); if (os_) *os_ << "scanCount: " << scanCount << "\n\n"; unit_assert(scanCount == 5); unit_assert(adapter.index(19) == 0); unit_assert(adapter.index(20) == 1); unit_assert(adapter.index(21) == 2); // first scan (scan number == 19) ScanHeaderStruct header1; adapter.getScanHeader(0, header1); if (os_) *os_ << header1; unit_assert(header1.seqNum == 1); unit_assert(header1.acquisitionNum == 19); unit_assert(header1.msLevel == 1); unit_assert(header1.peaksCount == 15); const double epsilon = 1e-8; unit_assert_equal(header1.totIonCurrent, 1.66755e7, epsilon); unit_assert_equal(header1.retentionTime, 353.43, epsilon); unit_assert_equal(header1.basePeakMZ, 445.347, epsilon); unit_assert_equal(header1.basePeakIntensity, 120053, epsilon); unit_assert_equal(header1.collisionEnergy, 0., epsilon); unit_assert_equal(header1.lowMZ, 400.39, epsilon); unit_assert_equal(header1.highMZ, 1795.56, epsilon); unit_assert(header1.precursorScanNum == 0); unit_assert(header1.scanType == string("Full")); unit_assert(header1.activationMethod == string("")); vector<double> peaks; adapter.getScanPeaks(0, peaks); unit_assert(peaks.size() == 30); if (os_) { const MZIntensityPair* begin = reinterpret_cast<const MZIntensityPair*>(&peaks[0]); copy(begin, begin+15, ostream_iterator<MZIntensityPair>(*os_, "\n")); *os_ << endl; } // second scan (scan number == 20) ScanHeaderStruct header2; adapter.getScanHeader(1, header2); if (os_) *os_ << header2; unit_assert(header2.seqNum == 2); unit_assert(header2.acquisitionNum == 20); unit_assert(header2.msLevel == 2); unit_assert(header2.activationMethod == string("collision-induced dissociation")); unit_assert(header2.peaksCount == 10); unit_assert_equal(header2.totIonCurrent, 1.66755e7, epsilon); unit_assert_equal(header2.retentionTime, 359.43, epsilon); unit_assert_equal(header2.basePeakMZ, 456.347, epsilon); unit_assert_equal(header2.basePeakIntensity, 23433, epsilon); unit_assert_equal(header2.collisionEnergy, 35, epsilon); unit_assert_equal(header2.lowMZ, 320.39, epsilon); unit_assert_equal(header2.highMZ, 1003.56, epsilon); unit_assert(header2.precursorScanNum == 19); unit_assert_equal(header2.precursorMZ, 445.34, epsilon); unit_assert(header2.precursorCharge == 2); unit_assert_equal(header2.precursorIntensity, 120053, epsilon); unit_assert(header2.scanType == string("Full")); adapter.getScanPeaks(1, peaks); unit_assert(peaks.size() == 20); if (os_) { const MZIntensityPair* begin = reinterpret_cast<const MZIntensityPair*>(&peaks[0]); copy(begin, begin+10, ostream_iterator<MZIntensityPair>(*os_, "\n")); *os_ << endl; } // last scan ScanHeaderStruct header5; adapter.getScanHeader(4, header5); if (os_) *os_ << header5; // RunHeader RunHeaderStruct runHeader; adapter.getRunHeader(runHeader); unit_assert(runHeader.scanCount == 5); unit_assert(runHeader.lowMZ == 0); unit_assert(runHeader.highMZ == 0); unit_assert(runHeader.startMZ == 0); unit_assert(runHeader.endMZ == 0); unit_assert_equal(runHeader.dStartTime, header1.retentionTime, 1e-6); unit_assert_equal(runHeader.dEndTime, header5.retentionTime, 1e-6); if (os_) *os_ << "RunHeader:\n" << runHeader << endl; // Instrument InstrumentStruct instrument; adapter.getInstrument(instrument); if (os_) *os_ << "Instrument:\n" << instrument << endl; unit_assert(!strcmp(instrument.manufacturer, "Thermo Finnigan")); unit_assert(!strcmp(instrument.model, "LCQ Deca")); unit_assert(!strcmp(instrument.ionisation, "nanoelectrospray")); unit_assert(!strcmp(instrument.analyzer, "quadrupole ion trap")); unit_assert(!strcmp(instrument.detector, "electron multiplier")); } static void test_mzML_1_0() { std::string srcparent(__FILE__); size_t pos = srcparent.find((bfs::path("pwiz") / "data").string()); srcparent.resize(pos); std::string example_data_dir = srcparent + "example_data/"; RAMPAdapter adapter_1_0(example_data_dir + "tiny.pwiz.1.0.mzML"); const char *testfiles[2] = {"tiny.pwiz.1.1.mzML","tiny.pwiz.mzXML"}; for (int tf=2;tf--;) { // test mzML 1.0 vs mzML 1.1 and mzXML RAMPAdapter adapter_1_1(example_data_dir + testfiles[tf]); // tiny example has 4 spectra, the last of which is non-default source -- test scans 1,2,3 only unit_assert(adapter_1_0.scanCount() == adapter_1_1.scanCount()); for (int scan=4;scan--;) { ScanHeaderStruct header1_0, header1_1; adapter_1_0.getScanHeader(scan, header1_0); adapter_1_1.getScanHeader(scan, header1_1); unit_assert(header1_0.seqNum == header1_1.seqNum ); if (scan < 3) { unit_assert(header1_0.acquisitionNum == header1_1.acquisitionNum ); } unit_assert(header1_0.msLevel == header1_1.msLevel ); unit_assert(header1_0.peaksCount == header1_1.peaksCount ); const double epsilon = 1e-6; unit_assert_equal(header1_0.totIonCurrent, header1_1.totIonCurrent, epsilon); unit_assert_equal(header1_0.retentionTime, header1_1.retentionTime, epsilon); unit_assert_equal(header1_0.basePeakMZ, header1_1.basePeakMZ, epsilon); unit_assert_equal(header1_0.basePeakIntensity, header1_1.basePeakIntensity, epsilon); unit_assert_equal(header1_0.collisionEnergy, header1_1.collisionEnergy, epsilon); unit_assert_equal(header1_0.lowMZ, header1_1.lowMZ, epsilon); unit_assert_equal(header1_0.highMZ, header1_1.highMZ, epsilon); unit_assert(header1_0.precursorScanNum == header1_1.precursorScanNum ); } } } int main(int argc, char* argv[]) { TEST_PROLOG(argc, argv) try { if (argc>1 && !strcmp(argv[1],"-v")) os_ = &cout; string filename = writeTempFile(); test(filename); // now try it with a gzipped file string gzfilename = filename + ".gz"; bio::filtering_istream tinyGZ(bio::gzip_compressor() | bio::file_descriptor_source(filename)); bio::copy(tinyGZ, bio::file_descriptor_sink(gzfilename, ios::out|ios::binary)); test(gzfilename); boost::filesystem::remove(filename); boost::filesystem::remove(gzfilename); // and make sure we're still good with older files test_mzML_1_0(); } catch (exception& e) { TEST_FAILED(e.what()) } catch (...) { TEST_FAILED("Caught unknown exception.") } TEST_EPILOG }
c++
code
11,355
2,493
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <asmjit/asmjit.h> #include <cpuinfo.h> #include <immintrin.h> #include <array> #include <iostream> #include <map> #include <stdexcept> #include <tuple> #include "GroupwiseConv.h" #include "RefImplementations.h" #include "TransposeUtils.h" #include "fbgemm/Fbgemm.h" namespace fbgemm { using namespace std; template <typename accT> thread_local asmjit::JitRuntime GenConvKernel<accT>::rt_; template <typename accT> thread_local asmjit::CodeHolder GenConvKernel<accT>::code_; template <typename accT> thread_local std::map<std::tuple<bool, int, int, int>, jit_conv_kernel_fp> GenConvKernel<accT>::codeCache_; template <typename accT> thread_local std::map<std::tuple<bool, int, int, int>, jit_rowoffset_kernel_fp> GenConvKernel<accT>::codeCacheRowOffset_; namespace x86 = asmjit::x86; void calculateRowOffsets( const conv_param_t<>& conv_param, const uint8_t* activations, int32_t* rowOffsetBuf, int32_t a_zero_point, int groupNum) { int H = conv_param.OUT_DIM[0]; int W = conv_param.OUT_DIM[1]; int G = conv_param.G; int C_per_G = conv_param.IC / conv_param.G; int H_PAD = conv_param.pad[0]; int W_PAD = conv_param.pad[1]; // calculate row offset for (int h = 0; h < H; ++h) { for (int w = 0; w < W; ++w) { int32_t sum = 0; for (int r = 0; r < conv_param.K[0]; ++r) { int h_in = -H_PAD + h + r; for (int s = 0; s < conv_param.K[1]; ++s) { int w_in = -W_PAD + w + s; for (int c = 0; c < C_per_G; ++c) { if (h_in < 0 || h_in >= H || w_in < 0 || w_in >= W) { sum += a_zero_point; } else { sum += activations[((h_in * W + w_in) * G + groupNum) * C_per_G + c]; } } } } rowOffsetBuf[h * W + w] = sum; } } } tuple<bool, int, int, int> getKernelSig( const conv_param_t<>& conv_param, bool isZeroPointZero) { int C_per_G = conv_param.IC / conv_param.G; int K_per_G = conv_param.OC / conv_param.G; auto kernelSig = std::make_tuple(isZeroPointZero, conv_param.G, C_per_G, K_per_G); return kernelSig; } template <typename accT = int32_t> jit_conv_kernel_fp getOrCreateConvKernel( const conv_param_t<>& conv_param, int a_zero_point) { // Note: Wrong code is generated if it's not one of the supported convolution assert(fbgemmOptimizedGConv<2>(conv_param)); auto kernelSig = getKernelSig(conv_param, a_zero_point == 0); if (GenConvKernel<accT>::codeCache_.find(kernelSig) != GenConvKernel<accT>::codeCache_.end()) { return GenConvKernel<accT>::codeCache_[kernelSig]; } else { auto genObj = GenConvKernel<accT>(conv_param, a_zero_point); // TODO: Instruction set based dispatch return genObj.template getOrCreate<inst_set_t::avx2>(conv_param); } } template <> template <> void GenConvKernel<int32_t>::createVector8BitOne<inst_set_t::avx2>( asmjit::X86Emitter* a) { // create 8-bit 1s // i.e., oneReg16BitAvx2_[0:7] contains 0x01, oneReg8BitAvx2_[8:15] contains // 0x01 and so on a->vpcmpeqw(oneReg8BitAvx2_, oneReg8BitAvx2_, oneReg8BitAvx2_); a->vpabsb(oneReg8BitAvx2_, oneReg8BitAvx2_); } template <> template <> void GenConvKernel<int32_t>::createVector16BitOne<inst_set_t::avx2>( asmjit::X86Emitter* a) { // create 16-bit 1s // i.e., oneReg16BitAvx2_[0:15] contains 0x0001, oneReg16BitAvx2_[16:31] // contains 0x0001 and so on a->vpcmpeqw(oneReg16BitAvx2_, oneReg16BitAvx2_, oneReg16BitAvx2_); a->vpsrlw(oneReg16BitAvx2_, oneReg16BitAvx2_, 15); } template <> template <> void GenConvKernel<int32_t>::setToZeroPt<inst_set_t::avx2>( asmjit::X86Emitter* a, asmjit::X86Ymm destReg) { // make destReg all zeros a->vxorps(destReg, destReg, destReg); asmjit::X86Xmm const_reg_xmm = x86::xmm10; // move zero point to xmm10 a->movq(const_reg_xmm, a_zero_pt_R_); // make copies of zero point a->vbroadcastsd(x86::ymm10, const_reg_xmm); // shuffle // overall impact is that destReg contains 32 8-bit values equal to the lower // 8-bits of a_zero_pt_R_ a->vpshufb(destReg, x86::ymm10, destReg); } template <> template <> void GenConvKernel<int32_t>::genConstForPermutations<inst_set_t::avx2>( asmjit::X86Emitter* a) { asmjit::X86Gp permute_const_reg = a->gpzRef(12); asmjit::X86Xmm const_reg_xmm = x86::xmm10; // We have 1st group in even lanes and 2nd group in odd lanes. // Permute to put 1st group to lower 128-bit and 2nd group in upper // 128-bit. // load 7, 5, 3, 1, 6, 4, 2, 0 in a 64-bit reg a->mov(permute_const_reg, static_cast<asmjit::Imm>(0x0705030106040200)); a->movq(const_reg_xmm, permute_const_reg); // Zero extend 8 packed 8-bit integers in the low 8 bytes of const_reg_xmm to // 8 packed 32-bit integers in stPermRegAvx2_ a->vpmovzxbd(stPermRegAvx2_, const_reg_xmm); } template <> template <> void GenConvKernel<int32_t>::storeResult<inst_set_t::avx2>( asmjit::X86Emitter* a, int offset) { // store with permutation a->vpermd(resultRegAvx2_, stPermRegAvx2_, resultRegAvx2_); a->vmovups(x86::dword_ptr(out_acts_R_, offset), resultRegAvx2_); } template <> template <> void GenConvKernel<int32_t>::storeResultRowoffset<inst_set_t::avx2>( asmjit::X86Emitter* a, int offset) { // store a->vmovups(x86::dword_ptr(row_offset_R_, offset), resultRegAvx2_); } template <> template <> void GenConvKernel<int32_t>::genForLoadingWeights<inst_set_t::avx2>( asmjit::X86Emitter* a) { // load weights for (int r = 0; r < R_; ++r) { for (int s = 0; s < S_; ++s) { a->vmovaps( WRegs_avx2_[r * S_ + s], x86::dword_ptr( wghts_R_, (r * S_ + s) * 2 * K_per_G_ * C_per_G_ * sizeof(int8_t))); } } } template <> template <> void GenConvKernel<int32_t>::gen8bitFMA<inst_set_t::avx2>( asmjit::X86Emitter* a, asmjit::X86Ymm aReg, asmjit::X86Ymm wReg) { a->vpmaddubsw(tmpReg1Avx2_, aReg, wReg); a->vpmaddwd(tmpReg1Avx2_, oneReg16BitAvx2_, tmpReg1Avx2_); a->vpaddd(resultRegAvx2_, tmpReg1Avx2_, resultRegAvx2_); } template <> template <> void GenConvKernel<int32_t>::gen8BitSum<inst_set_t::avx2>( asmjit::X86Emitter* a, asmjit::X86Ymm aReg) { a->vpmaddubsw(tmpReg1Avx2_, aReg, oneReg8BitAvx2_); a->vpmaddwd(tmpReg1Avx2_, tmpReg1Avx2_, oneReg16BitAvx2_); a->vpaddd(resultRegAvx2_, tmpReg1Avx2_, resultRegAvx2_); } template <> template <> void GenConvKernel<int32_t>::genForTopEdge<inst_set_t::avx2>( asmjit::X86Emitter* a) { // top-left corner code // zero out the results register a->vxorps(resultRegAvx2_, resultRegAvx2_, resultRegAvx2_); for (int r = 0; r < R_; ++r) { int h_in = -H_PAD_ + r; if (h_in >= 0) { a->imul( scratchReg1_, W_R_, static_cast<asmjit::Imm>(h_in * C_ * sizeof(uint8_t))); } for (int s = 0; s < S_; ++s) { int w_in = -W_PAD_ + s; if (h_in >= 0 && w_in >= 0) { a->vbroadcastsd( actRegAvx2_, x86::dword_ptr( in_acts_R_, scratchReg1_, 0, w_in * C_ * sizeof(uint8_t))); gen8bitFMA<inst_set_t::avx2>(a, actRegAvx2_, WRegs_avx2_[r * S_ + s]); } else { if (!isZeroPointZero_) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } } } storeResult<inst_set_t::avx2>(a); a->add(out_acts_R_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); // top edge excluding corners asmjit::Label LoopTopEdge = a->newLabel(); a->mov(loopR2_, static_cast<asmjit::Imm>(W_PAD_)); a->bind(LoopTopEdge); // zero out a->vxorps(resultRegAvx2_, resultRegAvx2_, resultRegAvx2_); if (!isZeroPointZero_) { for (int r = 0; r < H_PAD_; ++r) { for (int s = 0; s < S_; ++s) { gen8bitFMA<inst_set_t::avx2>(a, zeroPTRegAvx2_, WRegs_avx2_[s]); } } } for (int r = H_PAD_; r < R_; ++r) { int h_in = -H_PAD_ + r; a->imul( scratchReg1_, W_R_, static_cast<asmjit::Imm>(h_in * C_ * sizeof(uint8_t))); for (int s = 0; s < S_; ++s) { a->vbroadcastsd( actRegAvx2_, x86::dword_ptr( in_acts_R_, scratchReg1_, 0, s * C_ * sizeof(uint8_t))); gen8bitFMA<inst_set_t::avx2>(a, actRegAvx2_, WRegs_avx2_[r * S_ + s]); } } a->add(in_acts_R_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); storeResult<inst_set_t::avx2>(a); a->add(out_acts_R_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->mov(loopR1_, W_R_); a->sub(loopR1_, static_cast<asmjit::Imm>(W_PAD_)); a->inc(loopR2_); a->cmp(loopR2_, loopR1_); a->jl(LoopTopEdge); a->mov(scratchReg2_, W_R_); a->imul(scratchReg2_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->sub( scratchReg2_, static_cast<asmjit::Imm>(2 * W_PAD_ * C_ * sizeof(uint8_t))); a->sub(in_acts_R_, scratchReg2_); // top-right corner code // zero out a->vxorps(resultRegAvx2_, resultRegAvx2_, resultRegAvx2_); if (!isZeroPointZero_) { for (int r = 0; r < H_PAD_; ++r) { for (int s = 0; s < S_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } } for (int r = H_PAD_; r < R_; ++r) { int h_in = -H_PAD_ + r; for (int s = 0; s < S_ - W_PAD_; ++s) { a->imul( scratchReg1_, W_R_, static_cast<asmjit::Imm>(h_in * C_ * sizeof(uint8_t))); a->mov(scratchReg2_, W_R_); a->sub(scratchReg2_, static_cast<asmjit::Imm>(R_ - W_PAD_ - s)); a->imul(scratchReg2_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->add(scratchReg1_, scratchReg2_); a->vbroadcastsd(actRegAvx2_, x86::dword_ptr(in_acts_R_, scratchReg1_)); gen8bitFMA<inst_set_t::avx2>(a, actRegAvx2_, WRegs_avx2_[r * S_ + s]); } if (!isZeroPointZero_) { for (int s = S_ - W_PAD_; s < S_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } } storeResult<inst_set_t::avx2>(a); a->add(out_acts_R_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); // reset output activation pointer a->imul(scratchReg1_, W_R_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->sub(out_acts_R_, scratchReg1_); } template <> template <> void GenConvKernel<int32_t>::genForLeftEdge<inst_set_t::avx2>( asmjit::X86Emitter* a) { // left edge excluding corners asmjit::Label LoopLeftEdge = a->newLabel(); a->mov(loopR1_, static_cast<asmjit::Imm>(H_PAD_)); a->bind(LoopLeftEdge); // zero out a->vxorps(resultRegAvx2_, resultRegAvx2_, resultRegAvx2_); a->mov(scratchReg1_, loopR1_); a->sub(scratchReg1_, static_cast<asmjit::Imm>(H_PAD_)); a->imul(scratchReg1_, W_R_); a->imul(scratchReg1_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); for (int r = 0; r < R_; ++r) { if (!isZeroPointZero_) { for (int s = 0; s < W_PAD_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } for (int s = W_PAD_; s < S_; ++s) { a->vbroadcastsd( actRegAvx2_, x86::dword_ptr( in_acts_R_, scratchReg1_, 0, (s - W_PAD_) * C_ * sizeof(uint8_t))); gen8bitFMA<inst_set_t::avx2>(a, actRegAvx2_, WRegs_avx2_[r * S_ + s]); } a->imul(scratchReg2_, W_R_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->add(scratchReg1_, scratchReg2_); } a->imul(scratchReg2_, W_R_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->add(out_acts_R_, scratchReg2_); storeResult<inst_set_t::avx2>(a); a->inc(loopR1_); a->mov(loopR2_, H_R_); a->sub(loopR2_, static_cast<asmjit::Imm>(H_PAD_)); a->cmp(loopR1_, loopR2_); a->jl(LoopLeftEdge); // reset output activation pointer a->mov(scratchReg2_, H_R_); a->sub(scratchReg2_, static_cast<asmjit::Imm>(2 * H_PAD_)); a->imul(scratchReg2_, W_R_); a->imul(scratchReg2_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->sub(out_acts_R_, scratchReg2_); } template <> template <> void GenConvKernel<int32_t>::genForRightEdge<inst_set_t::avx2>( asmjit::X86Emitter* a) { // right edge excluding corners asmjit::Label LoopRightEdge = a->newLabel(); // output pointer to the right edge // (W_ + W_ - 1)*K_*sizeof(int32_t) a->mov(scratchReg2_, W_R_); a->imul(scratchReg2_, 2); a->sub(scratchReg2_, 1); a->imul(scratchReg2_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->add(out_acts_R_, scratchReg2_); a->mov(loopR1_, static_cast<asmjit::Imm>(H_PAD_)); a->bind(LoopRightEdge); // zero out a->vxorps(resultRegAvx2_, resultRegAvx2_, resultRegAvx2_); a->mov(scratchReg1_, loopR1_); a->sub(scratchReg1_, static_cast<asmjit::Imm>(H_PAD_)); a->imul(scratchReg1_, W_R_); a->imul(scratchReg1_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->mov(scratchReg2_, W_R_); a->sub(scratchReg2_, static_cast<asmjit::Imm>(2 * W_PAD_)); a->imul(scratchReg2_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->add(scratchReg1_, scratchReg2_); for (int r = 0; r < R_; ++r) { for (int s = 0; s < S_ - W_PAD_; ++s) { a->vbroadcastsd(actRegAvx2_, x86::dword_ptr(in_acts_R_, scratchReg1_)); gen8bitFMA<inst_set_t::avx2>(a, actRegAvx2_, WRegs_avx2_[r * S_ + s]); a->add(scratchReg1_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); } if (!isZeroPointZero_) { for (int s = S_ - W_PAD_; s < S_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } a->sub( scratchReg1_, static_cast<asmjit::Imm>((S_ - W_PAD_) * C_ * sizeof(uint8_t))); a->imul(scratchReg2_, W_R_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->add(scratchReg1_, scratchReg2_); } // storeResult<inst_set_t::avx2>(a, (W_+W_-1)*K_*sizeof(int32_t)); storeResult<inst_set_t::avx2>(a); a->imul(scratchReg2_, W_R_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->add(out_acts_R_, scratchReg2_); a->mov(loopR2_, H_R_); a->sub(loopR2_, static_cast<asmjit::Imm>(H_PAD_)); a->inc(loopR1_); a->cmp(loopR1_, loopR2_); a->jl(LoopRightEdge); // reset base a->mov(scratchReg2_, W_R_); a->imul(scratchReg2_, 2); a->sub(scratchReg2_, 1); a->imul(scratchReg2_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->sub(out_acts_R_, scratchReg2_); // reset loop increments //(H_ - 2*H_PAD_)*W_*K_*sizeof(int32_t) a->mov(scratchReg2_, H_R_); a->sub(scratchReg2_, static_cast<asmjit::Imm>(2 * H_PAD_)); a->imul(scratchReg2_, W_R_); a->imul(scratchReg2_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->sub(out_acts_R_, scratchReg2_); // a->sub(out_acts_R_, (H_ - 2*H_PAD_)*W_*K_*sizeof(int32_t)); } template <> template <> void GenConvKernel<int32_t>::genForBottomEdge<inst_set_t::avx2>( asmjit::X86Emitter* a) { // bottom-left corner // zero out a->vxorps(resultRegAvx2_, resultRegAvx2_, resultRegAvx2_); a->mov(scratchReg1_, H_R_); a->sub(scratchReg1_, static_cast<asmjit::Imm>(2 * H_PAD_)); a->imul(scratchReg1_, W_R_); a->imul(scratchReg1_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); for (int r = 0; r < R_ - H_PAD_; ++r) { if (!isZeroPointZero_) { for (int s = 0; s < W_PAD_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } for (int s = W_PAD_; s < S_; ++s) { a->vbroadcastsd( actRegAvx2_, x86::dword_ptr( in_acts_R_, scratchReg1_, 0, (s - W_PAD_) * C_ * sizeof(uint8_t))); gen8bitFMA<inst_set_t::avx2>(a, actRegAvx2_, WRegs_avx2_[r * S_ + s]); } a->imul(scratchReg2_, W_R_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->add(scratchReg1_, scratchReg2_); } if (!isZeroPointZero_) { for (int r = R_ - H_PAD_; r < R_; ++r) { for (int s = 0; s < S_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } } // we updating the last row a->mov(scratchReg1_, H_R_); a->sub(scratchReg1_, 1); a->imul(scratchReg1_, W_R_); a->imul(scratchReg1_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->add(out_acts_R_, scratchReg1_); // storeResult<inst_set_t::avx2>(a, (H_-1)*W_*K_*sizeof(int32_t)); storeResult<inst_set_t::avx2>(a); a->add(out_acts_R_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); // bottom edge excluding corners asmjit::Label LoopBottomEdge = a->newLabel(); a->mov(loopR2_, static_cast<asmjit::Imm>(W_PAD_)); a->bind(LoopBottomEdge); // zero out a->vxorps(resultRegAvx2_, resultRegAvx2_, resultRegAvx2_); a->mov(scratchReg1_, H_R_); a->sub(scratchReg1_, static_cast<asmjit::Imm>(2 * H_PAD_)); a->imul(scratchReg1_, W_R_); a->imul(scratchReg1_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); for (int r = 0; r < R_ - W_PAD_; ++r) { // int h_in = H_-2*H_PAD_ + r; for (int s = 0; s < S_; ++s) { a->vbroadcastsd( actRegAvx2_, x86::dword_ptr( in_acts_R_, scratchReg1_, 0, s * C_ * sizeof(uint8_t))); gen8bitFMA<inst_set_t::avx2>(a, actRegAvx2_, WRegs_avx2_[r * S_ + s]); } a->imul(scratchReg2_, W_R_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->add(scratchReg1_, scratchReg2_); } if (!isZeroPointZero_) { for (int r = R_ - W_PAD_; r < R_; ++r) { for (int s = 0; s < S_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } } a->add(in_acts_R_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); // storeResult<inst_set_t::avx2>(a, ((H_-1)*W_+1)*K_*sizeof(int32_t)); storeResult<inst_set_t::avx2>(a); a->add(out_acts_R_, static_cast<asmjit::Imm>(K_ * sizeof(int32_t))); a->inc(loopR2_); a->mov(loopR1_, W_R_); a->sub(loopR1_, static_cast<asmjit::Imm>(W_PAD_)); a->cmp(loopR2_, loopR1_); a->jl(LoopBottomEdge); a->mov(scratchReg1_, W_R_); a->sub(scratchReg1_, static_cast<asmjit::Imm>(2 * W_PAD_)); a->imul(scratchReg1_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->sub(in_acts_R_, scratchReg1_); // a->sub(in_acts_R_, (W_ - 2*W_PAD_)*C_*sizeof(uint8_t)); // a->sub(out_acts_R_, (W_ - 2*W_PAD_)*K_*sizeof(int32_t)); // bottom-right corner // zero out a->vxorps(resultRegAvx2_, resultRegAvx2_, resultRegAvx2_); // input start point // ((H_-(R_-H_PAD_))*W_+(W_-(S_-W_PAD_)))*C_*sizeof(uint8_t) a->mov(scratchReg1_, H_R_); a->sub(scratchReg1_, static_cast<asmjit::Imm>(R_ - H_PAD_)); a->imul(scratchReg1_, W_R_); a->add(scratchReg1_, W_R_); a->sub(scratchReg1_, static_cast<asmjit::Imm>(S_ - W_PAD_)); a->imul(scratchReg1_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); for (int r = 0; r < R_ - H_PAD_; ++r) { for (int s = 0; s < S_ - W_PAD_; ++s) { a->vbroadcastsd( actRegAvx2_, x86::dword_ptr( in_acts_R_, scratchReg1_, 0, s * C_ * sizeof(uint8_t))); gen8bitFMA<inst_set_t::avx2>(a, actRegAvx2_, WRegs_avx2_[r * S_ + s]); } a->imul(scratchReg2_, W_R_, static_cast<asmjit::Imm>(C_ * sizeof(uint8_t))); a->add(scratchReg1_, scratchReg2_); if (!isZeroPointZero_) { for (int s = S_ - W_PAD_; s < S_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } } if (!isZeroPointZero_) { for (int r = R_ - H_PAD_; r < R_; ++r) { for (int s = 0; s < S_; ++s) { gen8bitFMA<inst_set_t::avx2>( a, zeroPTRegAvx2_, WRegs_avx2_[r * S_ + s]); } } } storeResult<inst_set_t::avx2>(a); // storeResult<inst_set_t::avx2>(a, ((H_-1)*W_+W_-1)*K_*sizeof(int32_t)); // reset output pointer a->mo
c++
code
20,000
5,447
#pragma once #include "thread_utility.hpp" #include <dispatch/dispatch.h> #include <sstream> #include <string> namespace krbn { class gcd_utility final { public: class scoped_queue final { public: scoped_queue(void) { auto label = get_next_queue_label(); queue_ = dispatch_queue_create(label.c_str(), nullptr); } ~scoped_queue(void) { dispatch_release(queue_); } dispatch_queue_t _Nonnull get(void) { return queue_; } std::string get_label(void) { auto p = dispatch_queue_get_label(queue_); return p ? p : ""; } private: dispatch_queue_t _Nonnull queue_; }; static void dispatch_sync_in_main_queue(void (^_Nonnull block)(void)) { if (thread_utility::is_main_thread()) { block(); } else { dispatch_sync(dispatch_get_main_queue(), block); } } class main_queue_timer final { public: main_queue_timer(dispatch_time_t start, uint64_t interval, uint64_t leeway, void (^_Nonnull block)(void)) { timer_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); if (timer_) { dispatch_source_set_timer(timer_, start, interval, leeway); dispatch_source_set_event_handler(timer_, block); dispatch_resume(timer_); } } ~main_queue_timer(void) { // Release timer_ in main thread to avoid callback invocations after object has been destroyed. dispatch_sync_in_main_queue(^{ if (timer_) { dispatch_source_cancel(timer_); dispatch_release(timer_); } }); } private: dispatch_source_t _Nonnull timer_; }; // We want to cancel the block execution if the instance has been deleted. // Thus, we don't use `dispatch_after`. class main_queue_after_timer final { public: main_queue_after_timer(dispatch_time_t when, bool is_strict, void (^_Nonnull block)(void)) { unsigned long mask = 0; if (is_strict) { mask |= DISPATCH_TIMER_STRICT; } timer_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, mask, dispatch_get_main_queue()); if (timer_) { uint64_t interval = 100.0 * NSEC_PER_SEC; /* dummy value */ dispatch_source_set_timer(timer_, when, interval, 0); dispatch_source_set_event_handler(timer_, ^{ cancel(); block(); }); dispatch_resume(timer_); } } ~main_queue_after_timer(void) { cancel(); } bool fired(void) const { bool __block r; gcd_utility::dispatch_sync_in_main_queue(^{ r = !timer_; }); return r; } private: void cancel(void) { // Release timer_ in main thread to avoid callback invocations after object has been destroyed. gcd_utility::dispatch_sync_in_main_queue(^{ if (timer_) { dispatch_source_cancel(timer_); dispatch_release(timer_); timer_ = nullptr; } }); } dispatch_source_t _Nonnull timer_; }; class fire_while_false_timer final { public: fire_while_false_timer(uint64_t interval, bool (^_Nonnull block)(void)) { timer_ = std::make_unique<gcd_utility::main_queue_timer>( DISPATCH_TIME_NOW, interval, 0, ^{ if (block()) { timer_ = nullptr; } }); } ~fire_while_false_timer(void) { timer_ = nullptr; } private: std::unique_ptr<main_queue_timer> timer_; }; private: static std::string get_next_queue_label(void) { static std::mutex mutex; std::lock_guard<std::mutex> guard(mutex); static int id = 0; std::stringstream stream; stream << "org.pqrs.gcd_utility." << id++; return stream.str(); } }; } // namespace krbn
c++
code
3,797
685
// Copyright 2017 The Ray 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 <future> #include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/function.hpp> #include "ray/common/status.h" #include "ray/common/common_protocol.h" #include "ray/object_manager/object_store_notification_manager.h" #include "ray/util/util.h" #ifdef _WIN32 #include <win32fd.h> #endif namespace ray { ObjectStoreNotificationManager::ObjectStoreNotificationManager( boost::asio::io_service &io_service, const std::string &store_socket_name, bool exit_on_error) : store_client_(), length_(0), num_adds_processed_(0), num_removes_processed_(0), socket_(io_service), exit_on_error_(exit_on_error) { RAY_ARROW_CHECK_OK(store_client_.Connect(store_socket_name.c_str(), "", 0, 300)); int fd; RAY_ARROW_CHECK_OK(store_client_.Subscribe(&fd)); boost::system::error_code ec; #ifdef _WIN32 boost::asio::detail::socket_type c_socket = fh_release(fd); WSAPROTOCOL_INFO pi; size_t n = sizeof(pi); char *p = reinterpret_cast<char *>(&pi); const int level = SOL_SOCKET; const int opt = SO_PROTOCOL_INFO; if (boost::asio::detail::socket_ops::getsockopt(c_socket, 0, level, opt, p, &n, ec) != boost::asio::detail::socket_error_retval) { switch (pi.iAddressFamily) { case AF_INET: socket_.assign(boost::asio::ip::tcp::v4(), c_socket, ec); break; case AF_INET6: socket_.assign(boost::asio::ip::tcp::v6(), c_socket, ec); break; default: ec = boost::system::errc::make_error_code( boost::system::errc::address_family_not_supported); break; } } #else socket_.assign(boost::asio::local::stream_protocol(), fd, ec); #endif RAY_CHECK(!ec); NotificationWait(); } ObjectStoreNotificationManager::~ObjectStoreNotificationManager() { RAY_ARROW_CHECK_OK(store_client_.Disconnect()); } void ObjectStoreNotificationManager::Shutdown() { RAY_ARROW_CHECK_OK(store_client_.Disconnect()); } void ObjectStoreNotificationManager::NotificationWait() { boost::asio::async_read(socket_, boost::asio::buffer(&length_, sizeof(length_)), boost::bind(&ObjectStoreNotificationManager::ProcessStoreLength, this, boost::asio::placeholders::error)); } void ObjectStoreNotificationManager::ProcessStoreLength( const boost::system::error_code &error) { notification_.resize(length_); if (error) { if (exit_on_error_) { // When shutting down a cluster, it's possible that the plasma store is killed // earlier than raylet. In this case we don't want raylet to crash, we instead // log an error message and exit. RAY_LOG(ERROR) << "Failed to process store length: " << boost_to_ray_status(error).ToString() << ", most likely plasma store is down, raylet will exit"; // Exit raylet process. _exit(kRayletStoreErrorExitCode); } else { // The log level is set to debug so user don't see it on ctrl+c exit. RAY_LOG(DEBUG) << "Failed to process store length: " << boost_to_ray_status(error).ToString() << ", most likely plasma store is down. " << "The error is silenced because exit_on_error_ " << "flag is set."; return; } } boost::asio::async_read( socket_, boost::asio::buffer(notification_), boost::bind(&ObjectStoreNotificationManager::ProcessStoreNotification, this, boost::asio::placeholders::error)); } void ObjectStoreNotificationManager::ProcessStoreNotification( const boost::system::error_code &error) { if (error) { if (exit_on_error_) { RAY_LOG(FATAL) << "Problem communicating with the object store from raylet, check logs or " << "dmesg for previous errors: " << boost_to_ray_status(error).ToString(); } else { // The log level is set to debug so user don't see it on ctrl+c exit. RAY_LOG(DEBUG) << "Problem communicating with the object store from raylet, check logs or " << "dmesg for previous errors: " << boost_to_ray_status(error).ToString() << " The error is silenced because exit_on_error_ " << "flag is set."; return; } } const auto &object_notification = flatbuffers::GetRoot<object_manager::protocol::PlasmaNotification>( notification_.data()); for (size_t i = 0; i < object_notification->object_info()->size(); ++i) { auto object_info = object_notification->object_info()->Get(i); const ObjectID object_id = ObjectID::FromPlasmaIdBinary(object_info->object_id()->str()); if (object_info->is_deletion()) { ProcessStoreRemove(object_id); } else { object_manager::protocol::ObjectInfoT result; object_info->UnPackTo(&result); ProcessStoreAdd(result); } } NotificationWait(); } void ObjectStoreNotificationManager::ProcessStoreAdd( const object_manager::protocol::ObjectInfoT &object_info) { for (auto &handler : add_handlers_) { handler(object_info); } num_adds_processed_++; } void ObjectStoreNotificationManager::ProcessStoreRemove(const ObjectID &object_id) { for (auto &handler : rem_handlers_) { handler(object_id); } num_removes_processed_++; } void ObjectStoreNotificationManager::SubscribeObjAdded( std::function<void(const object_manager::protocol::ObjectInfoT &)> callback) { add_handlers_.push_back(std::move(callback)); } void ObjectStoreNotificationManager::SubscribeObjDeleted( std::function<void(const ObjectID &)> callback) { rem_handlers_.push_back(std::move(callback)); } std::string ObjectStoreNotificationManager::DebugString() const { std::stringstream result; result << "ObjectStoreNotificationManager:"; result << "\n- num adds processed: " << num_adds_processed_; result << "\n- num removes processed: " << num_removes_processed_; return result.str(); } } // namespace ray
c++
code
6,588
1,364
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/vod/v20180717/model/ConcatFileInfo2017.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Vod::V20180717::Model; using namespace rapidjson; using namespace std; ConcatFileInfo2017::ConcatFileInfo2017() : m_errCodeHasBeenSet(false), m_messageHasBeenSet(false), m_fileIdHasBeenSet(false), m_fileUrlHasBeenSet(false), m_fileTypeHasBeenSet(false) { } CoreInternalOutcome ConcatFileInfo2017::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("ErrCode") && !value["ErrCode"].IsNull()) { if (!value["ErrCode"].IsInt64()) { return CoreInternalOutcome(Error("response `ConcatFileInfo2017.ErrCode` IsInt64=false incorrectly").SetRequestId(requestId)); } m_errCode = value["ErrCode"].GetInt64(); m_errCodeHasBeenSet = true; } if (value.HasMember("Message") && !value["Message"].IsNull()) { if (!value["Message"].IsString()) { return CoreInternalOutcome(Error("response `ConcatFileInfo2017.Message` IsString=false incorrectly").SetRequestId(requestId)); } m_message = string(value["Message"].GetString()); m_messageHasBeenSet = true; } if (value.HasMember("FileId") && !value["FileId"].IsNull()) { if (!value["FileId"].IsString()) { return CoreInternalOutcome(Error("response `ConcatFileInfo2017.FileId` IsString=false incorrectly").SetRequestId(requestId)); } m_fileId = string(value["FileId"].GetString()); m_fileIdHasBeenSet = true; } if (value.HasMember("FileUrl") && !value["FileUrl"].IsNull()) { if (!value["FileUrl"].IsString()) { return CoreInternalOutcome(Error("response `ConcatFileInfo2017.FileUrl` IsString=false incorrectly").SetRequestId(requestId)); } m_fileUrl = string(value["FileUrl"].GetString()); m_fileUrlHasBeenSet = true; } if (value.HasMember("FileType") && !value["FileType"].IsNull()) { if (!value["FileType"].IsString()) { return CoreInternalOutcome(Error("response `ConcatFileInfo2017.FileType` IsString=false incorrectly").SetRequestId(requestId)); } m_fileType = string(value["FileType"].GetString()); m_fileTypeHasBeenSet = true; } return CoreInternalOutcome(true); } void ConcatFileInfo2017::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_errCodeHasBeenSet) { Value iKey(kStringType); string key = "ErrCode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_errCode, allocator); } if (m_messageHasBeenSet) { Value iKey(kStringType); string key = "Message"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_message.c_str(), allocator).Move(), allocator); } if (m_fileIdHasBeenSet) { Value iKey(kStringType); string key = "FileId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_fileId.c_str(), allocator).Move(), allocator); } if (m_fileUrlHasBeenSet) { Value iKey(kStringType); string key = "FileUrl"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_fileUrl.c_str(), allocator).Move(), allocator); } if (m_fileTypeHasBeenSet) { Value iKey(kStringType); string key = "FileType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_fileType.c_str(), allocator).Move(), allocator); } } int64_t ConcatFileInfo2017::GetErrCode() const { return m_errCode; } void ConcatFileInfo2017::SetErrCode(const int64_t& _errCode) { m_errCode = _errCode; m_errCodeHasBeenSet = true; } bool ConcatFileInfo2017::ErrCodeHasBeenSet() const { return m_errCodeHasBeenSet; } string ConcatFileInfo2017::GetMessage() const { return m_message; } void ConcatFileInfo2017::SetMessage(const string& _message) { m_message = _message; m_messageHasBeenSet = true; } bool ConcatFileInfo2017::MessageHasBeenSet() const { return m_messageHasBeenSet; } string ConcatFileInfo2017::GetFileId() const { return m_fileId; } void ConcatFileInfo2017::SetFileId(const string& _fileId) { m_fileId = _fileId; m_fileIdHasBeenSet = true; } bool ConcatFileInfo2017::FileIdHasBeenSet() const { return m_fileIdHasBeenSet; } string ConcatFileInfo2017::GetFileUrl() const { return m_fileUrl; } void ConcatFileInfo2017::SetFileUrl(const string& _fileUrl) { m_fileUrl = _fileUrl; m_fileUrlHasBeenSet = true; } bool ConcatFileInfo2017::FileUrlHasBeenSet() const { return m_fileUrlHasBeenSet; } string ConcatFileInfo2017::GetFileType() const { return m_fileType; } void ConcatFileInfo2017::SetFileType(const string& _fileType) { m_fileType = _fileType; m_fileTypeHasBeenSet = true; } bool ConcatFileInfo2017::FileTypeHasBeenSet() const { return m_fileTypeHasBeenSet; }
c++
code
5,762
1,152
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "chainparams.h" #include "validation.h" #include "streams.h" #include "consensus/validation.h" namespace block_bench { #include "bench/data/block413567.raw.h" } // These are the two major time-sinks which happen after we have fully received // a block off the wire, but before we can relay the block on to peers using // compact block relay. // Searchcoin uses block height 878439, hash 0babe680f55a55d54339511226755f0837261da89a4e78eba4d6436a63026df8 // which contains 3808 transactions. static void DeserializeBlockTest(benchmark::State& state) { CDataStream stream((const char*)block_bench::block413567, (const char*)&block_bench::block413567[sizeof(block_bench::block413567)], SER_NETWORK, PROTOCOL_VERSION); char a; stream.write(&a, 1); // Prevent compaction while (state.KeepRunning()) { CBlock block; stream >> block; assert(stream.Rewind(sizeof(block_bench::block413567))); } } static void DeserializeAndCheckBlockTest(benchmark::State& state) { CDataStream stream((const char*)block_bench::block413567, (const char*)&block_bench::block413567[sizeof(block_bench::block413567)], SER_NETWORK, PROTOCOL_VERSION); char a; stream.write(&a, 1); // Prevent compaction Consensus::Params params = Params(CBaseChainParams::MAIN).GetConsensus(); while (state.KeepRunning()) { CBlock block; // Note that CBlock caches its checked state, so we need to recreate it here stream >> block; assert(stream.Rewind(sizeof(block_bench::block413567))); CValidationState validationState; assert(CheckBlock(block, validationState, params)); } } BENCHMARK(DeserializeBlockTest); BENCHMARK(DeserializeAndCheckBlockTest);
c++
code
1,986
376
#include "world_window.hpp" #include "world_cell.hpp" using namespace std; WorldWindow::WorldWindow() { } WorldWindow::WorldWindow(unsigned int windowSize) { this->windowSize = windowSize; } vector<Entity*> WorldWindow::getEntities()const { int len = 0; for ( map<Vec2i, WorldCell>::const_iterator it = cells.begin(); it != cells.end(); ++it ) { len += it->second.size(); } vector<Entity*> res; res.reserve(len); for ( map<Vec2i, WorldCell>::const_iterator it = cells.begin(); it != cells.end(); ++it ) { const WorldCell& wc = it->second; for(unsigned int i=0; i<wc.size(); i++) { res.push_back( wc[i] ); } } return res; } WorldWindow::~WorldWindow() { }
c++
code
831
207
/* Copyright Disney Enterprises, Inc. All rights reserved. This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non- infringement. */ #include <stdio.h> #include "BRDFAnalytic.h" BRDFAnalytic::BRDFAnalytic() { } BRDFAnalytic::~BRDFAnalytic() { } bool BRDFAnalytic::canReadSectionType( std::string type ) { if( type == "shader" ) return true; if( type == "isFunc" ) return true; return false; } bool BRDFAnalytic::beginSection( std::string section ) { if( section == "shader" ) shader = ""; if( section == "isFunc" ) isFunc = ""; return true; } bool BRDFAnalytic::processLineFromSection( std::string section, std::string line ) { if( section == "shader" ) shader = shader + line + std::string("\n"); else if( section == "isFunc" ) isFunc = isFunc + line + std::string("\n"); return true; } bool BRDFAnalytic::endFile() { return true; } std::string BRDFAnalytic::getBRDFFunction() { return shader; } std::string BRDFAnalytic::getISFunction() { // return the custom function if we have one if( isFunc.length() ) return isFunc; // otherwise, return the base function return BRDFBase::getISFunction(); } bool BRDFAnalytic::hasISFunction() { if( isFunc.length() ) return true; return false; }
c++
code
3,837
787
// $Id$ /* Copyright (c) 2007-2015, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "booksim.hpp" #include <iostream> #include "maxsize.hpp" // shortest augmenting path: // // for all unmatched left nodes, // push node onto work stack // end // // for all j, // from[j] = undefined // end // // do, // // while( !stack.empty ), // // nl = stack.pop // for each edge (nl,j), // if ( ( lmatch[nl] != j ) && ( from[j] == undefined ) ), // if ( rmatch[j] == undefined ), // stop // augmenting path found // else // from[j] = nl // newstack.push( rmatch[j] ) // end // end // end // end // // stack = newstack // end // //#define DEBUG_MAXSIZE //#define PRINT_MATCHING MaxSizeMatch::MaxSizeMatch(Module *parent, const string &name, int inputs, int outputs) : DenseAllocator(parent, name, inputs, outputs) { _from.resize(outputs); _s = new int[inputs]; _ns = new int[inputs]; _prio = 0; } MaxSizeMatch::~MaxSizeMatch() { delete[] _s; delete[] _ns; } void MaxSizeMatch::Allocate() { // augment as many times as possible // (this is an O(N^3) maximum-size matching algorithm) while (_ShortestAugmenting()) ; // next time, start at next input to ensure fairness _prio = (_prio + 1) % _inputs; } bool MaxSizeMatch::_ShortestAugmenting() { int i, j, jn; int slen, nslen; // start with empty stack slen = 0; // push all unassigned inputs to the stack for (i = 0; i < _inputs; ++i) { j = (i + _prio) % _inputs; if (_inmatch[j] == -1) { // start with unmatched left nodes _s[slen++] = j; } } _from.assign(_inputs, -1); for (int iter = 0; iter < _inputs; iter++) { nslen = 0; for (int e = 0; e < slen; ++e) { i = _s[e]; for (j = 0; j < _outputs; ++j) { if ((_request[i][j].label != -1) && // edge (i,j) exists (_inmatch[i] != j) && // (i,j) is not contained in the current matching (_from[j] == -1)) { // no shorter path to j exists _from[j] = i; // how did we get to j? #ifdef DEBUG_MAXSIZE cout << " got to " << j << " from " << i << endl; #endif if (_outmatch[j] == -1) { // j is unmatched -- augmenting path found goto found_augmenting; } else { // j is matched _ns[nslen] = _outmatch[j]; // add the destination of this edge to the leaf nodes nslen++; #ifdef DEBUG_MAXSIZE cout << " adding " << _outmatch[j] << endl; #endif } } } } // no augmenting path found yet, swap stacks int *t = _s; _s = _ns; _ns = t; slen = nslen; } return false; // no augmenting paths found_augmenting: // the augmenting path ends at node j on the right #ifdef DEBUG_MAXSIZE cout << "Found path: " << j << "c <- "; #endif i = _from[j]; _outmatch[j] = i; #ifdef DEBUG_MAXSIZE cout << i; #endif while (_inmatch[i] != -1) { // loop until the end of the path jn = _inmatch[i]; // remove previous edge (i,jn) and add (i,j) _inmatch[i] = j; #ifdef DEBUG_MAXSIZE cout << " <- " << j << "c <- "; #endif j = jn; // add edge from (jn,in) i = _from[j]; _outmatch[j] = i; #ifdef DEBUG_MAXSIZE cout << i; #endif } #ifdef DEBUG_MAXSIZE cout << endl; #endif _inmatch[i] = j; #ifdef PRINT_MATCHING cout << "left matching: "; for (i = 0; i < _inputs; i++) { cout << _inmatch[i] << " "; } cout << endl; cout << "right matching: "; for (i = 0; i < _outputs; i++) { cout << _outmatch[i] << " "; } cout << endl; #endif return true; }
c++
code
5,278
1,230
// // c4Query.hh // // Copyright (c) 2020 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include "c4Base.hh" #include "c4QueryTypes.h" #include <functional> #include <memory> #include <mutex> #include <set> #include <utility> C4_ASSUME_NONNULL_BEGIN // ************************************************************************ // This header is part of the LiteCore C++ API. // If you use this API, you must _statically_ link LiteCore; // the dynamic library only exports the C API. // ************************************************************************ /** A compiled database query. */ struct C4Query final : public fleece::RefCounted, public fleece::InstanceCountedIn<C4Query>, C4Base { public: /// Creates a new query on a database. static Retained<C4Query> newQuery(C4Database*, C4QueryLanguage, slice queryExpression, int* C4NULLABLE outErrorPos); /// Creates a new query on the collection's database. /// If the query does not refer to a collection by name (e.g. "FROM airlines"), /// it will use the given collection instead of the default one. static Retained<C4Query> newQuery(C4Collection*, C4QueryLanguage, slice queryExpression, int* C4NULLABLE outErrorPos); unsigned columnCount() const noexcept; slice columnTitle(unsigned col) const; alloc_slice explain() const; alloc_slice parameters() const noexcept {return _parameters;} void setParameters(slice parameters) {_parameters = parameters;} alloc_slice fullTextMatched(const C4FullTextMatch&); // Running the query: /// C++ query enumerator; equivalent to C4QueryEnumerator but more C++-friendly. class Enumerator { public: bool next(); int64_t rowCount() const; void seek(int64_t rowIndex); FLArrayIterator columns() const; FLValue column(unsigned i) const; unsigned fullTextMatchCount() const; C4FullTextMatch fullTextMatch(unsigned i) const; bool restart(); void close() noexcept; Enumerator(Enumerator&&); ~Enumerator(); private: friend struct C4Query; friend class litecore::C4QueryObserverImpl; explicit Enumerator(C4Query*, const C4QueryOptions* C4NULLABLE =nullptr, slice encodedParameters =fleece::nullslice); explicit Enumerator(Retained<litecore::QueryEnumerator> e); Retained<litecore::QueryEnumerator> _enum; Retained<litecore::Query> _query; }; /// Runs the query, returning an enumerator. Use it like this: /// ``` /// auto e = query.run(); /// while (e.next()) { ... } /// ``` Enumerator run(const C4QueryOptions* C4NULLABLE opt =nullptr, slice params =fleece::nullslice); /// Creates a C-style enumerator. Prefer \ref run to this. C4QueryEnumerator* createEnumerator(const C4QueryOptions* C4NULLABLE, slice params =fleece::nullslice); // Observer: using ObserverCallback = std::function<void(C4QueryObserver*)>; std::unique_ptr<C4QueryObserver> observe(ObserverCallback); protected: friend class litecore::C4QueryObserverImpl; C4Query(C4Collection*, C4QueryLanguage language, slice queryExpression); ~C4Query(); void enableObserver(litecore::C4QueryObserverImpl *obs, bool enable); private: class LiveQuerierDelegate; Retained<litecore::QueryEnumerator> _createEnumerator(const C4QueryOptions* C4NULLABLE, slice params); Retained<litecore::C4QueryEnumeratorImpl> wrapEnumerator(litecore::QueryEnumerator*); void liveQuerierUpdated(litecore::QueryEnumerator *qe, C4Error err); Retained<litecore::DatabaseImpl> _database; Retained<litecore::Query> _query; alloc_slice _parameters; Retained<litecore::LiveQuerier> _bgQuerier; std::unique_ptr<LiveQuerierDelegate> _bgQuerierDelegate; std::set<litecore::C4QueryObserverImpl*> _observers; mutable std::mutex _mutex; }; /** A registration for callbacks whenever a query's result set changes. The registration lasts until this object is destructed. Created by calling \ref C4Query::observe. */ struct C4QueryObserver : public fleece::InstanceCounted, C4Base { public: virtual ~C4QueryObserver() = default; C4Query* query() const {return _query;} virtual void setEnabled(bool enabled) =0; /// If the latest run of the query failed, the error will be stored here, with nonzero `code`. /// Always check the error before getting the enumerator. C4Error getError() const {return _currentError;} /// Returns a new enumerator on the query results. /// If the query failed, throws that error as an exception. virtual C4Query::Enumerator getEnumerator(bool forget =true) =0; protected: C4QueryObserver(C4Query *query) :_query(query) { } Retained<C4Query> _query; C4Error _currentError {}; }; C4_ASSUME_NONNULL_END
c++
code
5,997
1,141
/* file: maximum_pooling1d_backward_batch.cpp */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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 <jni.h> #include "neural_networks/layers/maximum_pooling1d/JMaximumPooling1dBackwardBatch.h" #include "daal.h" #include "common_helpers.h" using namespace daal; using namespace daal::algorithms::neural_networks::layers; /* * Class: com_intel_daal_algorithms_neural_networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch * Method: cInit * Signature: (II)J */ JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch_cInit (JNIEnv *env, jobject thisObj, jint prec, jint method, jlong nDim) { return jniBatch<maximum_pooling1d::Method, maximum_pooling1d::backward::Batch, maximum_pooling1d::defaultDense>:: newObj(prec, method, nDim); } /* * Class: com_intel_daal_algorithms_neural_networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch * Method: cGetInput * Signature: (JII)J */ JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch_cGetInput (JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method) { return jniBatch<maximum_pooling1d::Method, maximum_pooling1d::backward::Batch, maximum_pooling1d::defaultDense>:: getInput(prec, method, algAddr); } /* * Class: com_intel_daal_algorithms_neural_networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch * Method: cInitParameter * Signature: (JII)J */ JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch_cInitParameter (JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method) { return jniBatch<maximum_pooling1d::Method, maximum_pooling1d::backward::Batch, maximum_pooling1d::defaultDense>:: getParameter(prec, method, algAddr); } /* * Class: com_intel_daal_algorithms_neural_networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch * Method: cGetResult * Signature: (JII)J */ JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch_cGetResult (JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method) { return jniBatch<maximum_pooling1d::Method, maximum_pooling1d::backward::Batch, maximum_pooling1d::defaultDense>:: getResult(prec, method, algAddr); } /* * Class: com_intel_daal_algorithms_neural_networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch * Method: cSetResult * Signature: (JIIJ)V */ JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch_cSetResult (JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method, jlong resAddr) { jniBatch<maximum_pooling1d::Method, maximum_pooling1d::backward::Batch, maximum_pooling1d::defaultDense>:: setResult<maximum_pooling1d::backward::Result>(prec, method, algAddr, resAddr); } /* * Class: com_intel_daal_algorithms_neural_networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch * Method: cClone * Signature: (JII)J */ JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_maximum_1pooling1d_MaximumPooling1dBackwardBatch_cClone (JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method) { return jniBatch<maximum_pooling1d::Method, maximum_pooling1d::backward::Batch, maximum_pooling1d::defaultDense>:: getClone(prec, method, algAddr); }
c++
code
5,694
1,015
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======= // // Purpose: // //============================================================================= #include "cbase.h" #include "tf_weapon_pipebomblauncher.h" #include "tf_fx_shared.h" #include "tf_weapon_grenade_pipebomb.h" #include "in_buttons.h" #include "datacache/imdlcache.h" // Client specific. #ifdef CLIENT_DLL #include "c_tf_player.h" #include <vgui_controls/Panel.h> #include <vgui/ISurface.h> #include "prediction.h" // Server specific. #else #include "tf_player.h" #include "tf_gamestats.h" #endif // Delete me and put in script extern ConVar tf_grenadelauncher_livetime; // hard code these eventually #define TF_PIPEBOMB_MIN_CHARGE_VEL 900 #define TF_PIPEBOMB_MAX_CHARGE_VEL 2400 #define TF_PIPEBOMB_MAX_CHARGE_TIME 4.0f //============================================================================= // // Weapon Pipebomb Launcher tables. // IMPLEMENT_NETWORKCLASS_ALIASED( TFPipebombLauncher, DT_WeaponPipebombLauncher ) BEGIN_NETWORK_TABLE_NOBASE( CTFPipebombLauncher, DT_PipebombLauncherLocalData ) #ifdef CLIENT_DLL RecvPropInt( RECVINFO( m_iPipebombCount ) ), #else SendPropInt( SENDINFO( m_iPipebombCount ), 5, SPROP_UNSIGNED ), #endif END_NETWORK_TABLE() BEGIN_NETWORK_TABLE( CTFPipebombLauncher, DT_WeaponPipebombLauncher ) #ifdef CLIENT_DLL RecvPropDataTable( "PipebombLauncherLocalData", 0, 0, &REFERENCE_RECV_TABLE( DT_PipebombLauncherLocalData ) ), #else SendPropDataTable( "PipebombLauncherLocalData", 0, &REFERENCE_SEND_TABLE( DT_PipebombLauncherLocalData ), SendProxy_SendLocalWeaponDataTable ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CTFPipebombLauncher ) DEFINE_FIELD( m_flChargeBeginTime, FIELD_FLOAT ) END_PREDICTION_DATA() #endif LINK_ENTITY_TO_CLASS( tf_weapon_pipebomblauncher, CTFPipebombLauncher ); PRECACHE_WEAPON_REGISTER( tf_weapon_pipebomblauncher ); // Server specific. #ifndef CLIENT_DLL BEGIN_DATADESC( CTFPipebombLauncher ) END_DATADESC() #endif //============================================================================= // // Weapon Pipebomb Launcher functions. // //----------------------------------------------------------------------------- // Purpose: // Input : - //----------------------------------------------------------------------------- CTFPipebombLauncher::CTFPipebombLauncher() { m_bReloadsSingly = true; m_flLastDenySoundTime = 0.0f; } //----------------------------------------------------------------------------- // Purpose: // Input : - //----------------------------------------------------------------------------- CTFPipebombLauncher::~CTFPipebombLauncher() { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFPipebombLauncher::Spawn( void ) { m_iAltFireHint = HINT_ALTFIRE_PIPEBOMBLAUNCHER; BaseClass::Spawn(); } //----------------------------------------------------------------------------- // Purpose: Reset the charge when we holster //----------------------------------------------------------------------------- bool CTFPipebombLauncher::Holster( CBaseCombatWeapon *pSwitchingTo ) { m_flChargeBeginTime = 0; StopSound("Weapon_StickyBombLauncher.ChargeUp"); return BaseClass::Holster( pSwitchingTo ); } //----------------------------------------------------------------------------- // Purpose: Reset the charge when we deploy //----------------------------------------------------------------------------- bool CTFPipebombLauncher::Deploy( void ) { m_flChargeBeginTime = 0; return BaseClass::Deploy(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFPipebombLauncher::WeaponReset( void ) { BaseClass::WeaponReset(); #ifndef CLIENT_DLL DetonateRemotePipebombs( true ); #endif m_flChargeBeginTime = 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFPipebombLauncher::PrimaryAttack( void ) { // Check for ammunition. if ( m_iClip1 <= 0 && m_iClip1 != -1 ) return; // Are we capable of firing again? if ( m_flNextPrimaryAttack > gpGlobals->curtime ) return; if ( !CanAttack() ) { m_flChargeBeginTime = 0; return; } if ( m_flChargeBeginTime <= 0 ) { // Set the weapon mode. m_iWeaponMode = TF_WEAPON_PRIMARY_MODE; // save that we had the attack button down m_flChargeBeginTime = gpGlobals->curtime; SendWeaponAnim( ACT_VM_PULLBACK ); } else { float flTotalChargeTime = gpGlobals->curtime - m_flChargeBeginTime; if ( flTotalChargeTime >= TF_PIPEBOMB_MAX_CHARGE_TIME ) { LaunchGrenade(); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFPipebombLauncher::WeaponIdle( void ) { if ( m_flChargeBeginTime > 0 && m_iClip1 > 0 ) { LaunchGrenade(); } else { BaseClass::WeaponIdle(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFPipebombLauncher::LaunchGrenade( void ) { // Get the player owning the weapon. CTFPlayer *pPlayer = ToTFPlayer( GetPlayerOwner() ); if ( !pPlayer ) return; StopSound("Weapon_StickyBombLauncher.ChargeUp"); CalcIsAttackCritical(); SendWeaponAnim( ACT_VM_PRIMARYATTACK ); pPlayer->SetAnimation( PLAYER_ATTACK1 ); pPlayer->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_PRIMARY ); CTFGrenadePipebombProjectile *pProjectile = static_cast<CTFGrenadePipebombProjectile*>( FireProjectile( pPlayer ) ); if ( pProjectile ) { // Save the charge time to scale the detonation timer. pProjectile->SetChargeTime( gpGlobals->curtime - m_flChargeBeginTime ); } #if !defined( CLIENT_DLL ) pPlayer->SpeakWeaponFire(); CTF_GameStats.Event_PlayerFiredWeapon( pPlayer, IsCurrentAttackACrit() ); #endif // Set next attack times. float flDelay = m_pWeaponInfo->GetWeaponData( m_iWeaponMode ).m_flTimeFireDelay; CALL_ATTRIB_HOOK_FLOAT( flDelay, mult_postfiredelay ); m_flNextPrimaryAttack = gpGlobals->curtime + flDelay; m_flLastDenySoundTime = gpGlobals->curtime; SetWeaponIdleTime( gpGlobals->curtime + SequenceDuration() ); // Check the reload mode and behave appropriately. if ( m_bReloadsSingly ) { m_iReloadMode.Set( TF_RELOAD_START ); } m_flChargeBeginTime = 0; } float CTFPipebombLauncher::GetProjectileSpeed( void ) { float flForwardSpeed = RemapValClamped( ( gpGlobals->curtime - m_flChargeBeginTime ), 0.0f, TF_PIPEBOMB_MAX_CHARGE_TIME, TF_PIPEBOMB_MIN_CHARGE_VEL, TF_PIPEBOMB_MAX_CHARGE_VEL ); return flForwardSpeed; } void CTFPipebombLauncher::AddPipeBomb( CTFGrenadePipebombProjectile *pBomb ) { PipebombHandle hHandle; hHandle = pBomb; m_Pipebombs.AddToTail( hHandle ); } //----------------------------------------------------------------------------- // Purpose: Add pipebombs to our list as they're fired //----------------------------------------------------------------------------- CBaseEntity *CTFPipebombLauncher::FireProjectile( CTFPlayer *pPlayer ) { CBaseEntity *pProjectile = BaseClass::FireProjectile( pPlayer ); if ( pProjectile ) { #ifdef GAME_DLL int nMaxPipebombs = TF_WEAPON_PIPEBOMB_COUNT; CALL_ATTRIB_HOOK_INT( nMaxPipebombs, add_max_pipebombs ); // If we've gone over the max pipebomb count, detonate the oldest if ( m_Pipebombs.Count() >= nMaxPipebombs ) { CTFGrenadePipebombProjectile *pTemp = m_Pipebombs[0]; if ( pTemp ) { pTemp->SetTimer( gpGlobals->curtime ); // explode NOW } m_Pipebombs.Remove(0); } CTFGrenadePipebombProjectile *pPipebomb = (CTFGrenadePipebombProjectile*)pProjectile; PipebombHandle hHandle; hHandle = pPipebomb; m_Pipebombs.AddToTail( hHandle ); m_iPipebombCount = m_Pipebombs.Count(); #endif } return pProjectile; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFPipebombLauncher::ItemPostFrame( void ) { BaseClass::ItemPostFrame(); // Allow player to fire and detonate at the same time. CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if ( pOwner && !( pOwner->m_nButtons & IN_ATTACK ) ) { if ( m_flChargeBeginTime > 0 && m_iClip1 > 0 ) { LaunchGrenade(); } } } //----------------------------------------------------------------------------- // Purpose: Detonate this demoman's pipebombs if secondary fire is down. //----------------------------------------------------------------------------- void CTFPipebombLauncher::ItemBusyFrame( void ) { #ifdef GAME_DLL CBasePlayer *pOwner = ToBasePlayer( GetOwner() ); if ( pOwner && pOwner->m_nButtons & IN_ATTACK2 ) { // We need to do this to catch the case of player trying to detonate // pipebombs while in the middle of reloading. SecondaryAttack(); } #endif BaseClass::ItemBusyFrame(); } //----------------------------------------------------------------------------- // Purpose: Detonate active pipebombs //----------------------------------------------------------------------------- void CTFPipebombLauncher::SecondaryAttack( void ) { if ( !CanAttack() ) return; if ( m_iPipebombCount ) { // Get a valid player. CTFPlayer *pPlayer = ToTFPlayer( GetOwner() ); if ( !pPlayer ) return; //If one or more pipebombs failed to detonate then play a sound. if ( DetonateRemotePipebombs( false ) == true ) { if ( m_flLastDenySoundTime <= gpGlobals->curtime ) { // Deny! m_flLastDenySoundTime = gpGlobals->curtime + 1; WeaponSound( SPECIAL2 ); return; } } else { // Play a detonate sound. WeaponSound( SPECIAL3 ); } } } //============================================================================= // // Server specific functions. // #ifdef GAME_DLL //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFPipebombLauncher::UpdateOnRemove(void) { // If we just died, we want to fizzle our pipebombs. // If the player switched classes, our pipebombs have already been removed. DetonateRemotePipebombs( true ); BaseClass::UpdateOnRemove(); } #endif //----------------------------------------------------------------------------- // Purpose: If a pipebomb has been removed, remove it from our list //----------------------------------------------------------------------------- void CTFPipebombLauncher::DeathNotice( CBaseEntity *pVictim ) { Assert( dynamic_cast<CTFGrenadePipebombProjectile*>(pVictim) ); PipebombHandle hHandle; hHandle = (CTFGrenadePipebombProjectile*)pVictim; m_Pipebombs.FindAndRemove( hHandle ); m_iPipebombCount = m_Pipebombs.Count(); } //----------------------------------------------------------------------------- // Purpose: Remove *with* explosions //----------------------------------------------------------------------------- bool CTFPipebombLauncher::DetonateRemotePipebombs( bool bFizzle ) { bool bFailedToDetonate = false; int count = m_Pipebombs.Count(); for ( int i = 0; i < count; i++ ) { CTFGrenadePipebombProjectile *pTemp = m_Pipebombs[i]; if ( pTemp ) { //This guy will die soon enough. if ( pTemp->IsEffectActive( EF_NODRAW ) ) continue; #ifdef GAME_DLL if ( bFizzle ) { pTemp->Fizzle(); } #endif if ( bFizzle == false ) { if ( ( gpGlobals->curtime - pTemp->m_flCreationTime ) < tf_grenadelauncher_livetime.GetFloat() ) { bFailedToDetonate = true; continue; } } #ifdef GAME_DLL pTemp->Detonate(); #endif } } return bFailedToDetonate; } float CTFPipebombLauncher::GetChargeMaxTime( void ) { return TF_PIPEBOMB_MAX_CHARGE_TIME; } bool CTFPipebombLauncher::Reload( void ) { if ( m_flChargeBeginTime > 0 ) return false; return BaseClass::Reload(); }
c++
code
12,231
2,959
#include <bits/stdc++.h> #define _overload(_1,_2,_3,name,...) name #define _rep(i,n) _range(i,0,n) #define _range(i,a,b) for(int i=int(a);i<int(b);++i) #define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__) #define _rrep(i,n) _rrange(i,n,0) #define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i) #define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__) #define _all(arg) begin(arg),end(arg) #define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg)) #define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary) #define clr(a,b) memset((a),(b),sizeof(a)) #define bit(n) (1LL<<(n)) #define popcount(n) (__builtin_popcountll(n)) using namespace std; template<class T>bool chmax(T &a, const T &b) { return (a<b)?(a=b,1):0;} template<class T>bool chmin(T &a, const T &b) { return (b<a)?(a=b,1):0;} using ll=long long; using R=long double; const R EPS=1e-9; // [-1000,1000]->EPS=1e-8 [-10000,10000]->EPS=1e-7 inline int sgn(const R& r){return(r > EPS)-(r < -EPS);} inline R sq(R x){return sqrt(max<R>(x,0.0));} const int dx[8]={1,0,-1,0,1,-1,-1,1}; const int dy[8]={0,1,0,-1,1,1,-1,-1}; // Problem Specific Parameter: const int limit=200000; // Description: [1,x]のクエリに対するデータ構造 // TimeComplexity: 更新$\mathcal{O}(\log n)$ クエリ$\mathcal{O}(\log n)$ // Verifyed: ARC 033 C template <typename T> class Binary_indexed_tree{ public: Binary_indexed_tree(int _n):n(_n){data.assign(n+1,0);} void update(int i,T x){ for(;i<=n;i+=i&-i) data[i]+=x; } T query(int i){ T ret=0; for(;i>0;i-=i&-i) ret+=data[i]; return ret; } int lower_bound(T x) { if(x<=0) return 0; int i=0; for(int k=bit(31-__builtin_clz(n));k>0;k>>=1){ if(i+k<=n && data[i+k]<x) x-=data[i+k],i+=k; } return i+1; } private: vector<T> data; int n; }; int main(void){ Binary_indexed_tree<int> Bit(limit); int q; cin >> q; rep(loop,q){ int t,x; cin >> t >> x; if(t==1){ Bit.update(x,1); }else{ int ans=Bit.lower_bound(x); cout << ans << endl; Bit.update(ans,-1); } } return 0; }
c++
code
2,099
818
/* * Copyright (C) Andrey Pikas */ #include "workers_reg.hpp" #include <cstring> namespace pruv { workers_reg::workers_reg() { } workers_reg & workers_reg::instance() { static workers_reg inst; return inst; } void workers_reg::add(const char *name, std::function<worker_loop * ()> factory) { f.emplace_back(name, std::move(factory)); } std::unique_ptr<worker_loop> workers_reg::get(const char *name) const { for (const auto &it : f) if (!strcmp(it.first, name) && it.second) return std::unique_ptr<worker_loop>(it.second()); return std::unique_ptr<worker_loop>(); } } // namespace pruv
c++
code
635
166
#include "msgpass/MeshVariableSynchronizerList.h" #include "msgpass/SyncBuffers.h" /*---------------------------------------------------------------------------*/ /* CellMatVarScalSync<DataType> : a Cell multi-mat variable to synchronize */ /*---------------------------------------------------------------------------*/ template<typename DataType> CellMatVarScalSync<DataType>::CellMatVarScalSync( CellMaterialVariableScalarRef<DataType> var, BufAddrMng* bam) : IMeshVarSync(), m_var (var), m_menv_var(var, bam) { // m_menv_var on DEVICE will be update by bam } template<typename DataType> CellMatVarScalSync<DataType>::~CellMatVarScalSync() { } //! Different sizes/properties depending on unit type template<typename DataType> IMeshVarSync::SizeInfos CellMatVarScalSync<DataType>::sizeInfos() const { return {alignof(DataType), sizeof(DataType), sizeof(DataType)*1}; } //! Pointer to MeshMaterialVariable if it exists (nullptr otherwise) template<typename DataType> MeshMaterialVariable* CellMatVarScalSync<DataType>::materialVariable() { IMeshMaterialVariable* mvar = m_var.materialVariable(); return dynamic_cast<MeshMaterialVariable*>(mvar); } //! Estimate an upper bound of the buffer size to pack <item_sizes> values template<typename DataType> Int64 CellMatVarScalSync<DataType>::estimatedMaxBufSz(IntegerConstArrayView item_sizes) const { return SyncBuffers::estimatedMaxBufSz<DataType>(item_sizes, /*degree=*/1); } //! Asynchronously pack "shared" cell (levis) into the buffer (buf) template<typename DataType> void CellMatVarScalSync<DataType>::asyncPackIntoBuf( ConstArrayView<EnvVarIndex> levis, ArrayView<Byte> buf, RunQueue& queue) { auto command = makeCommand(queue); auto in_var_menv = m_menv_var.spanD(); Span<const EnvVarIndex> in_levis(levis); Span<DataType> buf_vals(MultiBufView::valBuf<DataType>(buf)); Integer nb_evis = levis.size(); command << RUNCOMMAND_LOOP1(iter, nb_evis) { auto [i] = iter(); buf_vals[i] = in_var_menv[ in_levis[i] ]; }; // asynchronous } //! Asynchronously unpack buffer (buf) into "ghost" cell (levis) template<typename DataType> void CellMatVarScalSync<DataType>::asyncUnpackFromBuf( ConstArrayView<EnvVarIndex> levis, ArrayView<Byte> buf, RunQueue& queue) { auto command = makeCommand(queue); auto out_var_menv = m_menv_var.spanD(); Span<const EnvVarIndex> in_levis(levis); Span<const DataType> buf_vals(MultiBufView::valBuf<DataType>(buf)); Integer nb_evis = levis.size(); command << RUNCOMMAND_LOOP1(iter, nb_evis) { auto [i] = iter(); out_var_menv.setValue(in_levis[i], buf_vals[i]); }; // asynchrone } /*---------------------------------------------------------------------------*/ /* MeshVariableSynchronizerList : List of mesh variables to synchronize */ /*---------------------------------------------------------------------------*/ MeshVariableSynchronizerList::MeshVariableSynchronizerList(BufAddrMng* bam) : m_buf_addr_mng (bam) { } MeshVariableSynchronizerList::~MeshVariableSynchronizerList() { for(auto v : m_vars) { delete v; } m_buf_addr_mng->reset(); } //! Add a multi-mat variable into the list of variables to synchronize template<typename DataType> void MeshVariableSynchronizerList::add(CellMaterialVariableScalarRef<DataType> var_menv) { m_vars.add(new CellMatVarScalSync<DataType>(var_menv, m_buf_addr_mng)); } //! Return the list of variables to synchronize ConstArrayView<IMeshVarSync*> MeshVariableSynchronizerList::varsList() const { return m_vars; } //! Asynchronous pointers tranfer onto device void MeshVariableSynchronizerList::asyncHToD(RunQueue& queue) { m_buf_addr_mng->asyncCpyHToD(queue); } /*---------------------------------------------------------------------------*/ /* INSTANCIATIONS STATIQUES */ /*---------------------------------------------------------------------------*/ #include <arcane/utils/Real3x3.h> #define INST_MESH_VAR_SYNC_LIST_ADD(__DataType__) \ template void MeshVariableSynchronizerList::add(CellMaterialVariableScalarRef<__DataType__> var_menv) INST_MESH_VAR_SYNC_LIST_ADD(Integer); INST_MESH_VAR_SYNC_LIST_ADD(Real); INST_MESH_VAR_SYNC_LIST_ADD(Real3); INST_MESH_VAR_SYNC_LIST_ADD(Real3x3);
c++
code
4,290
985
//===- SampleProfWriter.cpp - Write LLVM sample profile data --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the class that writes LLVM sample profiles. It // supports two file formats: text and binary. The textual representation // is useful for debugging and testing purposes. The binary representation // is more compact, resulting in smaller file sizes. However, they can // both be used interchangeably. // // See lib/ProfileData/SampleProfReader.cpp for documentation on each of the // supported formats. // //===----------------------------------------------------------------------===// #include "llvm/ProfileData/SampleProfWriter.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/ProfileData/ProfileCommon.h" #include "llvm/ProfileData/SampleProf.h" #include "llvm/Support/Compression.h" #include "llvm/Support/Endian.h" #include "llvm/Support/EndianStream.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/LEB128.h" #include "llvm/Support/MD5.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstdint> #include <memory> #include <set> #include <system_error> #include <utility> #include <vector> using namespace llvm; using namespace sampleprof; std::error_code SampleProfileWriter::writeFuncProfiles(const SampleProfileMap &ProfileMap) { std::vector<NameFunctionSamples> V; sortFuncProfiles(ProfileMap, V); for (const auto &I : V) { if (std::error_code EC = writeSample(*I.second)) return EC; } return sampleprof_error::success; } std::error_code SampleProfileWriter::write(const SampleProfileMap &ProfileMap) { if (std::error_code EC = writeHeader(ProfileMap)) return EC; if (std::error_code EC = writeFuncProfiles(ProfileMap)) return EC; return sampleprof_error::success; } /// Return the current position and prepare to use it as the start /// position of a section given the section type \p Type and its position /// \p LayoutIdx in SectionHdrLayout. uint64_t SampleProfileWriterExtBinaryBase::markSectionStart(SecType Type, uint32_t LayoutIdx) { uint64_t SectionStart = OutputStream->tell(); assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range"); const auto &Entry = SectionHdrLayout[LayoutIdx]; assert(Entry.Type == Type && "Unexpected section type"); // Use LocalBuf as a temporary output for writting data. if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress)) LocalBufStream.swap(OutputStream); return SectionStart; } std::error_code SampleProfileWriterExtBinaryBase::compressAndOutput() { if (!llvm::zlib::isAvailable()) return sampleprof_error::zlib_unavailable; std::string &UncompressedStrings = static_cast<raw_string_ostream *>(LocalBufStream.get())->str(); if (UncompressedStrings.size() == 0) return sampleprof_error::success; auto &OS = *OutputStream; SmallString<128> CompressedStrings; llvm::Error E = zlib::compress(UncompressedStrings, CompressedStrings, zlib::BestSizeCompression); if (E) return sampleprof_error::compress_failed; encodeULEB128(UncompressedStrings.size(), OS); encodeULEB128(CompressedStrings.size(), OS); OS << CompressedStrings.str(); UncompressedStrings.clear(); return sampleprof_error::success; } /// Add a new section into section header table given the section type /// \p Type, its position \p LayoutIdx in SectionHdrLayout and the /// location \p SectionStart where the section should be written to. std::error_code SampleProfileWriterExtBinaryBase::addNewSection( SecType Type, uint32_t LayoutIdx, uint64_t SectionStart) { assert(LayoutIdx < SectionHdrLayout.size() && "LayoutIdx out of range"); const auto &Entry = SectionHdrLayout[LayoutIdx]; assert(Entry.Type == Type && "Unexpected section type"); if (hasSecFlag(Entry, SecCommonFlags::SecFlagCompress)) { LocalBufStream.swap(OutputStream); if (std::error_code EC = compressAndOutput()) return EC; } SecHdrTable.push_back({Type, Entry.Flags, SectionStart - FileStart, OutputStream->tell() - SectionStart, LayoutIdx}); return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::write(const SampleProfileMap &ProfileMap) { if (std::error_code EC = writeHeader(ProfileMap)) return EC; std::string LocalBuf; LocalBufStream = std::make_unique<raw_string_ostream>(LocalBuf); if (std::error_code EC = writeSections(ProfileMap)) return EC; if (std::error_code EC = writeSecHdrTable()) return EC; return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::writeContextIdx( const SampleContext &Context) { if (Context.hasContext()) return writeCSNameIdx(Context); else return SampleProfileWriterBinary::writeNameIdx(Context.getName()); } std::error_code SampleProfileWriterExtBinaryBase::writeCSNameIdx(const SampleContext &Context) { const auto &Ret = CSNameTable.find(Context); if (Ret == CSNameTable.end()) return sampleprof_error::truncated_name_table; encodeULEB128(Ret->second, *OutputStream); return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::writeSample(const FunctionSamples &S) { uint64_t Offset = OutputStream->tell(); auto &Context = S.getContext(); FuncOffsetTable[Context] = Offset - SecLBRProfileStart; encodeULEB128(S.getHeadSamples(), *OutputStream); return writeBody(S); } std::error_code SampleProfileWriterExtBinaryBase::writeFuncOffsetTable() { auto &OS = *OutputStream; // Write out the table size. encodeULEB128(FuncOffsetTable.size(), OS); // Write out FuncOffsetTable. auto WriteItem = [&](const SampleContext &Context, uint64_t Offset) { if (std::error_code EC = writeContextIdx(Context)) return EC; encodeULEB128(Offset, OS); return (std::error_code)sampleprof_error::success; }; if (FunctionSamples::ProfileIsCS) { // Sort the contexts before writing them out. This is to help fast load all // context profiles for a function as well as their callee contexts which // can help profile-guided importing for ThinLTO. std::map<SampleContext, uint64_t> OrderedFuncOffsetTable( FuncOffsetTable.begin(), FuncOffsetTable.end()); for (const auto &Entry : OrderedFuncOffsetTable) { if (std::error_code EC = WriteItem(Entry.first, Entry.second)) return EC; } addSectionFlag(SecFuncOffsetTable, SecFuncOffsetFlags::SecFlagOrdered); } else { for (const auto &Entry : FuncOffsetTable) { if (std::error_code EC = WriteItem(Entry.first, Entry.second)) return EC; } } FuncOffsetTable.clear(); return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::writeFuncMetadata( const SampleProfileMap &Profiles) { if (!FunctionSamples::ProfileIsProbeBased && !FunctionSamples::ProfileIsCS) return sampleprof_error::success; auto &OS = *OutputStream; for (const auto &Entry : Profiles) { if (std::error_code EC = writeContextIdx(Entry.second.getContext())) return EC; if (FunctionSamples::ProfileIsProbeBased) encodeULEB128(Entry.second.getFunctionHash(), OS); if (FunctionSamples::ProfileIsCS) encodeULEB128(Entry.second.getContext().getAllAttributes(), OS); } return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::writeNameTable() { if (!UseMD5) return SampleProfileWriterBinary::writeNameTable(); auto &OS = *OutputStream; std::set<StringRef> V; stablizeNameTable(NameTable, V); // Write out the MD5 name table. We wrote unencoded MD5 so reader can // retrieve the name using the name index without having to read the // whole name table. encodeULEB128(NameTable.size(), OS); support::endian::Writer Writer(OS, support::little); for (auto N : V) Writer.write(MD5Hash(N)); return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::writeNameTableSection( const SampleProfileMap &ProfileMap) { for (const auto &I : ProfileMap) { assert(I.first == I.second.getContext() && "Inconsistent profile map"); addContext(I.second.getContext()); addNames(I.second); } // If NameTable contains ".__uniq." suffix, set SecFlagUniqSuffix flag // so compiler won't strip the suffix during profile matching after // seeing the flag in the profile. for (const auto &I : NameTable) { if (I.first.contains(FunctionSamples::UniqSuffix)) { addSectionFlag(SecNameTable, SecNameTableFlags::SecFlagUniqSuffix); break; } } if (auto EC = writeNameTable()) return EC; return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::writeCSNameTableSection() { // Sort the names to make CSNameTable deterministic. std::set<SampleContext> OrderedContexts; for (const auto &I : CSNameTable) OrderedContexts.insert(I.first); assert(OrderedContexts.size() == CSNameTable.size() && "Unmatched ordered and unordered contexts"); uint64_t I = 0; for (auto &Context : OrderedContexts) CSNameTable[Context] = I++; auto &OS = *OutputStream; encodeULEB128(OrderedContexts.size(), OS); support::endian::Writer Writer(OS, support::little); for (auto Context : OrderedContexts) { auto Frames = Context.getContextFrames(); encodeULEB128(Frames.size(), OS); for (auto &Callsite : Frames) { if (std::error_code EC = writeNameIdx(Callsite.FuncName)) return EC; encodeULEB128(Callsite.Location.LineOffset, OS); encodeULEB128(Callsite.Location.Discriminator, OS); } } return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::writeProfileSymbolListSection() { if (ProfSymList && ProfSymList->size() > 0) if (std::error_code EC = ProfSymList->write(*OutputStream)) return EC; return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinaryBase::writeOneSection( SecType Type, uint32_t LayoutIdx, const SampleProfileMap &ProfileMap) { // The setting of SecFlagCompress should happen before markSectionStart. if (Type == SecProfileSymbolList && ProfSymList && ProfSymList->toCompress()) setToCompressSection(SecProfileSymbolList); if (Type == SecFuncMetadata && FunctionSamples::ProfileIsProbeBased) addSectionFlag(SecFuncMetadata, SecFuncMetadataFlags::SecFlagIsProbeBased); if (Type == SecProfSummary && FunctionSamples::ProfileIsCS) addSectionFlag(SecProfSummary, SecProfSummaryFlags::SecFlagFullContext); if (Type == SecFuncMetadata && FunctionSamples::ProfileIsCS) addSectionFlag(SecFuncMetadata, SecFuncMetadataFlags::SecFlagHasAttribute); if (Type == SecProfSummary && FunctionSamples::ProfileIsFS) addSectionFlag(SecProfSummary, SecProfSummaryFlags::SecFlagFSDiscriminator); uint64_t SectionStart = markSectionStart(Type, LayoutIdx); switch (Type) { case SecProfSummary: computeSummary(ProfileMap); if (auto EC = writeSummary()) return EC; break; case SecNameTable: if (auto EC = writeNameTableSection(ProfileMap)) return EC; break; case SecCSNameTable: if (auto EC = writeCSNameTableSection()) return EC; break; case SecLBRProfile: SecLBRProfileStart = OutputStream->tell(); if (std::error_code EC = writeFuncProfiles(ProfileMap)) return EC; break; case SecFuncOffsetTable: if (auto EC = writeFuncOffsetTable()) return EC; break; case SecFuncMetadata: if (std::error_code EC = writeFuncMetadata(ProfileMap)) return EC; break; case SecProfileSymbolList: if (auto EC = writeProfileSymbolListSection()) return EC; break; default: if (auto EC = writeCustomSection(Type)) return EC; break; } if (std::error_code EC = addNewSection(Type, LayoutIdx, SectionStart)) return EC; return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinary::writeDefaultLayout( const SampleProfileMap &ProfileMap) { // The const indices passed to writeOneSection below are specifying the // positions of the sections in SectionHdrLayout. Look at // initSectionHdrLayout to find out where each section is located in // SectionHdrLayout. if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap)) return EC; if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap)) return EC; if (auto EC = writeOneSection(SecCSNameTable, 2, ProfileMap)) return EC; if (auto EC = writeOneSection(SecLBRProfile, 4, ProfileMap)) return EC; if (auto EC = writeOneSection(SecProfileSymbolList, 5, ProfileMap)) return EC; if (auto EC = writeOneSection(SecFuncOffsetTable, 3, ProfileMap)) return EC; if (auto EC = writeOneSection(SecFuncMetadata, 6, ProfileMap)) return EC; return sampleprof_error::success; } static void splitProfileMapToTwo(const SampleProfileMap &ProfileMap, SampleProfileMap &ContextProfileMap, SampleProfileMap &NoContextProfileMap) { for (const auto &I : ProfileMap) { if (I.second.getCallsiteSamples().size()) ContextProfileMap.insert({I.first, I.second}); else NoContextProfileMap.insert({I.first, I.second}); } } std::error_code SampleProfileWriterExtBinary::writeCtxSplitLayout( const SampleProfileMap &ProfileMap) { SampleProfileMap ContextProfileMap, NoContextProfileMap; splitProfileMapToTwo(ProfileMap, ContextProfileMap, NoContextProfileMap); if (auto EC = writeOneSection(SecProfSummary, 0, ProfileMap)) return EC; if (auto EC = writeOneSection(SecNameTable, 1, ProfileMap)) return EC; if (auto EC = writeOneSection(SecLBRProfile, 3, ContextProfileMap)) return EC; if (auto EC = writeOneSection(SecFuncOffsetTable, 2, ContextProfileMap)) return EC; // Mark the section to have no context. Note section flag needs to be set // before writing the section. addSectionFlag(5, SecCommonFlags::SecFlagFlat); if (auto EC = writeOneSection(SecLBRProfile, 5, NoContextProfileMap)) return EC; // Mark the section to have no context. Note section flag needs to be set // before writing the section. addSectionFlag(4, SecCommonFlags::SecFlagFlat); if (auto EC = writeOneSection(SecFuncOffsetTable, 4, NoContextProfileMap)) return EC; if (auto EC = writeOneSection(SecProfileSymbolList, 6, ProfileMap)) return EC; if (auto EC = writeOneSection(SecFuncMetadata, 7, ProfileMap)) return EC; return sampleprof_error::success; } std::error_code SampleProfileWriterExtBinary::writeSections( const SampleProfileMap &ProfileMap) { std::error_code EC; if (SecLayout == DefaultLayout) EC = writeDefaultLayout(ProfileMap); else if (SecLayout == CtxSplitLayout) EC = writeCtxSplitLayout(ProfileMap); else llvm_unreachable("Unsupported layout"); return EC; } std::error_code SampleProfileWriterCompactBinary::write(const SampleProfileMap &ProfileMap) { if (std::error_code EC = SampleProfileWriter::write(ProfileMap)) return EC; if (std::error_code EC = writeFuncOffsetTable()) return EC; return sampleprof_error::success; } /// Write samples to a text file. /// /// Note: it may be tempting to implement this in terms of /// FunctionSamples::print(). Please don't. The dump functionality is intended /// for debugging and has no specified form. /// /// The format used here is more structured and deliberate because /// it needs to be parsed by the SampleProfileReaderText class. std::error_code SampleProfileWriterText::writeSample(const FunctionSamples &S) { auto &OS = *OutputStream; if (FunctionSamples::ProfileIsCS) OS << "[" << S.getContext().toString() << "]:" << S.getTotalSamples(); else OS << S.getName() << ":" << S.getTotalSamples(); if (Indent == 0) OS << ":" << S.getHeadSamples(); OS << "\n"; SampleSorter<LineLocation, SampleRecord> SortedSamples(S.getBodySamples()); for (const auto &I : SortedSamples.get()) { LineLocation Loc = I->first; const SampleRecord &Sample = I->second; OS.indent(Indent + 1); if (Loc.Discriminator == 0) OS << Loc.LineOffset << ": "; else OS << Loc.LineOffset << "." << Loc.Discriminator << ": "; OS << Sample.getSamples(); for (const auto &J : Sample.getSortedCallTargets()) OS << " " << J.first << ":" << J.second; OS << "\n"; } SampleSorter<LineLocation, FunctionSamplesMap> SortedCallsiteSamples( S.getCallsiteSamples()); Indent += 1; for (const auto &I : SortedCallsiteSamples.get()) for (const auto &FS : I->second) { LineLocation Loc = I->first; const FunctionSamples &CalleeSamples = FS.second; OS.indent(Indent); if (Loc.Discriminator == 0) OS << Loc.LineOffset << ": "; else OS << Loc.LineOffset << "." << Loc.Discriminator << ": "; if (std::error_code EC = writeSample(CalleeSamples)) return EC; } Indent -= 1; if (Indent == 0) { if (FunctionSamples::ProfileIsProbeBased) { OS.indent(Indent + 1); OS << "!CFGChecksum: " << S.getFunctionHash() << "\n"; } if (FunctionSamples::ProfileIsCS) { OS.indent(Indent + 1); OS << "!Attributes: " << S.getContext().getAllAttributes() << "\n"; } } return sampleprof_error::success; } std::error_code SampleProfileWriterBinary::writeContextIdx(const SampleContext &Context) { assert(!Context.hasContext() && "cs profile is not supported"); return writeNameIdx(Context.getName()); } std::error_code SampleProfileWriterBinary::writeNameIdx(StringRef FName) { auto &NTable = getNameTable(); const auto &Ret = NTable.find(FName); if (Ret == NTable.end()) return sampleprof_error::truncated_name_table; encodeULEB128(Ret->second, *OutputStream); return sampleprof_error::success; } void SampleProfileWriterBinary::addName(StringRef FName) { auto &NTable = getNameTable(); NTable.insert(std::make_pair(FName, 0)); } void SampleProfileWriterBinary::addContext(const SampleContext &Context) { addName(Context.getName()); } void SampleProfileWriterBinary::addNames(const FunctionSamples &S) { // Add all the names in indirect call targets. for (const auto &I : S.getBodySamples()) { const SampleRecord &Sample = I.second; for (const auto &J : Sample.getCallTargets()) addName(J.first()); } // Recursively add all the names for inlined callsites. for (const auto &J : S.getCallsiteSamples()) for (const auto &FS : J.second) { const FunctionSamples &CalleeSamples = FS.second; addName(CalleeSamples.getName()); addNames(CalleeSamples); } } void SampleProfileWriterExtBinaryBase::addContext( const SampleContext &Context) { if (Context.hasContext()) { for (auto &Callsite : Context.getContextFrames()) SampleProfileWriterBinary::addName(Callsite.FuncName); CSNameTable.insert(std::make_pair(Context, 0)); } else { SampleProfileWriterBinary::addName(Context.getName()); } } void SampleProfileWriterBinary::stablizeNameTable( MapVector<StringRef, uint32_t> &NameTable, std::set<StringRef> &V) { // Sort the names to make NameTable deterministic. for (const auto &I : NameTable) V.insert(I.first); int i = 0; for (const StringRef &N : V) NameTable[N] = i++; } std::error_code SampleProfileWriterBinary::writeNameTable() { auto &OS = *OutputStream; std::set<StringRef> V; stablizeNameTable(NameTable, V); // Write out the name table. encodeULEB128(NameTable.size(), OS); for (auto N : V) { OS << N; encodeULEB128(0, OS); } retu
c++
code
20,000
4,049
// Copyright (c) 2012 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 "ash/wm/workspace/workspace_window_resizer.h" #include "ash/ash_constants.h" #include "ash/ash_switches.h" #include "ash/display/display_manager.h" #include "ash/root_window_controller.h" #include "ash/screen_util.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/test/ash_test_base.h" #include "ash/wm/window_state.h" #include "ash/wm/window_util.h" #include "ash/wm/wm_event.h" #include "ash/wm/workspace/phantom_window_controller.h" #include "ash/wm/workspace_controller.h" #include "base/command_line.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/test/event_generator.h" #include "ui/aura/test/test_window_delegate.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/base/hit_test.h" #include "ui/events/gestures/gesture_configuration.h" #include "ui/gfx/insets.h" #include "ui/gfx/screen.h" #include "ui/views/widget/widget.h" namespace ash { namespace { const int kRootHeight = 600; // A simple window delegate that returns the specified min size. class TestWindowDelegate : public aura::test::TestWindowDelegate { public: TestWindowDelegate() { } virtual ~TestWindowDelegate() {} void set_min_size(const gfx::Size& size) { min_size_ = size; } void set_max_size(const gfx::Size& size) { max_size_ = size; } private: // Overridden from aura::Test::TestWindowDelegate: virtual gfx::Size GetMinimumSize() const OVERRIDE { return min_size_; } virtual gfx::Size GetMaximumSize() const OVERRIDE { return max_size_; } gfx::Size min_size_; gfx::Size max_size_; DISALLOW_COPY_AND_ASSIGN(TestWindowDelegate); }; } // namespace class WorkspaceWindowResizerTest : public test::AshTestBase { public: WorkspaceWindowResizerTest() : workspace_resizer_(NULL) {} virtual ~WorkspaceWindowResizerTest() {} virtual void SetUp() OVERRIDE { AshTestBase::SetUp(); UpdateDisplay(base::StringPrintf("800x%d", kRootHeight)); // Ignore the touch slop region. ui::GestureConfiguration::set_max_touch_move_in_pixels_for_click(0); aura::Window* root = Shell::GetPrimaryRootWindow(); gfx::Rect root_bounds(root->bounds()); #if defined(OS_WIN) // RootWindow and Display can't resize on Windows Ash. // http://crbug.com/165962 EXPECT_EQ(kRootHeight, root_bounds.height()); #endif EXPECT_EQ(800, root_bounds.width()); Shell::GetInstance()->SetDisplayWorkAreaInsets(root, gfx::Insets()); window_.reset(new aura::Window(&delegate_)); window_->SetType(ui::wm::WINDOW_TYPE_NORMAL); window_->Init(aura::WINDOW_LAYER_NOT_DRAWN); ParentWindowInPrimaryRootWindow(window_.get()); window_->set_id(1); window2_.reset(new aura::Window(&delegate2_)); window2_->SetType(ui::wm::WINDOW_TYPE_NORMAL); window2_->Init(aura::WINDOW_LAYER_NOT_DRAWN); ParentWindowInPrimaryRootWindow(window2_.get()); window2_->set_id(2); window3_.reset(new aura::Window(&delegate3_)); window3_->SetType(ui::wm::WINDOW_TYPE_NORMAL); window3_->Init(aura::WINDOW_LAYER_NOT_DRAWN); ParentWindowInPrimaryRootWindow(window3_.get()); window3_->set_id(3); window4_.reset(new aura::Window(&delegate4_)); window4_->SetType(ui::wm::WINDOW_TYPE_NORMAL); window4_->Init(aura::WINDOW_LAYER_NOT_DRAWN); ParentWindowInPrimaryRootWindow(window4_.get()); window4_->set_id(4); } virtual void TearDown() OVERRIDE { window_.reset(); window2_.reset(); window3_.reset(); window4_.reset(); touch_resize_window_.reset(); AshTestBase::TearDown(); } // Returns a string identifying the z-order of each of the known child windows // of |parent|. The returned string constains the id of the known windows and // is ordered from topmost to bottomost windows. std::string WindowOrderAsString(aura::Window* parent) const { std::string result; const aura::Window::Windows& windows = parent->children(); for (aura::Window::Windows::const_reverse_iterator i = windows.rbegin(); i != windows.rend(); ++i) { if (*i == window_ || *i == window2_ || *i == window3_) { if (!result.empty()) result += " "; result += base::IntToString((*i)->id()); } } return result; } protected: WindowResizer* CreateResizerForTest( aura::Window* window, const gfx::Point& point_in_parent, int window_component) { WindowResizer* resizer = CreateWindowResizer( window, point_in_parent, window_component, aura::client::WINDOW_MOVE_SOURCE_MOUSE).release(); workspace_resizer_ = WorkspaceWindowResizer::instance_; return resizer; } WorkspaceWindowResizer* CreateWorkspaceResizerForTest( aura::Window* window, const gfx::Point& point_in_parent, int window_component, aura::client::WindowMoveSource source, const std::vector<aura::Window*>& attached_windows) { wm::WindowState* window_state = wm::GetWindowState(window); window_state->CreateDragDetails( window, point_in_parent, window_component, source); return WorkspaceWindowResizer::Create(window_state, attached_windows); } PhantomWindowController* snap_phantom_window_controller() const { return workspace_resizer_->snap_phantom_window_controller_.get(); } gfx::Point CalculateDragPoint(const WindowResizer& resizer, int delta_x, int delta_y) const { gfx::Point location = resizer.GetInitialLocation(); location.set_x(location.x() + delta_x); location.set_y(location.y() + delta_y); return location; } std::vector<aura::Window*> empty_windows() const { return std::vector<aura::Window*>(); } ShelfLayoutManager* shelf_layout_manager() { return Shell::GetPrimaryRootWindowController()->GetShelfLayoutManager(); } void InitTouchResizeWindow(const gfx::Rect& bounds, int window_component) { touch_resize_delegate_.set_window_component(window_component); touch_resize_window_.reset( CreateTestWindowInShellWithDelegate(&touch_resize_delegate_, 0, bounds)); } TestWindowDelegate delegate_; TestWindowDelegate delegate2_; TestWindowDelegate delegate3_; TestWindowDelegate delegate4_; scoped_ptr<aura::Window> window_; scoped_ptr<aura::Window> window2_; scoped_ptr<aura::Window> window3_; scoped_ptr<aura::Window> window4_; TestWindowDelegate touch_resize_delegate_; scoped_ptr<aura::Window> touch_resize_window_; WorkspaceWindowResizer* workspace_resizer_; private: DISALLOW_COPY_AND_ASSIGN(WorkspaceWindowResizerTest); }; // Assertions around attached window resize dragging from the right with 2 // windows. TEST_F(WorkspaceWindowResizerTest, AttachedResize_RIGHT_2) { window_->SetBounds(gfx::Rect(0, 300, 400, 300)); window2_->SetBounds(gfx::Rect(400, 200, 100, 200)); std::vector<aura::Window*> windows; windows.push_back(window2_.get()); scoped_ptr<WorkspaceWindowResizer> resizer(CreateWorkspaceResizerForTest( window_.get(), gfx::Point(), HTRIGHT, aura::client::WINDOW_MOVE_SOURCE_MOUSE, windows)); ASSERT_TRUE(resizer.get()); // Move it 100 to the right, which should expand w1 and push w2. resizer->Drag(CalculateDragPoint(*resizer, 100, 10), 0); EXPECT_EQ("0,300 500x300", window_->bounds().ToString()); EXPECT_EQ("500,200 100x200", window2_->bounds().ToString()); // Push off the screen, w2 should be resized to its min. delegate2_.set_min_size(gfx::Size(20, 20)); resizer->Drag(CalculateDragPoint(*resizer, 800, 20), 0); EXPECT_EQ("0,300 780x300", window_->bounds().ToString()); EXPECT_EQ("780,200 20x200", window2_->bounds().ToString()); // Move back to 100 and verify w2 gets its original size. resizer->Drag(CalculateDragPoint(*resizer, 100, 10), 0); EXPECT_EQ("0,300 500x300", window_->bounds().ToString()); EXPECT_EQ("500,200 100x200", window2_->bounds().ToString()); // Revert and make sure everything moves back. resizer->Drag(CalculateDragPoint(*resizer, 800, 20), 0); resizer->RevertDrag(); EXPECT_EQ("0,300 400x300", window_->bounds().ToString()); EXPECT_EQ("400,200 100x200", window2_->bounds().ToString()); } // Assertions around collapsing and expanding. TEST_F(WorkspaceWindowResizerTest, AttachedResize_RIGHT_Compress) { window_->SetBounds(gfx::Rect( 0, 300, 400, 300)); window2_->SetBounds(gfx::Rect(400, 200, 100, 200)); std::vector<aura::Window*> windows; windows.push_back(window2_.get()); scoped_ptr<WorkspaceWindowResizer> resizer(CreateWorkspaceResizerForTest( window_.get(), gfx::Point(), HTRIGHT, aura::client::WINDOW_MOVE_SOURCE_MOUSE, windows)); ASSERT_TRUE(resizer.get()); // Move it 100 to the left, which should expand w2 and collapse w1. resizer->Drag(CalculateDragPoint(*resizer, -100, 10), 0); EXPECT_EQ("0,300 300x300", window_->bounds().ToString()); EXPECT_EQ("300,200 200x200", window2_->bounds().ToString()); // Collapse all the way to w1's min. delegate_.set_min_size(gfx::Size(20, 20)); resizer->Drag(CalculateDragPoint(*resizer, -800, 20), 0); EXPECT_EQ("0,300 20x300", window_->bounds().ToString()); EXPECT_EQ("20,200 480x200", window2_->bounds().ToString()); // Move 100 to the left. resizer->Drag(CalculateDragPoint(*resizer, 100, 10), 0); EXPECT_EQ("0,300 500x300", window_->bounds().ToString()); EXPECT_EQ("500,200 100x200", window2_->bounds().ToString()); // Back to -100. resizer->Drag(CalculateDragPoint(*resizer, -100, 20), 0); EXPECT_EQ("0,300 300x300", window_->bounds().ToString()); EXPECT_EQ("300,200 200x200", window2_->bounds().ToString()); } // Assertions around attached window resize dragging from the right with 3 // windows. TEST_F(WorkspaceWindowResizerTest, AttachedResize_RIGHT_3) { window_->SetBounds(gfx::Rect( 100, 300, 200, 300)); window2_->SetBounds(gfx::Rect(300, 300, 150, 200)); window3_->SetBounds(gfx::Rect(450, 300, 100, 200)); delegate2_.set_min_size(gfx::Size(52, 50)); delegate3_.set_min_size(gfx::Size(38, 50)); std::vector<aura::Window*> windows; windows.push_back(window2_.get()); windows.push_back(window3_.get()); scoped_ptr<WorkspaceWindowResizer> resizer(CreateWorkspaceResizerForTest( window_.get(), gfx::Point(), HTRIGHT, aura::client::WINDOW_MOVE_SOURCE_MOUSE, windows)); ASSERT_TRUE(resizer.get()); // Move it 100 to the right, which should expand w1 and push w2 and w3. resizer->Drag(CalculateDragPoint(*resizer, 100, -10), 0); EXPECT_EQ("100,300 300x300", window_->bounds().ToString()); EXPECT_EQ("400,300 150x200", window2_->bounds().ToString()); EXPECT_EQ("550,300 100x200", window3_->bounds().ToString()); // Move it 300, things should compress. resizer->Drag(CalculateDragPoint(*resizer, 300, -10), 0); EXPECT_EQ("100,300 500x300", window_->bounds().ToString()); EXPECT_EQ("600,300 120x200", window2_->bounds().ToString()); EXPECT_EQ("720,300 80x200", window3_->bounds().ToString()); // Move it so much the last two end up at their min. resizer->Drag(CalculateDragPoint(*resizer, 800, 50), 0); EXPECT_EQ("100,300 610x300", window_->bounds().ToString()); EXPECT_EQ("710,300 52x200", window2_->bounds().ToString()); EXPECT_EQ("762,300 38x200", window3_->bounds().ToString()); // Revert and make sure everything moves back. resizer->RevertDrag(); EXPECT_EQ("100,300 200x300", window_->bounds().ToString()); EXPECT_EQ("300,300 150x200", window2_->bounds().ToString()); EXPECT_EQ("450,300 100x200", window3_->bounds().ToString()); } // Assertions around attached window resizing (collapsing and expanding) with // 3 windows. TEST_F(WorkspaceWindowResizerTest, AttachedResize_RIGHT_3_Compress) { window_->SetBounds(gfx::Rect( 100, 300, 200, 300)); window2_->SetBounds(gfx::Rect(300, 300, 200, 200)); window3_->SetBounds(gfx::Rect(450, 300, 100, 200)); delegate2_.set_min_size(gfx::Size(52, 50)); delegate3_.set_min_size(gfx::Size(38, 50)); std::vector<aura::Window*> windows; windows.push_back(window2_.get()); windows.push_back(window3_.get()); scoped_ptr<WorkspaceWindowResizer> resizer(CreateWorkspaceResizerForTest( window_.get(), gfx::Point(), HTRIGHT, aura::client::WINDOW_MOVE_SOURCE_MOUSE, windows)); ASSERT_TRUE(resizer.get()); // Move it -100 to the right, which should collapse w1 and expand w2 and w3. resizer->Drag(CalculateDragPoint(*resizer, -100, -10), 0); EXPECT_EQ("100,300 100x300", window_->bounds().ToString()); EXPECT_EQ("200,300 266x200", window2_->bounds().ToString()); EXPECT_EQ("466,300 134x200", window3_->bounds().ToString()); // Move it 100 to the right. resizer->Drag(CalculateDragPoint(*resizer, 100, -10), 0); EXPECT_EQ("100,300 300x300", window_->bounds().ToString()); EXPECT_EQ("400,300 200x200", window2_->bounds().ToString()); EXPECT_EQ("600,300 100x200", window3_->bounds().ToString()); // 100 to the left again. resizer->Drag(CalculateDragPoint(*resizer, -100, -10), 0); EXPECT_EQ("100,300 100x300", window_->bounds().ToString()); EXPECT_EQ("200,300 266x200", window2_->bounds().ToString()); EXPECT_EQ("466,300 134x200", window3_->bounds().ToString()); } // Assertions around collapsing and expanding from the bottom. TEST_F(WorkspaceWindowResizerTest, AttachedResize_BOTTOM_Compress) { window_->SetBounds(gfx::Rect( 0, 100, 400, 300)); window2_->SetBounds(gfx::Rect(400, 400, 100, 200)); std::vector<aura::Window*> windows; windows.push_back(window2_.get()); scoped_ptr<WorkspaceWindowResizer> resizer(CreateWorkspaceResizerForTest( window_.get(), gfx::Point(), HTBOTTOM, aura::client::WINDOW_MOVE_SOURCE_MOUSE, windows)); ASSERT_TRUE(resizer.get()); // Move it up 100, which should expand w2 and collapse w1. resizer->Drag(CalculateDragPoint(*resizer, 10, -100), 0); EXPECT_EQ("0,100 400x200", window_->bounds().ToString()); EXPECT_EQ("400,300 100x300", window2_->bounds().ToString()); // Collapse all the way to w1's min. delegate_.set_min_size(gfx::Size(20, 20)); resizer->Drag(CalculateDragPoint(*resizer, 20, -800), 0); EXPECT_EQ("0,100 400x20", window_->bounds().ToString()); EXPECT_EQ("400,120 100x480", window2_->bounds().ToString()); // Move 100 down. resizer->Drag(CalculateDragPoint(*resizer, 10, 100), 0); EXPECT_EQ("0,100 400x400", window_->bounds().ToString()); EXPECT_EQ("400,500 100x100", window2_->bounds().ToString()); // Back to -100. resizer->Drag(CalculateDragPoint(*resizer, 20, -100), 0); EXPECT_EQ("0,100 400x200", window_->bounds().ToString()); EXPECT_EQ("400,300 100x300", window2_->bounds().ToString()); } // Assertions around attached window resize dragging from the bottom with 2 // windows. TEST_F(WorkspaceWindowResizerTest, AttachedResize_BOTTOM_2) { window_->SetBounds(gfx::Rect( 0, 50, 400, 200)); window2_->SetBounds(gfx::Rect(0, 250, 200, 100)); std::vector<aura::Window*> windows; windows.push_back(window2_.get()); scoped_ptr<WorkspaceWindowResizer> resizer(CreateWorkspaceResizerForTest( window_.get(), gfx::Point(), HTBOTTOM, aura::client::WINDOW_MOVE_SOURCE_MOUSE, windows)); ASSERT_TRUE(resizer.get()); // Move it 100 to the bottom, which should expand w1 and push w2. resizer->Drag(CalculateDragPoint(*resizer, 10, 100), 0); EXPECT_EQ("0,50 400x300", window_->bounds().ToString()); EXPECT_EQ("0,350 200x100", window2_->bounds().ToString()); // Push off the screen, w2 should be resized to its min. delegate2_.set_min_size(gfx::Size(20, 20)); resizer->Drag(CalculateDragPoint(*resizer, 50, 820), 0); EXPECT_EQ("0,50 400x530", window_->bounds().ToString()); EXPECT_EQ("0,580 200x20", window2_->bounds().ToString()); // Move back to 100 and verify w2 gets its original size. resizer->Drag(CalculateDragPoint(*resizer, 10, 100), 0); EXPECT_EQ("0,50 400x300", window_->bounds().ToString()); EXPECT_EQ("0,350 200x100", window2_->bounds().ToString()); // Revert and make sure everything moves back. resizer->Drag(CalculateDragPoint(*resizer, 800, 20), 0); resizer->RevertDrag(); EXPECT_EQ("0,50 400x200", window_->bounds().ToString()); EXPECT_EQ("0,250 200x100", window2_->bounds().ToString()); } #if defined(OS_WIN) // RootWindow and Display can't resize on Windows Ash. http://crbug.com/165962 #define MAYBE_AttachedResize_BOTTOM_3 DISABLED_AttachedResize_BOTTOM_3 #else #define MAYBE_AttachedResize_BOTTOM_3 AttachedResize_BOTTOM_3 #endif // Assertions around attached window resize dragging from the bottom with 3 // windows. TEST_F(WorkspaceWindowResizerTest, MAYBE_AttachedResize_BOTTOM_3) { UpdateDisplay("600x800"); aura::Window* root = Shell::GetPrimaryRootWindow(); Shell::GetInstance()->SetDisplayWorkAreaInsets(root, gfx::Insets()); window_->SetBounds(gfx::Rect( 300, 100, 300, 200)); window2_->SetBounds(gfx::Rect(300, 300, 200, 150)); window3_->SetBounds(gfx::Rect(300, 450, 200, 100)); delegate2_.set_min_size(gfx::Size(50, 52)); delegate3_.set_min_size(gfx::Size(50, 38)); std::vector<aura::Window*> windows; windows.push_back(window2_.get()); windows.push_back(window3_.get()); scoped_ptr<WorkspaceWindowResizer> resizer(CreateWorkspaceResizerForTest( window_.get(), gfx::Point(), HTBOTTOM, aura::client::WINDOW_MOVE_SOURCE_MOUSE, windows)); ASSERT_TRUE(resizer.get()); // Move it 100 down, which should expand w1 and push w2 and w3. resizer->Drag(CalculateDragPoint(*resizer, -10, 100), 0); EXPECT_EQ("300,100 300x300", window_->bounds().ToString()); EXPECT_EQ("300,400 200x150", window2_->bounds().ToString()); EXPECT_EQ("300,550 200x100", window3_->bounds().ToString()); // Move it 296 things should compress. resizer->Drag(CalculateDragPoint(*resizer, -10, 296), 0); EXPECT_EQ("300,100 300x496", window_->bounds().ToString()); EXPECT_EQ("300,596 200x123", window2_->bounds().ToString()); EXPECT_EQ("300,719 200x81", window3_->bounds().ToString()); // Move it so much everything ends up at its min. resizer->Drag(CalculateDragPoint(*resizer, 50, 798), 0); EXPECT_EQ("300,100 300x610", window_->bounds().ToString()); EXPECT_EQ("300,710 200x52", window2_->bounds().ToString()); EXPECT_EQ("300,762 200x38", window3_->bounds().ToString()); // Revert and make sure everything moves back. resizer->RevertDrag(); EXPECT_EQ("300,100 300x200", window_->bounds().ToString()); EXPECT_EQ("300,300 200x150", window2_->bounds().ToString()); EXPECT_EQ("300,450 200x100", window3_->bounds().ToString()); } // Assertions around attached window resizing (collapsing and expanding) with // 3 windows. TEST_F(WorkspaceWindowResizerTest, AttachedResize_BOTTOM_3_Compress) { window_->SetBounds(gfx::Rect( 0, 0, 200, 200)); window2_->SetBounds(gfx::Rect(10, 200, 200, 200)); window3_->SetBounds(gfx::Rect(20, 400, 100, 100)); delegate2_.set_min_size(gfx::Size(52, 50)); delegate3_.set_min_size(gfx::Size(38, 50)); std::vector<aura::Window*> windows; windows.push_back(window2_.get()); windows.push_back(window3_.get()); scoped_ptr<WorkspaceWindowResizer> resizer(CreateWorkspaceResizerForTest( window_.get(), gfx::Point(), HTBOTTOM, aura::client::WINDOW_MOVE_SOURCE_MOUSE, windows)); ASSERT_TRUE(resizer.get()); // Move it 100 up, which should collapse w1 and expand w2 and w3. resizer->Drag(CalculateDragPoint(*resizer, -10, -100), 0); EXPECT_EQ("0,0 200x100", window_->bounds().ToString()); EXPECT_EQ("10,100 200x266", window2_->bounds().ToString()); EXPECT_EQ("20,366 100x134", window3_->bounds().ToString()); // Move it 100 down. resizer->Drag(CalculateDragPoint(*resizer, 10, 100), 0); EXPECT_EQ("0,0 200x300", window_->bounds().ToString()); EXPECT_EQ("10,300
c++
code
19,999
4,894
// Copyright 2013 Room77 Inc. All Rights Reserved. // Author: [email protected] (Pramod Gupta) #include "meta/log/offline/reader/raw_user_log_reader.h" #include "meta/log/offline/reader/log_element_reader.h" #include "test/cc/test_main.h" #include "util/time/localtime.h" namespace logging { namespace reader { namespace test { namespace { struct CounterLogElementReader : public LogElementMutableReaderInterface { // Simply return 0 every time it is called to stop further processing of the file. virtual int ReadMutable(const string& element) { ++count; return 0; } int count = 0; }; } // namespace // Test class for RawUserLogReader. class RawUserLogReaderTest : public ::testing::Test { public: static void SetUpTestCase() {} static void TearDownTestCase() {} protected: // Sets up the test fixture. virtual void SetUp() {} // Tears down the test fixture. virtual void TearDown() {} CounterLogElementReader element_reader_; }; TEST_F(RawUserLogReaderTest, Initialization) { LocalDate today = LocalDate::Today(); LocalDate yesterday = today - 1; { RawUserLogReader reader(1); EXPECT_EQ("/home/share/data/logs/raw", reader.dir_name()); EXPECT_EQ(yesterday, reader.begin_date()); EXPECT_EQ(today, reader.end_date()); } { RawUserLogReader reader(yesterday, today); EXPECT_EQ("/home/share/data/logs/raw", reader.dir_name()); EXPECT_EQ(yesterday, reader.begin_date()); EXPECT_EQ(today, reader.end_date()); } { RawUserLogReader reader(yesterday.PrintFormatted("%Y%m%d"), today.PrintFormatted("%Y%m%d")); EXPECT_EQ("/home/share/data/logs/raw", reader.dir_name()); EXPECT_EQ(yesterday, reader.begin_date()); EXPECT_EQ(today, reader.end_date()); } } TEST_F(RawUserLogReaderTest, Sanity) { RawUserLogReader reader(1); // We returned false for each file we parsed. Thus, the returned value should be 0. EXPECT_EQ(0, reader.ReadLogs(element_reader_)); EXPECT_EQ(24, element_reader_.count); } } // namespace test } // namespace reader } // namespace logging
c++
code
2,071
417
///////////////////////////////////////////////////////////////////////////// // Name: src/msw/window.cpp // Purpose: wxWindowMSW // Author: Julian Smart // Modified by: VZ on 13.05.99: no more Default(), MSWOnXXX() reorganisation // Created: 04/01/98 // RCS-ID: $Id: window.cpp 63391 2010-02-05 00:26:44Z RD $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // =========================================================================== // declarations // =========================================================================== // --------------------------------------------------------------------------- // headers // --------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/window.h" #ifndef WX_PRECOMP #include "wx/msw/wrapwin.h" #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly" #include "wx/msw/missing.h" #include "wx/accel.h" #include "wx/menu.h" #include "wx/dc.h" #include "wx/dcclient.h" #include "wx/dcmemory.h" #include "wx/utils.h" #include "wx/app.h" #include "wx/layout.h" #include "wx/dialog.h" #include "wx/frame.h" #include "wx/listbox.h" #include "wx/button.h" #include "wx/msgdlg.h" #include "wx/settings.h" #include "wx/statbox.h" #include "wx/sizer.h" #include "wx/intl.h" #include "wx/log.h" #include "wx/textctrl.h" #include "wx/menuitem.h" #include "wx/module.h" #endif #if wxUSE_OWNER_DRAWN && !defined(__WXUNIVERSAL__) #include "wx/ownerdrw.h" #endif #include "wx/evtloop.h" #include "wx/power.h" #include "wx/sysopt.h" #if wxUSE_DRAG_AND_DROP #include "wx/dnd.h" #endif #if wxUSE_ACCESSIBILITY #include "wx/access.h" #include <ole2.h> #include <oleacc.h> #ifndef WM_GETOBJECT #define WM_GETOBJECT 0x003D #endif #ifndef OBJID_CLIENT #define OBJID_CLIENT 0xFFFFFFFC #endif #endif #include "wx/msw/private.h" #if wxUSE_TOOLTIPS #include "wx/tooltip.h" #endif #if wxUSE_CARET #include "wx/caret.h" #endif // wxUSE_CARET #if wxUSE_SPINCTRL #include "wx/spinctrl.h" #endif // wxUSE_SPINCTRL #include "wx/notebook.h" #include "wx/listctrl.h" #include "wx/dynlib.h" #include <string.h> #if (!defined(__GNUWIN32_OLD__) && !defined(__WXMICROWIN__) /* && !defined(__WXWINCE__) */ ) || defined(__CYGWIN10__) #include <shellapi.h> #include <mmsystem.h> #endif #ifdef __WIN32__ #include <windowsx.h> #endif #if !defined __WXWINCE__ && !defined NEED_PBT_H #include <pbt.h> #endif #if defined(__WXWINCE__) #include "wx/msw/wince/missing.h" #ifdef __POCKETPC__ #include <windows.h> #include <shellapi.h> #include <ole2.h> #include <aygshell.h> #endif #endif #if wxUSE_UXTHEME #include "wx/msw/uxtheme.h" #define EP_EDITTEXT 1 #define ETS_NORMAL 1 #define ETS_HOT 2 #define ETS_SELECTED 3 #define ETS_DISABLED 4 #define ETS_FOCUSED 5 #define ETS_READONLY 6 #define ETS_ASSIST 7 #endif #if defined(TME_LEAVE) && defined(WM_MOUSELEAVE) && wxUSE_DYNLIB_CLASS #define HAVE_TRACKMOUSEEVENT #endif // everything needed for TrackMouseEvent() // if this is set to 1, we use deferred window sizing to reduce flicker when // resizing complicated window hierarchies, but this can in theory result in // different behaviour than the old code so we keep the possibility to use it // by setting this to 0 (in the future this should be removed completely) #ifdef __WXWINCE__ #define USE_DEFERRED_SIZING 0 #else #define USE_DEFERRED_SIZING 1 #endif // set this to 1 to filter out duplicate mouse events, e.g. mouse move events // when mouse position didnd't change #ifdef __WXWINCE__ #define wxUSE_MOUSEEVENT_HACK 0 #else #define wxUSE_MOUSEEVENT_HACK 1 #endif // --------------------------------------------------------------------------- // global variables // --------------------------------------------------------------------------- #if wxUSE_MENUS_NATIVE wxMenu *wxCurrentPopupMenu = NULL; #endif // wxUSE_MENUS_NATIVE #ifdef __WXWINCE__ extern wxChar *wxCanvasClassName; #else extern const wxChar *wxCanvasClassName; #endif // true if we had already created the std colour map, used by // wxGetStdColourMap() and wxWindow::OnSysColourChanged() (FIXME-MT) static bool gs_hasStdCmap = false; // last mouse event information we need to filter out the duplicates #if wxUSE_MOUSEEVENT_HACK static struct MouseEventInfoDummy { // mouse position (in screen coordinates) wxPoint pos; // last mouse event type wxEventType type; } gs_lastMouseEvent; #endif // wxUSE_MOUSEEVENT_HACK // --------------------------------------------------------------------------- // private functions // --------------------------------------------------------------------------- // the window proc for all our windows LRESULT WXDLLEXPORT APIENTRY _EXPORT wxWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); #ifdef __WXDEBUG__ const wxChar *wxGetMessageName(int message); #endif //__WXDEBUG__ void wxRemoveHandleAssociation(wxWindowMSW *win); extern void wxAssociateWinWithHandle(HWND hWnd, wxWindowMSW *win); wxWindow *wxFindWinFromHandle(WXHWND hWnd); // get the text metrics for the current font static TEXTMETRIC wxGetTextMetrics(const wxWindowMSW *win); #ifdef __WXWINCE__ // find the window for the mouse event at the specified position static wxWindowMSW *FindWindowForMouseEvent(wxWindowMSW *win, int *x, int *y); #endif // __WXWINCE__ // wrapper around BringWindowToTop() API static inline void wxBringWindowToTop(HWND hwnd) { #ifdef __WXMICROWIN__ // It seems that MicroWindows brings the _parent_ of the window to the top, // which can be the wrong one. // activate (set focus to) specified window ::SetFocus(hwnd); #endif // raise top level parent to top of z order if (!::SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE)) { wxLogLastError(_T("SetWindowPos")); } } #ifndef __WXWINCE__ // ensure that all our parent windows have WS_EX_CONTROLPARENT style static void EnsureParentHasControlParentStyle(wxWindow *parent) { /* If we have WS_EX_CONTROLPARENT flag we absolutely *must* set it for our parent as well as otherwise several Win32 functions using GetNextDlgTabItem() to iterate over all controls such as IsDialogMessage() or DefDlgProc() would enter an infinite loop: indeed, all of them iterate over all the controls starting from the currently focused one and stop iterating when they get back to the focus but unless all parents have WS_EX_CONTROLPARENT bit set, they would never get back to the initial (focused) window: as we do have this style, GetNextDlgTabItem() will leave this window and continue in its parent, but if the parent doesn't have it, it wouldn't recurse inside it later on and so wouldn't have a chance of getting back to this window either. */ while ( parent && !parent->IsTopLevel() ) { LONG exStyle = ::GetWindowLong(GetHwndOf(parent), GWL_EXSTYLE); if ( !(exStyle & WS_EX_CONTROLPARENT) ) { // force the parent to have this style ::SetWindowLong(GetHwndOf(parent), GWL_EXSTYLE, exStyle | WS_EX_CONTROLPARENT); } parent = parent->GetParent(); } } #endif // !__WXWINCE__ #ifdef __WXWINCE__ // On Windows CE, GetCursorPos can return an error, so use this function // instead bool GetCursorPosWinCE(POINT* pt) { if (!GetCursorPos(pt)) { DWORD pos = GetMessagePos(); pt->x = LOWORD(pos); pt->y = HIWORD(pos); } return true; } #endif static wxBorder TranslateBorder(wxBorder border) { if ( border == wxBORDER_THEME ) { #if defined(__POCKETPC__) || defined(__SMARTPHONE__) return wxBORDER_SIMPLE; #elif wxUSE_UXTHEME if (wxUxThemeEngine::GetIfActive()) return wxBORDER_THEME; #endif return wxBORDER_SUNKEN; } return border; } // --------------------------------------------------------------------------- // event tables // --------------------------------------------------------------------------- // in wxUniv/MSW this class is abstract because it doesn't have DoPopupMenu() // method #ifdef __WXUNIVERSAL__ IMPLEMENT_ABSTRACT_CLASS(wxWindowMSW, wxWindowBase) #else // __WXMSW__ #if wxUSE_EXTENDED_RTTI // windows that are created from a parent window during its Create method, eg. spin controls in a calendar controls // must never been streamed out separately otherwise chaos occurs. Right now easiest is to test for negative ids, as // windows with negative ids never can be recreated anyway bool wxWindowStreamingCallback( const wxObject *object, wxWriter * , wxPersister * , wxxVariantArray & ) { const wxWindow * win = dynamic_cast<const wxWindow*>(object) ; if ( win && win->GetId() < 0 ) return false ; return true ; } IMPLEMENT_DYNAMIC_CLASS_XTI_CALLBACK(wxWindow, wxWindowBase,"wx/window.h", wxWindowStreamingCallback) // make wxWindowList known before the property is used wxCOLLECTION_TYPE_INFO( wxWindow* , wxWindowList ) ; template<> void wxCollectionToVariantArray( wxWindowList const &theList, wxxVariantArray &value) { wxListCollectionToVariantArray<wxWindowList::compatibility_iterator>( theList , value ) ; } WX_DEFINE_FLAGS( wxWindowStyle ) wxBEGIN_FLAGS( wxWindowStyle ) // new style border flags, we put them first to // use them for streaming out wxFLAGS_MEMBER(wxBORDER_SIMPLE) wxFLAGS_MEMBER(wxBORDER_SUNKEN) wxFLAGS_MEMBER(wxBORDER_DOUBLE) wxFLAGS_MEMBER(wxBORDER_RAISED) wxFLAGS_MEMBER(wxBORDER_STATIC) wxFLAGS_MEMBER(wxBORDER_NONE) // old style border flags wxFLAGS_MEMBER(wxSIMPLE_BORDER) wxFLAGS_MEMBER(wxSUNKEN_BORDER) wxFLAGS_MEMBER(wxDOUBLE_BORDER) wxFLAGS_MEMBER(wxRAISED_BORDER) wxFLAGS_MEMBER(wxSTATIC_BORDER) wxFLAGS_MEMBER(wxBORDER) // standard window styles wxFLAGS_MEMBER(wxTAB_TRAVERSAL) wxFLAGS_MEMBER(wxCLIP_CHILDREN) wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW) wxFLAGS_MEMBER(wxWANTS_CHARS) wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE) wxFLAGS_MEMBER(wxALWAYS_SHOW_SB ) wxFLAGS_MEMBER(wxVSCROLL) wxFLAGS_MEMBER(wxHSCROLL) wxEND_FLAGS( wxWindowStyle ) wxBEGIN_PROPERTIES_TABLE(wxWindow) wxEVENT_PROPERTY( Close , wxEVT_CLOSE_WINDOW , wxCloseEvent) wxEVENT_PROPERTY( Create , wxEVT_CREATE , wxWindowCreateEvent ) wxEVENT_PROPERTY( Destroy , wxEVT_DESTROY , wxWindowDestroyEvent ) // Always constructor Properties first wxREADONLY_PROPERTY( Parent,wxWindow*, GetParent, EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) wxPROPERTY( Id,wxWindowID, SetId, GetId, -1 /*wxID_ANY*/ , 0 /*flags*/ , wxT("Helpstring") , wxT("group") ) wxPROPERTY( Position,wxPoint, SetPosition , GetPosition, wxDefaultPosition , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // pos wxPROPERTY( Size,wxSize, SetSize, GetSize, wxDefaultSize , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // size wxPROPERTY( WindowStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style // Then all relations of the object graph wxREADONLY_PROPERTY_COLLECTION( Children , wxWindowList , wxWindowBase* , GetWindowChildren , wxPROP_OBJECT_GRAPH /*flags*/ , wxT("Helpstring") , wxT("group")) // and finally all other properties wxPROPERTY( ExtraStyle , long , SetExtraStyle , GetExtraStyle , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // extstyle wxPROPERTY( BackgroundColour , wxColour , SetBackgroundColour , GetBackgroundColour , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // bg wxPROPERTY( ForegroundColour , wxColour , SetForegroundColour , GetForegroundColour , EMPTY_MACROVALUE , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // fg wxPROPERTY( Enabled , bool , Enable , IsEnabled , wxxVariant((bool)true) , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) wxPROPERTY( Shown , bool , Show , IsShown , wxxVariant((bool)true) , 0 /*flags*/ , wxT("Helpstring") , wxT("group")) #if 0 // possible property candidates (not in xrc) or not valid in all subclasses wxPROPERTY( Title,wxString, SetTitle, GetTitle, wxEmptyString ) wxPROPERTY( Font , wxFont , SetFont , GetWindowFont , ) wxPROPERTY( Label,wxString, SetLabel, GetLabel, wxEmptyString ) // MaxHeight, Width , MinHeight , Width // TODO switch label to control and title to toplevels wxPROPERTY( ThemeEnabled , bool , SetThemeEnabled , GetThemeEnabled , ) //wxPROPERTY( Cursor , wxCursor , SetCursor , GetCursor , ) // wxPROPERTY( ToolTip , wxString , SetToolTip , GetToolTipText , ) wxPROPERTY( AutoLayout , bool , SetAutoLayout , GetAutoLayout , ) #endif wxEND_PROPERTIES_TABLE() wxBEGIN_HANDLERS_TABLE(wxWindow) wxEND_HANDLERS_TABLE() wxCONSTRUCTOR_DUMMY(wxWindow) #else IMPLEMENT_DYNAMIC_CLASS(wxWindow, wxWindowBase) #endif #endif // __WXUNIVERSAL__/__WXMSW__ BEGIN_EVENT_TABLE(wxWindowMSW, wxWindowBase) EVT_SYS_COLOUR_CHANGED(wxWindowMSW::OnSysColourChanged) EVT_ERASE_BACKGROUND(wxWindowMSW::OnEraseBackground) #ifdef __WXWINCE__ EVT_INIT_DIALOG(wxWindowMSW::OnInitDialog) #endif END_EVENT_TABLE() // =========================================================================== // implementation // =========================================================================== // --------------------------------------------------------------------------- // wxWindow utility functions // --------------------------------------------------------------------------- // Find an item given the MS Windows id wxWindow *wxWindowMSW::FindItem(long id) const { #if wxUSE_CONTROLS wxControl *item = wxDynamicCastThis(wxControl); if ( item ) { // is it us or one of our "internal" children? if ( item->GetId() == id #ifndef __WXUNIVERSAL__ || (item->GetSubcontrols().Index(id) != wxNOT_FOUND) #endif // __WXUNIVERSAL__ ) { return item; } } #endif // wxUSE_CONTROLS wxWindowList::compatibility_iterator current = GetChildren().GetFirst(); while (current) { wxWindow *childWin = current->GetData(); wxWindow *wnd = childWin->FindItem(id); if ( wnd ) return wnd; current = current->GetNext(); } return NULL; } // Find an item given the MS Windows handle wxWindow *wxWindowMSW::FindItemByHWND(WXHWND hWnd, bool controlOnly) const { wxWindowList::compatibility_iterator current = GetChildren().GetFirst(); while (current) { wxWindow *parent = current->GetData(); // Do a recursive search. wxWindow *wnd = parent->FindItemByHWND(hWnd); if ( wnd ) return wnd; if ( !controlOnly #if wxUSE_CONTROLS || parent->IsKindOf(CLASSINFO(wxControl)) #endif // wxUSE_CONTROLS ) { wxWindow *item = current->GetData(); if ( item->GetHWND() == hWnd ) return item; else { if ( item->ContainsHWND(hWnd) ) return item; } } current = current->GetNext(); } return NULL; } // Default command handler bool wxWindowMSW::MSWCommand(WXUINT WXUNUSED(param), WXWORD WXUNUSED(id)) { return false; } // ---------------------------------------------------------------------------- // constructors and such // ---------------------------------------------------------------------------- void wxWindowMSW::Init() { // MSW specific m_isBeingDeleted = false; m_oldWndProc = NULL; m_mouseInWindow = false; m_lastKeydownProcessed = false; m_childrenDisabled = NULL; m_frozenness = 0; m_hWnd = 0; m_hDWP = 0; m_xThumbSize = 0; m_yThumbSize = 0; m_pendingPosition = wxDefaultPosition; m_pendingSize = wxDefaultSize; #ifdef __POCKETPC__ m_contextMenuEnabled = false; #endif } // Destructor wxWindowMSW::~wxWindowMSW() { m_isBeingDeleted = true; #ifndef __WXUNIVERSAL__ // VS: make sure there's no wxFrame with last focus set to us: for ( wxWindow *win = GetParent(); win; win = win->GetParent() ) { wxTopLevelWindow *frame = wxDynamicCast(win, wxTopLevelWindow); if ( frame ) { if ( frame->GetLastFocus() == this ) { frame->SetLastFocus(NULL); } // apparently sometimes we can end up with our grand parent // pointing to us as well: this is surely a bug in focus handling // code but it's not clear where it happens so for now just try to // fix it here by not breaking out of the loop //break; } } #endif // __WXUNIVERSAL__ // VS: destroy children first and _then_ detach *this from its parent. // If we did it the other way around, children wouldn't be able // find their parent frame (see above). DestroyChildren(); if ( m_hWnd ) { // VZ: test temp removed to understand what really happens here //if (::IsWindow(GetHwnd())) { if ( !::DestroyWindow(GetHwnd()) ) wxLogLastError(wxT("DestroyWindow")); } // remove hWnd <-> wxWindow association wxRemoveHandleAssociation(this); } delete m_childrenDisabled; } // real construction (Init() must have been called before!) bool wxWindowMSW::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { wxCHECK_MSG( parent, false, wxT("can't create wxWindow without parent") ); if ( !CreateBase(parent, id, pos, size, style, wxDefaultValidator, name) ) return false; parent->AddChild(this); WXDWORD exstyle; DWORD msflags = MSWGetCreateWindowFlags(&exstyle); #ifdef __WXUNIVERSAL__ // no borders, we draw them ourselves exstyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_STATICEDGE | WS_EX_CLIENTEDGE | WS_EX_WINDOWEDGE); msflags &= ~WS_BORDER; #endif // wxUniversal if ( IsShown() ) { msflags |= WS_VISIBLE; } if ( !MSWCreate(wxCanvasClassName, NULL, pos, size, msflags, exstyle) ) return false; InheritAttributes(); return true; } // --------------------------------------------------------------------------- // basic operations // --------------------------------------------------------------------------- void wxWindowMSW::SetFocus() { HWND hWnd = GetHwnd(); wxCHECK_RET( hWnd, _T("can't set focus to invalid window") ); #if !defined(__WXMICROWIN__) && !defined(__WXWINCE__) ::SetLastError(0); #endif if ( !::SetFocus(hWnd) ) { #if defined(__WXDEBUG__) && !defined(__WXMICROWIN__) // was there really an error? DWORD dwRes = ::GetLastError(); if ( dwRes ) { HWND hwndFocus = ::GetFocus(); if ( hwndFocus != hWnd ) { wxLogApiError(_T("SetFocus"), dwRes); } } #endif // Debug } } void wxWindowMSW::SetFocusFromKbd() { // when the focus is given to the control with DLGC_HASSETSEL style from // keyboard its contents should be
c++
code
19,999
3,927
#include "IntNode.h" #include "IntDiff.h" #include "Logs.h" #include "PackStream.h" #include <cassert> #include <sstream> IntNode::IntNode(DefinitionNode *parent, const string &name, int value) : DefinitionNode(parent, name, "int"), value(value) { } string IntNode::toString(int indent) const { ostringstream stream; stream << DefinitionNode::toString(indent) << " " << value; return stream.str(); } void IntNode::save(PackStream *stream) const { stream->write(&value); } void IntNode::load(PackStream *stream) { int val; stream->read(&val); setValue(val); } void IntNode::copy(DefinitionNode *destination) const { if (auto tdest = dynamic_cast<IntNode *>(destination)) { tdest->setValue(value); } else { Logs::error("Definition") << "Can't copy from " << getTypeName() << " to " << destination->getTypeName() << endl; } } void IntNode::setValue(int new_value) { addDiff(produceDiff(new_value)); } const IntDiff *IntNode::produceDiff(int new_value) const { return new IntDiff(this, value, new_value); } void IntNode::generateInitDiffs(vector<const DefinitionDiff *> *diffs) const { diffs->push_back(produceDiff(value)); } bool IntNode::applyDiff(const DefinitionDiff *diff, bool backward) { if (!DefinitionNode::applyDiff(diff, backward)) { return false; } assert(diff->getTypeName() == "int"); auto int_diff = dynamic_cast<const IntDiff *>(diff); if (int_diff) { int previous = backward ? int_diff->getNewValue() : int_diff->getOldValue(); int next = backward ? int_diff->getOldValue() : int_diff->getNewValue(); if (value == previous) { value = next; tellChanged(); return true; } else { Logs::error("Definition") << "Can't apply int diff " << previous << " => " << next << " to " << getName() << endl; return false; } } else { Logs::error("Could not cast DefinitionDiff to IntDiff"); return false; } }
c++
code
2,115
505
/** * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * OpenAPI spec version: 20220523 * * * NOTE: This class is auto generated by OpenAPI Generator * https://github.com/OpenAPITools/openapi-generator * Do not edit the class manually. */ #include "OpenAPILocationAreaApi.h" #include "OpenAPILocationAreaApiOperations.h" #include "OpenAPIModule.h" #include "HttpModule.h" #include "Serialization/JsonSerializer.h" namespace OpenAPI { OpenAPILocationAreaApi::OpenAPILocationAreaApi() : Url(TEXT("https://pokeapi.co")) { } OpenAPILocationAreaApi::~OpenAPILocationAreaApi() {} void OpenAPILocationAreaApi::SetURL(const FString& InUrl) { Url = InUrl; } void OpenAPILocationAreaApi::AddHeaderParam(const FString& Key, const FString& Value) { AdditionalHeaderParams.Add(Key, Value); } void OpenAPILocationAreaApi::ClearHeaderParams() { AdditionalHeaderParams.Reset(); } bool OpenAPILocationAreaApi::IsValid() const { if (Url.IsEmpty()) { UE_LOG(LogOpenAPI, Error, TEXT("OpenAPILocationAreaApi: Endpoint Url is not set, request cannot be performed")); return false; } return true; } void OpenAPILocationAreaApi::SetHttpRetryManager(FHttpRetrySystem::FManager& InRetryManager) { if(RetryManager != &GetHttpRetryManager()) { DefaultRetryManager.Reset(); RetryManager = &InRetryManager; } } FHttpRetrySystem::FManager& OpenAPILocationAreaApi::GetHttpRetryManager() { checkf(RetryManager, TEXT("OpenAPILocationAreaApi: RetryManager is null. You may have meant to set it with SetHttpRetryManager first, or you may not be using a custom RetryManager at all.")) return *RetryManager; } FHttpRequestRef OpenAPILocationAreaApi::CreateHttpRequest(const Request& Request) const { if (!Request.GetRetryParams().IsSet()) { return FHttpModule::Get().CreateRequest(); } else { if (!RetryManager) { // Create default retry manager if none was specified DefaultRetryManager = MakeUnique<HttpRetryManager>(6, 60); RetryManager = DefaultRetryManager.Get(); } const HttpRetryParams& Params = Request.GetRetryParams().GetValue(); return RetryManager->CreateRequest(Params.RetryLimitCountOverride, Params.RetryTimeoutRelativeSecondsOverride, Params.RetryResponseCodes, Params.RetryVerbs, Params.RetryDomains); } } void OpenAPILocationAreaApi::HandleResponse(FHttpResponsePtr HttpResponse, bool bSucceeded, Response& InOutResponse) const { InOutResponse.SetHttpResponse(HttpResponse); InOutResponse.SetSuccessful(bSucceeded); if (bSucceeded && HttpResponse.IsValid()) { InOutResponse.SetHttpResponseCode((EHttpResponseCodes::Type)HttpResponse->GetResponseCode()); FString ContentType = HttpResponse->GetContentType(); FString Content; if (ContentType.IsEmpty()) { return; // Nothing to parse } else if (ContentType.StartsWith(TEXT("application/json")) || ContentType.StartsWith("text/json")) { Content = HttpResponse->GetContentAsString(); TSharedPtr<FJsonValue> JsonValue; auto Reader = TJsonReaderFactory<>::Create(Content); if (FJsonSerializer::Deserialize(Reader, JsonValue) && JsonValue.IsValid()) { if (InOutResponse.FromJson(JsonValue)) return; // Successfully parsed } } else if(ContentType.StartsWith(TEXT("text/plain"))) { Content = HttpResponse->GetContentAsString(); InOutResponse.SetResponseString(Content); return; // Successfully parsed } // Report the parse error but do not mark the request as unsuccessful. Data could be partial or malformed, but the request succeeded. UE_LOG(LogOpenAPI, Error, TEXT("Failed to deserialize Http response content (type:%s):\n%s"), *ContentType , *Content); return; } // By default, assume we failed to establish connection InOutResponse.SetHttpResponseCode(EHttpResponseCodes::RequestTimeout); } FHttpRequestPtr OpenAPILocationAreaApi::LocationAreaList(const LocationAreaListRequest& Request, const FLocationAreaListDelegate& Delegate /*= FLocationAreaListDelegate()*/) const { if (!IsValid()) return nullptr; FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) { HttpRequest->SetHeader(It.Key, It.Value); } Request.SetupHttpRequest(HttpRequest); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPILocationAreaApi::OnLocationAreaListResponse, Delegate); HttpRequest->ProcessRequest(); return HttpRequest; } void OpenAPILocationAreaApi::OnLocationAreaListResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLocationAreaListDelegate Delegate) const { LocationAreaListResponse Response; HandleResponse(HttpResponse, bSucceeded, Response); Delegate.ExecuteIfBound(Response); } FHttpRequestPtr OpenAPILocationAreaApi::LocationAreaRead(const LocationAreaReadRequest& Request, const FLocationAreaReadDelegate& Delegate /*= FLocationAreaReadDelegate()*/) const { if (!IsValid()) return nullptr; FHttpRequestRef HttpRequest = CreateHttpRequest(Request); HttpRequest->SetURL(*(Url + Request.ComputePath())); for(const auto& It : AdditionalHeaderParams) { HttpRequest->SetHeader(It.Key, It.Value); } Request.SetupHttpRequest(HttpRequest); HttpRequest->OnProcessRequestComplete().BindRaw(this, &OpenAPILocationAreaApi::OnLocationAreaReadResponse, Delegate); HttpRequest->ProcessRequest(); return HttpRequest; } void OpenAPILocationAreaApi::OnLocationAreaReadResponse(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded, FLocationAreaReadDelegate Delegate) const { LocationAreaReadResponse Response; HandleResponse(HttpResponse, bSucceeded, Response); Delegate.ExecuteIfBound(Response); } }
c++
code
5,739
1,068
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #pragma once #include <eve/detail/spy.hpp> #include <concepts> #if defined(SPY_STDLIB_IS_LIBCPP) #include <type_traits> #include <functional> namespace std { template<typename T> concept floating_point = std::is_floating_point_v<T>; template<typename T> concept integral = std::is_integral_v<T>; template<typename T> concept unsigned_integral = std::is_unsigned_v<T>; template<typename T> concept signed_integral = std::is_signed_v<T> && std::is_integral_v<T>; template<typename F, typename... Ts> concept invocable = requires(F&& f, Ts&&...ts) { std::invoke(std::forward<F>(f), std::forward<Ts>(ts)...); }; template<typename From, typename To> concept convertible_to = std::is_convertible_v<From, To> && requires(std::add_rvalue_reference_t<From> (&f)()) { static_cast<To>(f()); }; template< class Derived, class Base > concept derived_from = std::is_base_of_v<Base, Derived> && std::is_convertible_v<const volatile Derived*, const volatile Base*>; // ----------------------------------------------------------------------------------------------- // Plumbing for input_iterator concept template<typename I> struct indirectly_readable_traits { }; template<typename T> struct indirectly_readable_traits<T*> { using value_type = std::remove_cv_t<T>; }; template<typename T> requires std::is_array_v<T> struct indirectly_readable_traits<T> { using value_type = std::remove_cv_t<std::remove_extent_t<T>>; }; template<typename T > struct indirectly_readable_traits<const T> : indirectly_readable_traits<T> {}; template<typename T> requires requires { typename T::value_type; } struct indirectly_readable_traits<T> { using value_type = typename T::value_type; }; template<typename T> requires requires { typename T::element_type; } struct indirectly_readable_traits<T> { using value_type = typename T::element_type; }; template<typename T > using iter_reference_t = decltype(*std::declval<T&>()); template<typename I> struct incrementable_traits {}; template<typename T> requires std::is_object_v<T> struct incrementable_traits<T*> { using difference_type = std::ptrdiff_t; }; template<typename T> struct incrementable_traits<const T> : incrementable_traits<T> {}; template<typename T> requires requires { typename T::difference_type; } struct incrementable_traits<T> { using difference_type = typename T::difference_type; }; template<typename I> concept input_iterator = requires(I i) { // Requires c++20 stdc++ typename std::incrementable_traits<I>::difference_type; typename std::indirectly_readable_traits<I>::value_type; requires std::signed_integral<typename std::incrementable_traits<I>::difference_type>; // typename std::common_reference_t< std::iter_reference_t<I>&& // , typename std::indirectly_readable_traits<I>::value_type& // >; { *i++ }; // typename std::common_reference_t< decltype(*i++)&& // , typename std::indirectly_readable_traits<I>::value_type& // >; }; } #endif
c++
code
3,659
733
// 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. #include <bsoncxx/builder/basic/array.hpp> #include <bsoncxx/builder/basic/document.hpp> #include <bsoncxx/builder/basic/kvp.hpp> #include <bsoncxx/stdx/make_unique.hpp> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/stdx.hpp> #include <mongocxx/uri.hpp> using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; using bsoncxx::builder::basic::array; int main(int, char**) { // The mongocxx::instance constructor and destructor initialize and shut down the driver, // respectively. Therefore, a mongocxx::instance must be created before using the driver and // must remain alive for as long as the driver is in use. mongocxx::instance inst{}; mongocxx::client conn{mongocxx::uri{}}; auto db = conn["test"]; // Many driver methods take a bsoncxx::document::view_or_value as // a parameter. You can use these methods with either a document::view // or a document::value. // Document::views can be passed in directly: { bsoncxx::document::value command = make_document(kvp("ping", 1)); bsoncxx::document::view command_view = command.view(); auto res = db.run_command(command_view); } // Document::values can be passed in one of two ways: // 1. Pass a view of the document::value { bsoncxx::document::value command = make_document(kvp("ping", 1)); auto res = db.run_command(command.view()); } // 2. Pass ownership of the document::value into the method { bsoncxx::document::value command = make_document(kvp("ping", 1)); auto res = db.run_command(std::move(command)); } // Temporary document::values are captured and owned by the view_or_value type { auto res = db.run_command(make_document(kvp("ping", 1))); // NOTE: there is no need to call .view() on a temporary document::value in // a call like this, and doing so could result in a use-after-free error. // BAD: // auto res = db.run_command(make_document(kvp("ping", 1)).view()); } }
c++
code
2,674
577
//===-test_reduce_log_sum_negative_axes_xnnpack.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 xnnpack // RUN: %halo_compiler -target cxx -o %data_path/test_reduce_log_sum_negative_axes/test_data_set_0/output_0.cc -x onnx -emit-data-as-c %data_path/test_reduce_log_sum_negative_axes/test_data_set_0/output_0.pb // RUN: %halo_compiler -target cxx -o %data_path/test_reduce_log_sum_negative_axes/test_data_set_0/input_0.cc -x onnx -emit-data-as-c %data_path/test_reduce_log_sum_negative_axes/test_data_set_0/input_0.pb // RUN: %halo_compiler -target cxx -batch-size 1 %halo_compile_flags %data_path/test_reduce_log_sum_negative_axes/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_reduce_log_sum_negative_axes/test_data_set_0 %odla_link %device_link -lodla_xnnpack -o %t_xnnpack.exe -Wno-deprecated-declarations // RUN: %t_xnnpack.exe 0.0001 0 xnnpack %data_path/test_reduce_log_sum_negative_axes | FileCheck %s // CHECK: Result Pass // clang-format on // XFAIL: * #include "test_reduce_log_sum_negative_axes_xnnpack.cc.tmp.main.cc.in"
c++
code
1,936
289
// // Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”) // 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. // #pragma once #include <filesystem> #include <list> #include <optional> #include <string> #include "cached_file.hpp" namespace boost { namespace asio { class io_context; } } // namespace boost namespace mtconnect::sink::rest_sink { using XmlNamespace = std::pair<std::string, std::string>; using XmlNamespaceList = std::list<XmlNamespace>; class FileCache { public: using Directory = std::pair<std::string, std::pair<std::filesystem::path, std::string>>; FileCache(size_t max = 20 * 1024); XmlNamespaceList registerFiles(const std::string &uri, const std::string &path, const std::string &version); XmlNamespaceList registerDirectory(const std::string &uri, const std::string &path, const std::string &version); std::optional<XmlNamespace> registerFile(const std::string &uri, const std::string &pathName, const std::string &version) { std::filesystem::path path(pathName); return registerFile(uri, path, version); } std::optional<XmlNamespace> registerFile(const std::string &uri, const std::filesystem::path &path, const std::string &version); CachedFilePtr getFile(const std::string &name, const std::optional<std::string> acceptEncoding = std::nullopt, boost::asio::io_context *context = nullptr); bool hasFile(const std::string &name) const { return (m_fileCache.count(name) > 0) || (m_fileMap.count(name) > 0); } void addMimeType(const std::string &ext, const std::string &type) { std::string s(ext); if (s[0] != '.') s.insert(0, "."); m_mimeTypes[s] = type; } void addDirectory(const std::string &uri, const std::string &path, const std::string &index); void setMaxCachedFileSize(size_t s) { m_maxCachedFileSize = s; } auto getMaxCachedFileSize() const { return m_maxCachedFileSize; } void setMinCompressedFileSize(size_t s) { m_minCompressedFileSize = s; } auto getMinCompressedFileSize() const { return m_minCompressedFileSize; } // For testing void clear() { m_fileCache.clear(); } protected: CachedFilePtr findFileInDirectories(const std::string &name); const std::string &getMimeType(std::string ext) { static std::string octStream("application/octet-stream"); auto mt = m_mimeTypes.find(ext); if (mt != m_mimeTypes.end()) return mt->second; else return octStream; } CachedFilePtr redirect(const std::string &name, const Directory &directory); void compressFile(CachedFilePtr file, boost::asio::io_context *context); protected: std::map<std::string, std::pair<std::filesystem::path, std::string>> m_directories; std::map<std::string, std::filesystem::path> m_fileMap; std::map<std::string, CachedFilePtr> m_fileCache; std::map<std::string, std::string> m_mimeTypes; size_t m_maxCachedFileSize; size_t m_minCompressedFileSize; }; } // namespace mtconnect::sink::rest_sink
c++
code
3,908
843
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2018 Miodrag Milanovic <[email protected]> * Copyright (C) 2018 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/register.h" #include "kernel/celltypes.h" #include "kernel/rtlil.h" #include "kernel/log.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct SynthAnlogicPass : public ScriptPass { SynthAnlogicPass() : ScriptPass("synth_anlogic", "synthesis for Anlogic FPGAs") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" synth_anlogic [options]\n"); log("\n"); log("This command runs synthesis for Anlogic FPGAs.\n"); log("\n"); log(" -top <module>\n"); log(" use the specified module as top module\n"); log("\n"); log(" -edif <file>\n"); log(" write the design to the specified EDIF file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -json <file>\n"); log(" write the design to the specified JSON file. writing of an output file\n"); log(" is omitted if this parameter is not specified.\n"); log("\n"); log(" -run <from_label>:<to_label>\n"); log(" only run the commands between the labels (see below). an empty\n"); log(" from label is synonymous to 'begin', and empty to label is\n"); log(" synonymous to the end of the command list.\n"); log("\n"); log(" -noflatten\n"); log(" do not flatten design before synthesis\n"); log("\n"); log(" -retime\n"); log(" run 'abc' with '-dff -D 1' options\n"); log("\n"); log(" -nolutram\n"); log(" do not use EG_LOGIC_DRAM16X4 cells in output netlist\n"); log("\n"); log("\n"); log("The following commands are executed by this synthesis command:\n"); help_script(); log("\n"); } string top_opt, edif_file, json_file; bool flatten, retime, nolutram; void clear_flags() YS_OVERRIDE { top_opt = "-auto-top"; edif_file = ""; json_file = ""; flatten = true; retime = false; nolutram = false; } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { string run_from, run_to; clear_flags(); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-top" && argidx+1 < args.size()) { top_opt = "-top " + args[++argidx]; continue; } if (args[argidx] == "-edif" && argidx+1 < args.size()) { edif_file = args[++argidx]; continue; } if (args[argidx] == "-json" && argidx+1 < args.size()) { json_file = args[++argidx]; continue; } if (args[argidx] == "-run" && argidx+1 < args.size()) { size_t pos = args[argidx+1].find(':'); if (pos == std::string::npos) break; run_from = args[++argidx].substr(0, pos); run_to = args[argidx].substr(pos+1); continue; } if (args[argidx] == "-noflatten") { flatten = false; continue; } if (args[argidx] == "-nolutram") { nolutram = true; continue; } if (args[argidx] == "-retime") { retime = true; continue; } break; } extra_args(args, argidx, design); if (!design->full_selection()) log_cmd_error("This command only operates on fully selected designs!\n"); log_header(design, "Executing SYNTH_ANLOGIC pass.\n"); log_push(); run_script(design, run_from, run_to); log_pop(); } void script() YS_OVERRIDE { if (check_label("begin")) { run("read_verilog -lib +/anlogic/cells_sim.v +/anlogic/eagle_bb.v"); run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str())); } if (flatten && check_label("flatten", "(unless -noflatten)")) { run("proc"); run("flatten"); run("tribuf -logic"); run("deminout"); } if (check_label("coarse")) { run("synth -run coarse"); } if (!nolutram && check_label("map_lutram", "(skip if -nolutram)")) { run("memory_bram -rules +/anlogic/lutrams.txt"); run("techmap -map +/anlogic/lutrams_map.v"); run("setundef -zero -params t:EG_LOGIC_DRAM16X4"); } if (check_label("map_ffram")) { run("opt -fast -mux_undef -undriven -fine"); run("memory_map"); run("opt -undriven -fine"); } if (check_label("map_gates")) { run("techmap -map +/techmap.v -map +/anlogic/arith_map.v"); run("opt -fast"); if (retime || help_mode) run("abc -dff -D 1", "(only if -retime)"); } if (check_label("map_ffs")) { run("techmap -D NO_LUT -map +/anlogic/cells_map.v"); run("dffinit -strinit SET RESET -ff AL_MAP_SEQ q REGSET -noreinit"); run("opt_expr -mux_undef"); run("simplemap"); } if (check_label("map_luts")) { run("abc -lut 4:6"); run("clean"); } if (check_label("map_cells")) { run("techmap -map +/anlogic/cells_map.v"); run("clean"); } if (check_label("map_anlogic")) { run("anlogic_fixcarry"); run("anlogic_eqn"); } if (check_label("check")) { run("hierarchy -check"); run("stat"); run("check -noinit"); } if (check_label("edif")) { if (!edif_file.empty() || help_mode) run(stringf("write_edif %s", help_mode ? "<file-name>" : edif_file.c_str())); } if (check_label("json")) { if (!json_file.empty() || help_mode) run(stringf("write_json %s", help_mode ? "<file-name>" : json_file.c_str())); } } } SynthAnlogicPass; PRIVATE_NAMESPACE_END
c++
code
6,207
1,639
/** * @file * $Revision: 1.1.1.1 $ * $Date: 2006/10/31 23:18:06 $ * * Unless noted otherwise, the portions of Isis written by the USGS are * public domain. See individual third-party library and package descriptions * for intellectual property information, user agreements, and related * information. * * Although Isis has been used by the USGS, no warranty, expressed or * implied, is made by the USGS as to the accuracy and functioning of such * software and related material nor shall the fact of distribution * constitute any such warranty, and no responsibility is assumed by the * USGS in connection therewith. * * For additional information, launch * $ISISROOT/doc//documents/Disclaimers/Disclaimers.html * in a browser or see the Privacy &amp; Disclaimers page on the Isis website, * http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on * http://www.usgs.gov/privacy.html. */ #include <iostream> #include <QList> #include "Buffer.h" #include "UniqueIOCachingAlgorithm.h" #include "RawCubeChunk.h" using namespace Isis; using namespace std; int main() { const int uniqueIos = 2; const int ioSeparation = 10; UniqueIOCachingAlgorithm alg(uniqueIos); QList <RawCubeChunk *> allocatedChunks; // algorithm doesn't use the buffer so we don't need to initialize this // properly Buffer ioBufferTmp; QList <RawCubeChunk *> ioUsedChunks; for (int ioNum = 0; ioNum < uniqueIos * 2; ioNum ++) { int cubeLine = (ioNum + 1) * ioSeparation + 1; RawCubeChunk *ioChunk = new RawCubeChunk(1, cubeLine, 1, 2, cubeLine, 1, 0); allocatedChunks.append(ioChunk); } QList <int> indicesToTry; for (int i = 0; i < 4; i++) { indicesToTry << 0; } for (int i = 0; i < 4; i++) { indicesToTry << i % uniqueIos; } for (int i = 0; i < 4; i++) { indicesToTry << i % (uniqueIos * 2); } for (int i = 0; i < 4; i++) { indicesToTry << (4 - i - 1) % (uniqueIos * 2); } QList <RawCubeChunk *> allocatedUsedSoFar; for (int i = 0; i < indicesToTry.size(); i++) { QList <RawCubeChunk *> used; used.append(allocatedChunks[indicesToTry[i]]); if (allocatedUsedSoFar.indexOf(used[0]) == -1) allocatedUsedSoFar.append(used[0]); CubeCachingAlgorithm::CacheResult result = alg.recommendChunksToFree( allocatedUsedSoFar, used, ioBufferTmp); std::cerr << "Cache result (input was " << (used[0]->getStartLine()) << "):\n"; std::cerr << " Understood data? " << result.algorithmUnderstoodData() << "\n"; if (result.algorithmUnderstoodData()) { QList<RawCubeChunk *> toFree = result.getChunksToFree(); std::cerr << " Number of chunks to free = " << toFree.size(); if(toFree.size()) { std::cerr << " @ lines = "; RawCubeChunk *chunkForPrintingLine; bool started = false; foreach(chunkForPrintingLine, toFree) { if(started) std::cerr << ", "; else started = true; std::cerr << chunkForPrintingLine->getStartLine(); allocatedUsedSoFar.removeAll(chunkForPrintingLine); } } std::cerr << "\n"; } } std::cerr << "\n"; return 0; }
c++
code
3,303
728
// Copyright Louis Dionne 2013-2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/assert.hpp> #include <boost/hana/bool.hpp> #include <boost/hana/config.hpp> #include <boost/hana/eval.hpp> #include <boost/hana/if.hpp> #include <boost/hana/lazy.hpp> namespace hana = boost::hana; int main() { BOOST_HANA_CONSTEXPR_LAMBDA auto f = hana::make<hana::lazy_tag>([](auto x) { return 1 / x; }); BOOST_HANA_CONSTEXPR_LAMBDA auto g = hana::make_lazy([](auto x) { return x + 1; }); BOOST_HANA_CONSTEXPR_CHECK(hana::eval(hana::if_(hana::false_c, f(0), g(0))) == 0 + 1); }
c++
code
742
162
/* * Software License Agreement (BSD License) * * Copyright (c) 2011-2012, Matteo Munaro [[email protected]], Filippo Basso [[email protected]] * Copyright (c) 2013-, Open Perception, 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 the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Matteo Munaro [[email protected]], Filippo Basso [[email protected]] * */ #include <ros/ros.h> #include <ros/package.h> #include <opencv2/opencv.hpp> #include <Eigen/Eigen> #include <visualization_msgs/MarkerArray.h> #include <std_msgs/Bool.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <tf/tf.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include <list> #include <sstream> #include <fstream> #include <string.h> #include <open_ptrack/opt_utils/conversions.h> #include <open_ptrack/detection/detection.h> #include <open_ptrack/detection/detection_source.h> #include <open_ptrack/tracking/tracker.h> #include <opt_msgs/Detection.h> #include <opt_msgs/DetectionArray.h> #include <opt_msgs/TrackArray.h> //#include <open_ptrack/opt_utils/ImageConverter.h> // Dynamic reconfigure: #include <dynamic_reconfigure/server.h> #include <tracking/TrackerConfig.h> typedef tracking::TrackerConfig Config; typedef dynamic_reconfigure::Server<Config> ReconfigureServer; // Global variables: std::map<std::string, open_ptrack::detection::DetectionSource*> detection_sources_map; tf::TransformListener* tf_listener; std::string world_frame_id; bool output_history_pointcloud; int output_history_size; int detection_history_size; bool output_markers; bool output_image_rgb; bool output_tracking_results; bool output_detection_results; // Enables/disables the publishing of detection positions to be visualized in RViz bool vertical; ros::Publisher results_pub; ros::Publisher marker_pub_tmp; ros::Publisher marker_pub; ros::Publisher pointcloud_pub; ros::Publisher detection_marker_pub; ros::Publisher detection_trajectory_pub; size_t starting_index; size_t detection_insert_index; tf::Transform camera_frame_to_world_transform; tf::Transform world_to_camera_frame_transform; bool extrinsic_calibration; double period; open_ptrack::tracking::Tracker* tracker; pcl::PointCloud<pcl::PointXYZRGB>::Ptr history_pointcloud(new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr detection_history_pointcloud(new pcl::PointCloud<pcl::PointXYZRGB>); bool swissranger; double min_confidence; double min_confidence_sr; double min_confidence_detections; double min_confidence_detections_sr; std::vector<cv::Vec3f> camera_colors; // vector containing colors to use to identify cameras in the network std::map<std::string, int> color_map; // map between camera frame_id and color // Chi square distribution std::map<double, double> chi_map; bool velocity_in_motion_term; double acceleration_variance; double position_variance_weight; double voxel_size; double gate_distance; bool calibration_refinement; std::map<std::string, Eigen::Matrix4d> registration_matrices; double max_detection_delay; ros::Time latest_time; /** * \brief Create marker to be visualized in RViz * * \param[in] id The marker ID. * \param[in] frame_id The marker reference frame. * \param[in] position The marker position. * \param[in] color The marker color. */ visualization_msgs::Marker createMarker (int id, std::string frame_id, ros::Time stamp, Eigen::Vector3d position, cv::Vec3f color) { visualization_msgs::Marker marker; marker.header.frame_id = world_frame_id; marker.header.stamp = stamp; marker.ns = frame_id; marker.id = id; marker.type = visualization_msgs::Marker::SPHERE; marker.action = visualization_msgs::Marker::ADD; marker.pose.position.x = position(0); marker.pose.position.y = position(1); marker.pose.position.z = position(2); marker.scale.x = 0.1; marker.scale.y = 0.1; marker.scale.z = 0.1; marker.color.r = color(0); marker.color.g = color(1); marker.color.b = color(2); marker.color.a = 1.0; marker.lifetime = ros::Duration(0.2); return marker; } Eigen::Matrix4d readMatrixFromFile (std::string filename) { Eigen::Matrix4d matrix; std::string line; std::ifstream myfile (filename.c_str()); if (myfile.is_open()) { int k = 0; std::string number; while (myfile >> number) { matrix(int(k/4), int(k%4)) = std::atof(number.c_str()); k++; } myfile.close(); } std::cout << matrix << std::endl; return matrix; } /** * \brief Read the DetectionArray message and use the detections for creating/updating/deleting tracks * * \param[in] msg the DetectionArray message. */ void detection_cb(const opt_msgs::DetectionArray::ConstPtr& msg) { // Read message header information: std::string frame_id = msg->header.frame_id; ros::Time frame_time = msg->header.stamp; // Compute delay of detection message, if any: double time_delay = 0.0; if (frame_time > latest_time) { latest_time = frame_time; time_delay = 0.0; } else { time_delay = (latest_time - frame_time).toSec(); } tf::StampedTransform transform; tf::StampedTransform inverse_transform; // cv_bridge::CvImage::Ptr cvPtr; try { // Read transforms between camera frame and world frame: if (!extrinsic_calibration) { static tf::TransformBroadcaster world_to_camera_tf_publisher; // world_to_camera_tf_publisher.sendTransform(tf::StampedTransform(camera_frame_to_world_transform, ros::Time::now(), world_frame_id, frame_id)); world_to_camera_tf_publisher.sendTransform(tf::StampedTransform(world_to_camera_frame_transform, ros::Time::now(), frame_id, world_frame_id)); } //Calculate direct and inverse transforms between camera and world frame: tf_listener->lookupTransform(world_frame_id, frame_id, ros::Time(0), transform); tf_listener->lookupTransform(frame_id, world_frame_id, ros::Time(0), inverse_transform); // cvPtr = cv_bridge::toCvCopy(msg->image, sensor_msgs::image_encodings::BGR8); // Read camera intrinsic parameters: Eigen::Matrix3d intrinsic_matrix; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) intrinsic_matrix(i, j) = msg->intrinsic_matrix[i * 3 + j]; // Add a new DetectionSource or update an existing one: if(detection_sources_map.find(frame_id) == detection_sources_map.end()) { detection_sources_map[frame_id] = new open_ptrack::detection::DetectionSource(cv::Mat(0, 0, CV_8UC3), transform, inverse_transform, intrinsic_matrix, frame_time, frame_id); } else { detection_sources_map[frame_id]->update(cv::Mat(0, 0, CV_8UC3), transform, inverse_transform, intrinsic_matrix, frame_time, frame_id); double d = detection_sources_map[frame_id]->getDuration().toSec() / period; int lostFrames = int(round(d)) - 1; } open_ptrack::detection::DetectionSource* source = detection_sources_map[frame_id]; // Create a Detection object for every detection in the detection message: std::vector<open_ptrack::detection::Detection> detections_vector; for(std::vector<opt_msgs::Detection>::const_iterator it = msg->detections.begin(); it != msg->detections.end(); it++) { detections_vector.push_back(open_ptrack::detection::Detection(*it, source)); } // Convert HOG+SVM confidences to HAAR+ADABOOST-like people detection confidences: if (not std::strcmp(msg->confidence_type.c_str(), "hog+svm")) { for(unsigned int i = 0; i < detections_vector.size(); i++) { // double new_confidence = detections_vector[i].getConfidence(); // new_confidence = (new_confidence - min_confidence_detections_sr) / (min_confidence_sr - min_confidence_detections_sr) * // (min_confidence - min_confidence_detections) + min_confidence_detections; // detections_vector[i].setConfidence(new_confidence+2); double new_confidence = detections_vector[i].getConfidence(); new_confidence = (new_confidence - (-3)) / 3 * 4 + 2; detections_vector[i].setConfidence(new_confidence); //std::cout << detections_vector[i].getConfidence() << std::endl; } } // Detection correction by means of calibration refinement: if (calibration_refinement) { if (strcmp(frame_id.substr(0,1).c_str(), "/") == 0) { frame_id = frame_id.substr(1, frame_id.size() - 1); } Eigen::Matrix4d registration_matrix; std::map<std::string, Eigen::Matrix4d>::iterator registration_matrices_iterator = registration_matrices.find(frame_id); if (registration_matrices_iterator != registration_matrices.end()) { // camera already present registration_matrix = registration_matrices_iterator->second; } else { // camera not present std::cout << "Reading refinement matrix of " << frame_id << " from file." << std::endl; std::string refinement_filename = ros::package::getPath("opt_calibration") + "/conf/registration_" + frame_id + ".txt"; std::ifstream f(refinement_filename.c_str()); if (f.good()) // if the file exists { f.close(); registration_matrix = readMatrixFromFile (refinement_filename); registration_matrices.insert(std::pair<std::string, Eigen::Matrix4d> (frame_id, registration_matrix)); } else // if the file does not exist { // insert the identity matrix std::cout << "Refinement file not found! Not doing refinement for this sensor." << std::endl; registration_matrices.insert(std::pair<std::string, Eigen::Matrix4d> (frame_id, Eigen::Matrix4d::Identity())); } } if(detections_vector.size() > 0) { // Apply detection refinement: for(unsigned int i = 0; i < detections_vector.size(); i++) { Eigen::Vector3d old_centroid = detections_vector[i].getWorldCentroid(); // std::cout << frame_id << std::endl; // std::cout << registration_matrix << std::endl; // std::cout << "old_centroid: " << old_centroid.transpose() << std::endl; Eigen::Vector4d old_centroid_homogeneous(old_centroid(0), old_centroid(1), old_centroid(2), 1.0); Eigen::Vector4d refined_centroid = registration_matrix * old_centroid_homogeneous; detections_vector[i].setWorldCentroid(Eigen::Vector3d(refined_centroid(0), refined_centroid(1), refined_centroid(2))); Eigen::Vector3d refined_centroid2 = detections_vector[i].getWorldCentroid(); // std::cout << "refined_centroid2: " << refined_centroid2.transpose() << std::endl; // std::cout << "difference: " << (refined_centroid2 - old_centroid).transpose() << std::endl << std::endl; } } } // If at least one detection has been received: if((detections_vector.size() > 0) & (time_delay < max_detection_delay)) { // Perform detection-track association: tracker->newFrame(detections_vector); tracker->updateTracks(); // Create a TrackingResult message with the output of the tracking process if(output_tracking_results) { opt_msgs::TrackArray::Ptr tracking_results_msg(new opt_msgs::TrackArray); tracking_results_msg->header.stamp = frame_time; tracking_results_msg->header.frame_id = world_frame_id; tracker->toMsg(tracking_results_msg); // Publish tracking message: results_pub.publish(tracking_results_msg); } // //Show the tracking process' results as an image // if(output_image_rgb) // { // tracker->drawRgb(); // for(std::map<std::string, open_ptrack::detection::DetectionSource*>::iterator // it = detection_sources_map.begin(); it != detection_sources_map.end(); it++) // { // cv::Mat image_to_show = it->second->getImage(); // if (not vertical) // { // //cv::imshow("TRACKER " + it->first, image_to_show); // cv::imshow("TRACKER ", image_to_show); // TODO: use the above row if using multiple cameras // } // else // { // cv::flip(image_to_show.t(), image_to_show, -1); // cv::flip(image_to_show, image_to_show, 1); // //cv::imshow("TRACKER " + it->first, image_to_show); // cv::imshow("TRACKER ", image_to_show); // TODO: use the above row if using multiple cameras // } // cv::waitKey(2); // } // } // Show the pose of each tracked object with a 3D marker (to be visualized with ROS RViz) if(output_markers) { visualization_msgs::MarkerArray::Ptr marker_msg(new visualization_msgs::MarkerArray); tracker->toMarkerArray(marker_msg); marker_pub.publish(marker_msg); } // Show the history of the movements in 3D (3D trajectory) of each tracked object as a PointCloud (which can be visualized in RViz) if(output_history_pointcloud) { history_pointcloud->header.stamp = frame_time.toNSec() / 1e3; // Convert from ns to us history_pointcloud->header.frame_id = world_frame_id; starting_index = tracker->appendToPointCloud(history_pointcloud, starting_index, output_history_size); pointcloud_pub.publish(history_pointcloud); } // Create message for showing detection positions in RViz: if (output_detection_results) { visualization_msgs::MarkerArray::Ptr marker_msg(new visualization_msgs::MarkerArray); detection_history_pointcloud->header.stamp = frame_time.toNSec() / 1e3; // Convert from ns to us detection_history_pointcloud->header.frame_id = world_frame_id; std::string frame_id = detections_vector[0].getSource()->getFrameId(); // Define color: int color_index; std::map<std::string, int>::iterator colormap_iterator = color_map.find(frame_id); if (colormap_iterator != color_map.end()) { // camera already present color_index = colormap_iterator->second; } else { // camera not present color_index = color_map.size(); color_map.insert(std::pair<std::string, int> (frame_id, color_index)); } for (unsigned int i = 0; i < detections_vector.size(); i++) { // Create marker and add it to message: Eigen::Vector3d centroid = detections_vector[i].getWorldCentroid(); visualization_msgs::Marker marker = createMarker (i, frame_id, frame_time, centroid, camera_colors[color_index]); marker_msg->markers.push_back(marker); // Point cloud: pcl::PointXYZRGB point; point.x = marker.pose.position.x; point.y = marker.pose.position.y; point.z = marker.pose.position.z; point.r = marker.color.r * 255.0f; point.g = marker.color.g * 255.0f; point.b = marker.color.b * 255.0f; detection_insert_index = (detection_insert_index + 1) % detection_history_size; detection_history_pointcloud->points[detection_insert_index] = point; } detection_marker_pub.publish(marker_msg); // publish marker message detection_trajectory_pub.publish(detection_history_pointcloud); // publish trajectory message } } else // if no detections have been received { if(output_tracking_results) { // Publish an empty tracking message opt_msgs::TrackArray::Ptr tracking_results_msg(new opt_msgs::TrackArray); tracking_results_msg->header.stamp = frame_time; tracking_results_msg->header.frame_id = world_frame_id; results_pub.publish(tracking_results_msg); } } } // catch(cv_bridge::Exception& ex) // { // ROS_ERROR("cv_bridge exception: %s", ex.what()); // } catch(tf::TransformException& ex) { ROS_ERROR("transform exception: %s", ex.what()); } } void generateColors(int colors_number, std::vector<cv::Vec3f>& colors) { for (unsigned int i = 0; i < colors_number; i++) { colors.push_back(cv::Vec3f( float(rand() % 256) / 255, float(rand() % 256) / 255, float(rand() % 256) / 255)); } } void fillChiMap(std::map<double, double>& chi_map, bool velocity_in_motion_term) { if (velocity_in_motion_term) // chi square values with state dimension = 4 { chi_map[0.5] = 3.357; chi_map[0.75] = 5.385; chi_map[0.8] = 5.989; chi_map[0.9] = 7.779; chi_map[0.95] = 9.488; chi_map[0.98] = 11.668; chi_map[0.99] = 13.277; chi_map[0.995] = 14.860; chi_map[0.998] = 16.924; chi_map[0.999] = 18.467; } else // chi square values with state dimension = 2 { chi_map[0.5] = 1.386; chi_map[0.75] = 2.773; chi_map[0.8] = 3.219; chi_map[0.9] = 4.605; chi_map[0.95] = 5.991; chi_map[0.98] = 7.824; chi_map[0.99] = 9.210; chi_map[0.995] = 10.597; chi_map[0.998] = 12.429; chi_map[0.999] = 13.816; } } void configCb(Config &config, uint32_t level) { tracker->setMinConfidenceForTrackInitialization (config.min_confidence_initialization); max_detection_delay = config.max_detection_delay; calibration_refinement = config.calibration_refinement; tracker->setSecBeforeOld (config.sec_before_old); tracker->setSecBeforeFake (config.sec_before_fake); tracker->setSecRemainNew (config.sec_remain_new); tracker->setDetectionsToValidate (config.detections_to_validate); tracker->setDetectorLikelihood (config.detector_likelihood); tracker->setLikelihoodWeights (config.detector_weight*chi_map[0.999]/18.467, config.motion_weight); // if (config.velocity_in_motion_term != velocity_in_motion_term) // { // // Take chi square values with regards to the state dimension: // fillChiMap(chi_map, config.velocity_in_motion_term); // // double position_variance = config.position_variance_weight*std::pow(2 * voxel_size, 2) / 12.0; // tracker->setVelocityInMotionTerm (config.velocity_in_motion_term, config.acceleration_variance, position_variance); // } // else // { if (config.acceleration_variance != acceleration_variance) { tracker->setAccelerationVariance (config.acceleration_variance); } if (config.position_variance_weight != position_variance_weight) { double position_variance = config.position_variance_weight*std::pow(2 * voxel_size, 2) / 12.0; tracker->setPositionVariance (position_varian
c++
code
20,000
3,982
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/block.h" #include "hash.h" #include "tinyformat.h" #include "utilstrencodings.h" #include "crypto/common.h" #include "chainparams.h" #include "consensus/params.h" #include "crypto/scrypt.h" #include "streams.h" uint256 CBlockHeader::GetHash(const Consensus::Params& params) const { int version; if (nHeight >= (uint32_t)params.XLCHeight) { version = PROTOCOL_VERSION; } else { version = PROTOCOL_VERSION | SERIALIZE_BLOCK_LEGACY; } CHashWriter writer(SER_GETHASH, version); ::Serialize(writer, *this); return writer.GetHash(); } uint256 CBlockHeader::GetHash() const { const Consensus::Params& consensusParams = Params().GetConsensus(); return GetHash(consensusParams); } uint256 CBlockHeader::GetPoWHash() const { int version; const Consensus::Params& params = Params().GetConsensus(); if (nHeight >= (uint32_t)params.XLCHeight) { version = PROTOCOL_VERSION; return GetHash();//hard fork; } else { version = PROTOCOL_VERSION | SERIALIZE_BLOCK_LEGACY; } CDataStream ss(SER_NETWORK,version); ss << *this; assert(ss.size()==80); uint256 thash; scrypt_1024_1_1_256(BEGIN(ss[0]), BEGIN(thash)); return thash; } std::string CBlock::ToString() const { std::stringstream s; s << strprintf("CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nHeight=%u, nTime=%u, nBits=%08x, nNonce=%s, vtx=%u)\n", GetHash().ToString(), nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nHeight, nTime, nBits, nNonce.GetHex(), vtx.size()); for (const auto& tx : vtx) { s << " " << tx->ToString() << "\n"; } return s.str(); }
c++
code
1,989
430
// Copyright 2016-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #ifndef JSONAPI_JSON_JSONDOCUMENT_HPP #define JSONAPI_JSON_JSONDOCUMENT_HPP #include <fs/File.hpp> #include <fs/Path.hpp> #include <var/StringView.hpp> #include "Json.hpp" namespace json { class JsonDocument : public api::ExecutionContext { public: enum class Flags { reject_duplicates = JSON_REJECT_DUPLICATES, disable_eof_check = JSON_DISABLE_EOF_CHECK, decode_any = JSON_DECODE_ANY, decode_int_as_real = JSON_DECODE_INT_AS_REAL, allow_null = JSON_ALLOW_NUL, indent1 = JSON_INDENT(1), indent2 = JSON_INDENT(2), indent3 = JSON_INDENT(3), indent4 = JSON_INDENT(4), indent5 = JSON_INDENT(5), indent6 = JSON_INDENT(6), indent7 = JSON_INDENT(7), indent8 = JSON_INDENT(8), compact = JSON_COMPACT, ensure_ascii = JSON_ENSURE_ASCII, encode_any = JSON_ENCODE_ANY, preserve_order = JSON_PRESERVE_ORDER, escape_slash = JSON_ESCAPE_SLASH, embed = JSON_EMBED }; JsonDocument &set_flags(Flags flags) { m_flags = flags; return *this; } Flags option_flags() const { return m_flags; } JsonValue load(const fs::FileObject &file); #if defined __link enum class IsXmlFlat { no, yes }; JsonValue from_xml_string(const char *xml, IsXmlFlat is_flat = IsXmlFlat::yes); JsonValue load_xml(const fs::FileObject &input, IsXmlFlat is_flat = IsXmlFlat::yes); #endif JsonValue from_string(const var::StringView json); var::String to_string(const JsonValue &value) const; var::String stringify(const JsonValue &value) const { return to_string(value); } JsonDocument &save(const JsonValue &value, const fs::FileObject &file); JsonDocument & save(const JsonValue &value, json_dump_callback_t callback, void *context); const JsonDocument & seek(const var::StringView path, const fs::FileObject &file) const; JsonDocument &seek(const var::StringView path, const fs::FileObject &file) { return API_CONST_CAST_SELF(JsonDocument, seek, path, file); } const JsonError &error() const { return m_error; } static bool is_valid(const fs::FileObject & file, printer::Printer *printer = nullptr); private: Flags m_flags = Flags::indent3; JsonError m_error; u32 json_flags() const { return static_cast<u32>(option_flags()); } static int write_file_data(const char *buffer, size_t buflen, void *data); static size_t read_file_data(void *buffer, size_t buflen, void *data); }; API_OR_NAMED_FLAGS_OPERATOR(JsonDocument, Flags) } // namespace json #endif // JSONAPI_JSON_JSONDOCUMENT_HPP
c++
code
2,617
497
/*==================================================================== Copyright(c) 2018 Adam Rankin 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. ====================================================================*/ // Local includes #include "pch.h" #include "Debug.h" #include "ModelRenderer.h" #include "Slice.h" #include "SliceRenderer.h" #include "TextRenderer.h" // STL includes #include <sstream> using namespace Windows::Foundation::Numerics; using namespace Windows::Media::SpeechRecognition; using namespace Windows::Perception::Spatial; using namespace Windows::UI::Input::Spatial; namespace HoloIntervention { //---------------------------------------------------------------------------- Debug::Debug(Rendering::SliceRenderer& sliceRenderer, const std::shared_ptr<DX::DeviceResources>& deviceResources) : m_textRenderer(std::make_unique<Rendering::TextRenderer>(deviceResources, 1920, 1080)) { m_textRenderer->SetFontSize(28); } //---------------------------------------------------------------------------- Debug::~Debug() { } //---------------------------------------------------------------------------- void Debug::RegisterVoiceCallbacks(Input::VoiceInputCallbackMap& callbackMap) { callbackMap[L"show debug"] = [this](SpeechRecognitionResult ^ result) { m_debugShowing = true; m_sliceEntry->SetVisible(m_debugShowing); std::lock_guard<std::mutex> guard(m_coordinateSystemModelLock); for (auto& entry : m_coordinateSystemModels) { entry.second.second->SetVisible(true); } }; callbackMap[L"hide debug"] = [this](SpeechRecognitionResult ^ result) { m_debugShowing = false; m_sliceEntry->SetVisible(m_debugShowing); std::lock_guard<std::mutex> guard(m_coordinateSystemModelLock); for (auto& entry : m_coordinateSystemModels) { entry.second.second->SetVisible(false); } }; callbackMap[L"lock debug"] = [this](SpeechRecognitionResult ^ result) { m_sliceEntry->SetHeadlocked(true); }; callbackMap[L"unlock debug"] = [this](SpeechRecognitionResult ^ result) { m_sliceEntry->ForceCurrentPose(m_sliceEntry->GetCurrentPose()); m_sliceEntry->SetHeadlocked(false); }; } //---------------------------------------------------------------------------- void Debug::Update(SpatialCoordinateSystem^ hmdCoordinateSystem) { if (m_sliceEntry == nullptr || !m_sliceEntry->GetVisible()) { return; } std::wstringstream wss; { std::lock_guard<std::mutex> guard(m_debugLock); for (auto& pair : m_debugValues) { wss << pair.first << L": " << pair.second << std::endl; } } m_textRenderer->RenderTextOffscreen(wss.str()); std::lock_guard<std::mutex> guard(m_coordinateSystemModelLock); for (auto& pair : m_coordinateSystemModels) { if (pair.second.first != nullptr) { auto result = pair.second.first->TryGetTransformTo(hmdCoordinateSystem); pair.second.second->SetDesiredPose(result->Value); } } } //---------------------------------------------------------------------------- void Debug::UpdateValue(const std::wstring& key, const std::wstring& value) { std::lock_guard<std::mutex> guard(m_debugLock); m_debugValues[key] = value; } //---------------------------------------------------------------------------- void Debug::UpdateValue(const std::wstring& key, const float2& value) { std::wstringstream wss; wss << value.x << L" " << value.y; std::lock_guard<std::mutex> guard(m_debugLock); m_debugValues[key] = wss.str(); } //---------------------------------------------------------------------------- void Debug::UpdateValue(const std::wstring& key, const float3& value) { std::wstringstream wss; wss << value.x << L" " << value.y << L" " << value.z; std::lock_guard<std::mutex> guard(m_debugLock); m_debugValues[key] = wss.str(); } //---------------------------------------------------------------------------- void Debug::UpdateValue(const std::wstring& key, const float4& value) { std::wstringstream wss; wss << value.x << L" " << value.y << L" " << value.z << L" " << value.w; std::lock_guard<std::mutex> guard(m_debugLock); m_debugValues[key] = wss.str(); } //---------------------------------------------------------------------------- void Debug::UpdateValue(const std::wstring& key, const float4x4& value) { std::wstringstream wss; wss << value.m11 << L" " << value.m12 << L" " << value.m13 << L" " << value.m14 << std::endl << value.m21 << L" " << value.m22 << L" " << value.m23 << L" " << value.m24 << std::endl << value.m31 << L" " << value.m32 << L" " << value.m33 << L" " << value.m34 << std::endl << value.m41 << L" " << value.m42 << L" " << value.m43 << L" " << value.m44; std::lock_guard<std::mutex> guard(m_debugLock); m_debugValues[key] = wss.str(); } //---------------------------------------------------------------------------- void Debug::UpdateValue(Platform::String^ key, Platform::String^ value) { UpdateValue(std::wstring(key->Data()), std::wstring(value->Data())); } //---------------------------------------------------------------------------- void Debug::UpdateValue(Platform::String^ key, const float2& value) { UpdateValue(std::wstring(key->Data()), value); } //---------------------------------------------------------------------------- void Debug::UpdateValue(Platform::String^ key, const float3& value) { UpdateValue(std::wstring(key->Data()), value); } //---------------------------------------------------------------------------- void Debug::UpdateValue(Platform::String^ key, const float4& value) { UpdateValue(std::wstring(key->Data()), value); } //---------------------------------------------------------------------------- void Debug::UpdateValue(Platform::String^ key, const float4x4& value) { UpdateValue(std::wstring(key->Data()), value); } //---------------------------------------------------------------------------- void Debug::UpdateCoordinateSystem(const std::wstring& key, const float4x4& value, SpatialCoordinateSystem^ coordinateSystem) { std::lock_guard<std::mutex> guard(m_coordinateSystemModelLock); if (m_coordinateSystemModels.find(key) == m_coordinateSystemModels.end()) { m_coordinateSystemModels[key] = CoordinateSystemEntry(nullptr, nullptr); m_modelRenderer->AddModelAsync(L"Debug\\CoordSystem").then([this, coordinateSystem, key, value](uint64 modelId) { auto entry = m_modelRenderer->GetModel(modelId); if (entry == nullptr) { LOG_ERROR("Unable to load coordinate system model."); return; } std::lock_guard<std::mutex> guard(m_coordinateSystemModelLock); entry->SetCurrentPose(value); entry->SetVisible(m_debugShowing); m_coordinateSystemModels[key] = CoordinateSystemEntry(coordinateSystem, entry); }); } else { if (coordinateSystem != nullptr) { m_coordinateSystemModels[key].first = coordinateSystem; } if (m_coordinateSystemModels[key].second != nullptr) { m_coordinateSystemModels[key].second->SetDesiredPose(value); } } } //---------------------------------------------------------------------------- void Debug::UpdateCoordinateSystem(const std::wstring& key, const float3& value, SpatialCoordinateSystem^ coordinateSystem) { UpdateCoordinateSystem(key, make_float4x4_translation(value), coordinateSystem); } //---------------------------------------------------------------------------- void Debug::UpdateCoordinateSystem(Platform::String^ key, const float4x4& value, SpatialCoordinateSystem^ coordinateSystem) { UpdateCoordinateSystem(std::wstring(key->Data()), value, coordinateSystem); } //---------------------------------------------------------------------------- void Debug::UpdateCoordinateSystem(Platform::String^ key, const float3& value, SpatialCoordinateSystem^ coordinateSystem) { UpdateCoordinateSystem(std::wstring(key->Data()), make_float4x4_translation(value), coordinateSystem); } //---------------------------------------------------------------------------- void Debug::SetModelRenderer(Rendering::ModelRenderer* modelRenderer) { m_modelRenderer = modelRenderer; m_componentReady = m_modelRenderer != nullptr && m_sliceRenderer != nullptr; } //---------------------------------------------------------------------------- void Debug::SetSliceRenderer(Rendering::SliceRenderer* sliceRenderer) { m_sliceRenderer = sliceRenderer; if (m_sliceEntry != nullptr) { m_sliceRenderer->RemoveSlice(m_sliceEntry->GetId()); m_sliceEntry = nullptr; } m_sliceRenderer->AddSliceAsync(m_textRenderer->GetTexture(), float4x4::identity(), true).then([this](uint64 entryId) { m_sliceEntry = m_sliceRenderer->GetSlice(entryId); m_sliceEntry->SetVisible(false); // off by default m_sliceEntry->SetScalingFactor(0.6f); m_componentReady = m_modelRenderer != nullptr && m_sliceRenderer != nullptr; }); } }
c++
code
10,308
2,745
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #ifndef OPENCV_GAPI_FLUID_BACKEND_HPP #define OPENCV_GAPI_FLUID_BACKEND_HPP // FIXME? Actually gfluidbackend.hpp is not included anywhere // and can be placed in gfluidbackend.cpp #include <opencv2/gapi/garg.hpp> #include <opencv2/gapi/gproto.hpp> #include <opencv2/gapi/fluid/gfluidkernel.hpp> #include <opencv2/gapi/fluid/gfluidbuffer.hpp> // PRIVATE STUFF! #include "backends/common/gbackend.hpp" #include "compiler/gislandmodel.hpp" namespace cv { namespace gimpl { struct FluidUnit { static const char *name() { return "FluidUnit"; } GFluidKernel k; gapi::fluid::BorderOpt border; int border_size; std::vector<int> line_consumption; double ratio; }; struct FluidUseOwnBorderBuffer { static const char *name() { return "FluidUseOwnBorderBuffer"; } bool use; }; struct FluidData { static const char *name() { return "FluidData"; } // FIXME: This structure starts looking like "FluidBuffer" meta int latency = 0; int skew = 0; int max_consumption = 1; int border_size = 0; int lpi_write = 1; bool internal = false; // is node internal to any fluid island gapi::fluid::BorderOpt border; }; struct agent_data_t { GFluidKernel::Kind kind; ade::NodeHandle nh; std::vector<int> in_buffer_ids; std::vector<int> out_buffer_ids; }; struct FluidAgent { public: virtual ~FluidAgent() = default; FluidAgent(const ade::Graph &g, ade::NodeHandle nh); GFluidKernel k; ade::NodeHandle op_handle; // FIXME: why it is here??// std::string op_name; // < 0 - not a buffer // >= 0 - a buffer with RcID std::vector<int> in_buffer_ids; std::vector<int> out_buffer_ids; cv::GArgs in_args; std::vector<cv::gapi::fluid::View> in_views; // sparce list of IN views std::vector<cv::gapi::fluid::Buffer*> out_buffers; // FIXME Current assumption is that outputs have EQUAL SIZES int m_outputLines = 0; int m_producedLines = 0; // Execution methods void reset(); bool canWork() const; bool canRead() const; bool canWrite() const; void doWork(); bool done() const; void debug(std::ostream& os); // FIXME: // refactor (implement a more solid replacement or // drop this method completely) virtual void setRatio(double ratio) = 0; private: // FIXME!!! // move to another class virtual int firstWindow(std::size_t inPort) const = 0; virtual std::pair<int,int> linesReadAndnextWindow(std::size_t inPort) const = 0; }; //helper data structure for accumulating graph traversal/analysis data struct FluidGraphInputData { std::vector<agent_data_t> m_agents_data; std::vector<std::size_t> m_scratch_users; std::unordered_map<int, std::size_t> m_id_map; // GMat id -> buffer idx map std::map<std::size_t, ade::NodeHandle> m_all_gmat_ids; std::size_t m_mat_count; }; //local helper function to traverse the graph once and pass the results to multiple instances of GFluidExecutable FluidGraphInputData fluidExtractInputDataFromGraph(const ade::Graph &m_g, const std::vector<ade::NodeHandle> &nodes); class GFluidExecutable final: public GIslandExecutable { GFluidExecutable(const GFluidExecutable&) = delete; // due std::unique_ptr in members list const ade::Graph &m_g; GModel::ConstGraph m_gm; std::vector<std::unique_ptr<FluidAgent>> m_agents; std::vector<cv::gapi::fluid::Buffer> m_buffers; std::vector<FluidAgent*> m_script; using Magazine = detail::magazine<cv::gapi::own::Scalar>; Magazine m_res; std::size_t m_num_int_buffers; // internal buffers counter (m_buffers - num_scratch) std::vector<std::size_t> m_scratch_users; std::unordered_map<int, std::size_t> m_id_map; // GMat id -> buffer idx map std::map<std::size_t, ade::NodeHandle> m_all_gmat_ids; void bindInArg (const RcDesc &rc, const GRunArg &arg); void bindOutArg(const RcDesc &rc, const GRunArgP &arg); void packArg (GArg &in_arg, const GArg &op_arg); void initBufferRois(std::vector<int>& readStarts, std::vector<cv::gapi::own::Rect>& rois, const std::vector<gapi::own::Rect> &out_rois); void makeReshape(const std::vector<cv::gapi::own::Rect>& out_rois); std::size_t total_buffers_size() const; public: virtual inline bool canReshape() const override { return true; } virtual void reshape(ade::Graph& g, const GCompileArgs& args) override; virtual void run(std::vector<InObj> &&input_objs, std::vector<OutObj> &&output_objs) override; void run(std::vector<InObj> &input_objs, std::vector<OutObj> &output_objs); GFluidExecutable(const ade::Graph &g, const FluidGraphInputData &graph_data, const std::vector<cv::gapi::own::Rect> &outputRois); }; class GParallelFluidExecutable final: public GIslandExecutable { GParallelFluidExecutable(const GParallelFluidExecutable&) = delete; // due std::unique_ptr in members list std::vector<std::unique_ptr<GFluidExecutable>> tiles; decltype(GFluidParallelFor::parallel_for) parallel_for; public: GParallelFluidExecutable(const ade::Graph &g, const FluidGraphInputData &graph_data, const std::vector<GFluidOutputRois> &parallelOutputRois, const decltype(parallel_for) &pfor); virtual inline bool canReshape() const override { return false; } virtual void reshape(ade::Graph& g, const GCompileArgs& args) override; virtual void run(std::vector<InObj> &&input_objs, std::vector<OutObj> &&output_objs) override; }; }} // cv::gimpl #endif // OPENCV_GAPI_FLUID_BACKEND_HPP
c++
code
6,181
1,267
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/dom_distiller/core/page_distiller.h" #include <map> #include "base/location.h" #include "base/message_loop/message_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "components/dom_distiller/core/distiller_page.h" #include "components/dom_distiller/core/distiller_url_fetcher.h" #include "grit/component_resources.h" #include "net/url_request/url_request_context_getter.h" #include "ui/base/resource/resource_bundle.h" #include "url/gurl.h" namespace dom_distiller { DistilledPageInfo::DistilledPageInfo() {} DistilledPageInfo::~DistilledPageInfo() {} PageDistiller::PageDistiller(const DistillerPageFactory& distiller_page_factory) : distiller_page_(distiller_page_factory.CreateDistillerPage(this).Pass()) { } PageDistiller::~PageDistiller() {} void PageDistiller::Init() { distiller_page_->Init(); } void PageDistiller::DistillPage(const GURL& url, const PageDistillerCallback& callback) { page_distiller_callback_ = callback; LoadURL(url); } void PageDistiller::LoadURL(const GURL& url) { distiller_page_->LoadURL(url); } void PageDistiller::OnLoadURLDone() { GetDistilledContent(); } void PageDistiller::GetDistilledContent() { std::string script = ResourceBundle::GetSharedInstance() .GetRawDataResource(IDR_DISTILLER_JS) .as_string(); distiller_page_->ExecuteJavaScript(script); } void PageDistiller::OnExecuteJavaScriptDone(const GURL& page_url, const base::Value* value) { scoped_ptr<DistilledPageInfo> page_info(new DistilledPageInfo()); std::string result; const base::ListValue* result_list = NULL; if (!value->GetAsList(&result_list)) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(page_distiller_callback_, base::Passed(&page_info), false)); } else { int i = 0; for (base::ListValue::const_iterator iter = result_list->begin(); iter != result_list->end(); ++iter, ++i) { std::string item; (*iter)->GetAsString(&item); // The JavaScript returns an array where the first element is the title, // the second element is the article content HTML, and the remaining // elements are image URLs referenced in the HTML. switch (i) { case 0: page_info->title = item; break; case 1: page_info->html = item; break; case 2: page_info->next_page_url = item; break; case 3: page_info->prev_page_url = item; break; default: page_info->image_urls.push_back(item); } } base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(page_distiller_callback_, base::Passed(&page_info), true)); } } } // namespace dom_distiller
c++
code
3,075
568
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/detail/overload.hpp> #include <eve/detail/abi.hpp> #include <eve/constant/half.hpp> #include <eve/function/fma.hpp> #include <eve/forward.hpp> #include <eve/detail/skeleton.hpp> #include <eve/concept/value.hpp> namespace eve::detail { template<real_scalar_value T, typename N> EVE_FORCEINLINE wide<T, N> average_(EVE_SUPPORTS(vmx_) , wide<T, N> const &v0 , wide<T, N> const &v1) noexcept requires ppc_abi<abi_t<T, N>> { if constexpr(integral_value<T> && sizeof(T) < 8) return vec_avg(v0.storage(), v1.storage()); else if constexpr(floating_value<T>) return fma(v0, half(eve::as(v0)), v1 * half(eve::as(v0))); else return map(average, v0, v1); } }
c++
code
1,165
202
#ifndef OPERATION_MANAGER_HPP #define OPERATION_MANAGER_HPP #include <map> #include <string> #include <functional> #include <boost/any.hpp> #include <boost/filesystem.hpp> #include <boost/python/import.hpp> #include <boost/python/raw_function.hpp> #include <boost/python/slice.hpp> #include <boost/shared_ptr.hpp> #include "operation_caller.hpp" namespace bp = boost::python; typedef boost::shared_ptr< std::vector< uint8_t > > serialized_t; void call_rule_engine( bp::object& _rc, const std::string& _name, std::vector< serialized_t >& _data ) { bp::list rule_arguments; for( size_t i = 0; i < _data.size(); ++i ) { PyObject* py_buf = PyBuffer_FromReadWriteMemory( &_data[i]->front(), _data[i]->size() * sizeof( uint8_t ) ); rule_arguments.append( bp::object(bp::handle<>(py_buf)) ); } bp::object rf = _rc.attr(_name.c_str()); rf( rule_arguments ); } void call_rule_engine( bp::object& _rc, const std::string& _name ) { bp::object rf = _rc.attr(_name.c_str()); rf( ); } template< typename T0 > void pack_serialized_parameters( std::vector< serialized_t >& _data, T0 _t0 ) { _data.push_back( serialize( std::forward<T0>(_t0) ) ); } template< typename T0, typename... types_t > void pack_serialized_parameters( std::vector< serialized_t >& _data, T0 _t0, types_t... _tn ) { _data.push_back( serialize( std::forward<T0>(_t0) ) ); pack_serialized_parameters( _data, std::forward<types_t>(_tn)... ); } class operation_manager { public: template< typename ret_t, typename... types_t> void add_operation( const std::string& _name, operation_caller<ret_t, types_t...> _operation ) { op_map_[ _name ] = _operation; } void add_operation( const std::string& _name, operation_caller<void,void> _operation ) { op_map_[ _name ] = _operation; } template< typename ret_t, typename... types_t> ret_t call( bp::object& _rc, const std::string& _name, types_t&&... _t ) { std::vector< serialized_t > data; pack_serialized_parameters( data, std::forward<types_t>(_t)... ); call_rule_engine( _rc, _name, data ); typedef operation_caller<ret_t, types_t...> caller_t; caller_t& fcn = boost::any_cast< caller_t& >( op_map_[ _name ] ); return fcn.call( std::forward<types_t>(_t)...); } template< typename ret_t > ret_t call( bp::object& _rc, const std::string& _name ) { call_rule_engine( _rc, _name ); typedef operation_caller<ret_t> caller_t; caller_t& fcn = boost::any_cast< caller_t& >( op_map_[ _name ] ); return fcn.call( ); } void call( bp::object& _rc, const std::string& _name ) { call_rule_engine( _rc, _name ); typedef operation_caller<void,void> caller_t; caller_t& fcn = boost::any_cast< caller_t& >( op_map_[ _name ] ); return fcn.call( ); } private: std::map<std::string,boost::any> op_map_; }; // class operation_manager #endif // OPERATION_MANAGER_HPP
c++
code
3,350
726
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <random> // template<class Engine, size_t k> // class shuffle_order_engine // result_type operator()(); #include <random> #include <cassert> template <class UIntType, UIntType Min, UIntType Max> class rand1 { public: // types typedef UIntType result_type; private: result_type x_; static_assert(Min < Max, "rand1 invalid parameters"); public: // Temporary work around for lack of constexpr static const result_type _Min = Min; static const result_type _Max = Max; static const/*expr*/ result_type min() {return Min;} static const/*expr*/ result_type max() {return Max;} explicit rand1(result_type sd = Min) : x_(sd) { if (x_ < Min) x_ = Min; if (x_ > Max) x_ = Max; } result_type operator()() { result_type r = x_; if (x_ < Max) ++x_; else x_ = Min; return r; } }; void test1() { typedef std::knuth_b E; E e; assert(e() == 152607844u); } void test2() { typedef rand1<unsigned long long, 0, 0xFFFFFFFFFFFFFFFFull> E0; typedef std::shuffle_order_engine<E0, 101> E; E e; e.discard(400); assert(e() == 501); } void test3() { typedef rand1<unsigned long long, 0, 0xFFFFFFFFFFFFFFFFull> E0; typedef std::shuffle_order_engine<E0, 100> E; E e; e.discard(400); assert(e() == 500); } int main() { test1(); test2(); test3(); }
c++
code
1,809
450
// Generated from /POI/java/org/apache/poi/ss/usermodel/ExcelStyleDateFormatter.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/text/fwd-POI.hpp> #include <java/util/fwd-POI.hpp> #include <org/apache/poi/ss/usermodel/fwd-POI.hpp> #include <java/text/SimpleDateFormat.hpp> struct default_init_tag; class poi::ss::usermodel::ExcelStyleDateFormatter : public ::java::text::SimpleDateFormat { public: typedef ::java::text::SimpleDateFormat super; static constexpr char16_t MMMMM_START_SYMBOL { u'\ue001' }; static constexpr char16_t MMMMM_TRUNCATE_SYMBOL { u'\ue002' }; static constexpr char16_t H_BRACKET_SYMBOL { u'\ue010' }; static constexpr char16_t HH_BRACKET_SYMBOL { u'\ue011' }; static constexpr char16_t M_BRACKET_SYMBOL { u'\ue012' }; static constexpr char16_t MM_BRACKET_SYMBOL { u'\ue013' }; static constexpr char16_t S_BRACKET_SYMBOL { u'\ue014' }; static constexpr char16_t SS_BRACKET_SYMBOL { u'\ue015' }; static constexpr char16_t L_BRACKET_SYMBOL { u'\ue016' }; static constexpr char16_t LL_BRACKET_SYMBOL { u'\ue017' }; private: static ::java::text::DecimalFormat* format1digit_; static ::java::text::DecimalFormat* format2digits_; static ::java::text::DecimalFormat* format3digit_; static ::java::text::DecimalFormat* format4digits_; double dateToBeFormatted { }; protected: void ctor(::java::lang::String* pattern); void ctor(::java::lang::String* pattern, ::java::text::DateFormatSymbols* formatSymbols); void ctor(::java::lang::String* pattern, ::java::util::Locale* locale); private: static ::java::lang::String* processFormatPattern(::java::lang::String* f); public: virtual void setDateToBeFormatted(double date); ::java::lang::StringBuffer* format(::java::util::Date* date, ::java::lang::StringBuffer* paramStringBuffer, ::java::text::FieldPosition* paramFieldPosition) override; bool equals(::java::lang::Object* o) override; int32_t hashCode() override; // Generated ExcelStyleDateFormatter(::java::lang::String* pattern); ExcelStyleDateFormatter(::java::lang::String* pattern, ::java::text::DateFormatSymbols* formatSymbols); ExcelStyleDateFormatter(::java::lang::String* pattern, ::java::util::Locale* locale); protected: ExcelStyleDateFormatter(const ::default_init_tag&); public: static ::java::lang::Class *class_(); static void clinit(); private: void init(); public: ::java::lang::String* format(::java::util::Date* date); ::java::lang::StringBuffer* format(::java::lang::Object* obj, ::java::lang::StringBuffer* toAppendTo, ::java::text::FieldPosition* fieldPosition); ::java::lang::String* format(::java::lang::Object* obj); private: static ::java::text::DecimalFormat*& format1digit(); static ::java::text::DecimalFormat*& format2digits(); static ::java::text::DecimalFormat*& format3digit(); static ::java::text::DecimalFormat*& format4digits(); virtual ::java::lang::Class* getClass0(); };
c++
code
3,045
727
#include <iostream> using namespace std; extern void agregarProducto (string descripcion, int cantidad, double precio); void producto(int opcion) { system("cls"); int opcionProducto = 0; switch (opcion) { case 1: { cout << " Bebidas Calientes " << endl; cout << " ******** "<< endl; cout << " 1 - Capuccino " << endl; cout << " 2 - Expresso " << endl; cout << " 3 - Granita " << endl; cout << endl; cout << " Ingrese una opcion "; cin >> opcionProducto; switch (opcionProducto) { case 1: agregarProducto ("1 - Capuccino - L 40.00", 1 , 40); break; case 2: agregarProducto ("1 - Expresso - L 30.00", 1 , 30); break; case 3: agregarProducto ("1 - granita - L 40.00", 1 , 40); break; default: { cout << " Opcion no valida "; return; break; } } cout << endl; cout << " Producto agregado " << endl << endl; system("pause"); break; } case 2: { cout << " Bebidas frias " << endl; cout << " ******** "<< endl; cout << " 1 - Jugo " << endl; cout << " 2 - pepsi " << endl; cout << " 3 - cocacola " << endl; cout << endl; cout << " Ingrese una opcion "; cin >> opcionProducto; switch (opcionProducto) { case 1: agregarProducto ("1 - Jugo - L 10.00", 1 , 10); break; case 2: agregarProducto ("1 - pepsi - L 30.00", 1 , 30); break; case 3: agregarProducto ("1 - cocacola - L 25.00", 1 , 25); break; default: { cout << " Opcion no valida "; return; break; } } cout << endl; cout << " Producto agregado " << endl << endl; system("pause"); break; } case 3: { cout << " Reposteria " << endl; cout << " ******** "<< endl; cout << " 1 - Pastel de chocolate " << endl; cout << " 2 - Pan " << endl; cout << " 3 - pie de manzana " << endl; cout << endl; cout << " Ingrese una opcion "; cin >> opcionProducto; switch (opcionProducto) { case 1: agregarProducto ("1 - Pastel de chocolate - L 150.00", 1 , 150); break; case 2: agregarProducto ("1 - Pan - L 20.00", 1 , 20); break; case 3: agregarProducto ("1 - pie de manzana - L 25.00", 1 , 55); break; default: { cout << " Opcion no valida "; return; break; } } cout << endl; cout << " Producto agregado " << endl << endl; system("pause"); break; }default: break; } }
c++
code
2,858
666
#include "supch.h" #include "engine/imgui/imgui_layer.h" #include "engine/core/app.h" #include <imgui.h> #include <examples/imgui_impl_glfw.h> #include <examples/imgui_impl_opengl3.h> //TEMP: #include <GLFW/glfw3.h> #include <glad/glad.h> #include <ImGuizmo.h> namespace susumu { ImGuiLayer::ImGuiLayer() : Layer("InGuiLayer") { } void ImGuiLayer::OnAttach() { SU_PROFILE_FUNCTION(); //Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport/Platform Windows const float fontSize = 15.5f; io.Fonts->AddFontFromFileTTF("assets/fonts/opensans/OpenSans-Bold.ttf", fontSize); io.FontDefault = io.Fonts->AddFontFromFileTTF("assets/fonts/opensans/OpenSans-Regular.ttf", fontSize); //Setup Dear ImGui style ImGui::StyleColorsDark(); ImGui::StyleColorsClassic(); // When viewports are enabled we tweak WindowRounding/WindowBg so // platform windows can look identical to regular ones. ImGuiStyle& style = ImGui::GetStyle(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { style.WindowRounding = 0.0f; style.Colors[ImGuiCol_WindowBg].w = 1.0f; } SetDarkThemeColors(); App& app = App::Get(); GLFWwindow* window = static_cast<GLFWwindow*>(app.GetWindow().GetNativeWindow()); //Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init("#version 410"); } void ImGuiLayer::OnDetach() { SU_PROFILE_FUNCTION(); ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); } void ImGuiLayer::OnEvent(Event& e) { if (m_BlockEvents) { ImGuiIO& io = ImGui::GetIO(); e.Handled |= e.IsInCategory(EventCategoryMouse) & io.WantCaptureMouse; e.Handled |= e.IsInCategory(EventCategoryKeyboard) & io.WantCaptureKeyboard; } } void ImGuiLayer::Begin() { SU_PROFILE_FUNCTION(); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGuizmo::BeginFrame(); } void ImGuiLayer::End() { SU_PROFILE_FUNCTION(); ImGuiIO& io = ImGui::GetIO(); App& app = App::Get(); io.DisplaySize = ImVec2((float)app.GetWindow().GetWidth(), (float)app.GetWindow().GetHeight()); // Rendering ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { GLFWwindow* backup_current_context = glfwGetCurrentContext(); ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(); glfwMakeContextCurrent(backup_current_context); } } void ImGuiLayer::SetDarkThemeColors() { auto& colors = ImGui::GetStyle().Colors; colors[ImGuiCol_WindowBg] = ImVec4{ 0.086f, 0.086f, 0.086f, 1.0f }; // Headers colors[ImGuiCol_Header] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f }; colors[ImGuiCol_HeaderHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f }; colors[ImGuiCol_HeaderActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f }; // Buttons colors[ImGuiCol_Button] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f }; colors[ImGuiCol_ButtonHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f }; colors[ImGuiCol_ButtonActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f }; // Frame BG colors[ImGuiCol_FrameBg] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f }; colors[ImGuiCol_FrameBgHovered] = ImVec4{ 0.3f, 0.305f, 0.31f, 1.0f }; colors[ImGuiCol_FrameBgActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f }; // Tabs colors[ImGuiCol_Tab] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f }; colors[ImGuiCol_TabHovered] = ImVec4{ 0.38f, 0.3805f, 0.381f, 1.0f }; colors[ImGuiCol_TabActive] = ImVec4{ 0.28f, 0.2805f, 0.281f, 1.0f }; colors[ImGuiCol_TabUnfocused] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f }; colors[ImGuiCol_TabUnfocusedActive] = ImVec4{ 0.2f, 0.205f, 0.21f, 1.0f }; // Title colors[ImGuiCol_TitleBg] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f }; colors[ImGuiCol_TitleBgActive] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f }; colors[ImGuiCol_TitleBgCollapsed] = ImVec4{ 0.15f, 0.1505f, 0.151f, 1.0f }; } }
c++
code
4,910
887
#include <iostream> #include <cfloat> #include <cassert> #include "bvh.hpp" BVH::BVH(std::vector<RTTriangle>* tris, SplitMode mode) { m_triangles = tris; m_mode = mode; // Setup references for building m_refs.resize(m_triangles->size()); for (int i = 0; i < m_triangles->size(); i++) { m_refs[i] = TriRef(i, (*m_triangles)[i]); } // Shared vector to avoid reallocations rightBoxes.resize(m_triangles->size()); BuildNode root(0, (U32)m_triangles->size() - 1, -1); m_build_nodes.push_back(root); nodes++; build(0, 0, 0.0f, 1.0f); // root, depth 0 printf("\rBVH builder: progress 100%%\n"); assert(m_build_nodes[0].rightChild != -1); assert(metrics.depth <= MaxDepth); assert(m_indices.size() == 0); if (metrics.depth > MaxDepth) std::cout << "WARN: BVH might not fit traversal stack! (" << metrics.depth << " > " << MaxDepth << ")" << std::endl; createIndexList(); createSmallNodes(); std::cout << "======================" << std::endl << ((m_mode == SplitMode::SAH) ? "SAH" : (m_mode == SplitMode::ObjectMedian) ? "Object Median" : (m_mode == SplitMode::SpatialMedian) ? "Spatial Median" : "Unknown") << std::endl << "Splits: " << metrics.splits << " (" << int(metrics.bad_splits / float(metrics.splits) * 100.0f) << "% bad)" << std::endl << "Depth: " << metrics.depth << std::endl << "Leaves: " << metrics.splits + 1 << std::endl << "======================" << std::endl; } BVH::BVH(std::vector<RTTriangle>* tris, const std::string filename) { m_triangles = tris; importFrom(filename); } AABB_t BVH::getSceneBounds(void) const { if (m_nodes.size() == 0) throw std::runtime_error("Cannot get scene bounds from uninitialized BVH"); return m_nodes[0].box; } void BVH::createSmallNodes() { m_nodes.clear(); for (BuildNode bn : m_build_nodes) { Node n; n.box = bn.box; n.parent = bn.parent; if (bn.rightChild == -1) { // leaf node n.iStart = bn.iStart; U32 sp = bn.spannedTris(); if (sp > std::numeric_limits<U8>::max()) throw std::runtime_error("Too many prims to fit into U8!"); n.nPrims = (U8)(sp); } else // interior node { n.rightChild = (U32)(bn.rightChild); } m_nodes.push_back(n); } std::cout << "Small node vector created" << std::endl; // Deallocate build node memory m_build_nodes.clear(); m_build_nodes.shrink_to_fit(); } void BVH::createIndexList() { m_indices.resize(m_refs.size()); for (int i = 0; i < m_refs.size(); i++) { m_indices[i] = m_refs[i].ind; } // No longer needed m_refs.clear(); m_refs.shrink_to_fit(); } std::vector<U32> importIndices(std::ifstream &in) { U32 size; read(in, size); std::vector<U32> vec(size); for (U32 i = 0; i < size; i++) { U32 ind; read(in, ind); vec[i] = ind; } // Return value optimization! return vec; } std::vector<Node> importNodes(std::ifstream &in) { U32 size; read(in, size); std::vector<Node> vec(size); for (U32 i = 0; i < size; i++) { Node n; fr::float3 bmin, bmax; read(in, bmin.x); read(in, bmin.y); read(in, bmin.z); read(in, bmax.x); read(in, bmax.y); read(in, bmax.z); n.box = AABB_t(bmin, bmax); read(in, n.iStart); read(in, n.parent); read(in, n.nPrims); vec[i] = n; } // Return value optimization! return vec; } void BVH::importFrom(const std::string filename) { std::ifstream infile(filename, std::ios::binary); m_indices = importIndices(infile); m_nodes = importNodes(infile); } void exportNode(std::ofstream &out, const Node &n) { // AABB fr::float3 bmin = n.box.min; fr::float3 bmax = n.box.max; write(out, bmin.x); write(out, bmin.y); write(out, bmin.z); write(out, bmax.x); write(out, bmax.y); write(out, bmax.z); // Parameters write(out, n.iStart); write(out, n.parent); write(out, n.nPrims); } /** Write BVH to file for later importing **/ void BVH::exportTo(const std::string filename) const { std::ofstream out(filename, std::ios::binary); if (out.good()) { // Index list write(out, (U32)m_indices.size()); for_each(m_indices.begin(), m_indices.end(), [&out](U32 index) { write(out, index); }); // Node list write(out, (U32)m_indices.size()); for_each(m_nodes.begin(), m_nodes.end(), [&out](const Node &n) { exportNode(out, n); }); } else { std::cout << "Could not create create file for BVH export!" << std::endl; } } // Too frequent printing is actually a bottleneck! void BVH::lazyPrintBuildStatus(F32 progress) { S32 percentage = S32(ceil(progress * 100.0f)); if (percentage > buildPercentage) { buildPercentage = percentage; printf("\rBVH builder: progress %d%%", percentage); } } void BVH::build(U32 nInd, U32 depth, F32 progressStart = 0.0f, F32 progressEnd = 1.0f) { lazyPrintBuildStatus(progressStart); m_build_nodes[nInd].computeBB(m_refs); metrics.depth = std::max(metrics.depth, depth); U32 elems = m_build_nodes[nInd].spannedTris(); if (elems > MaxLeafElems) { SplitInfo info; bool shouldSplit = partition(m_build_nodes[nInd], info); if (!shouldSplit) { // parent is cheaper (SAH) assert(elems <= std::numeric_limits<U8>::max()); return; } metrics.splits++; // Statistics for progress bar F32 progressMid = lerp(progressStart, progressEnd, (F32)(info.i - m_build_nodes[nInd].iStart) / (F32)(elems)); // Left child m_build_nodes.push_back(BuildNode(m_build_nodes[nInd].iStart, info.i, nInd)); nodes++; build(nodes - 1, depth + 1, progressStart, progressMid); // last pushed // Right child m_build_nodes.push_back(BuildNode(info.i + 1, m_build_nodes[nInd].iEnd, nInd)); m_build_nodes[nInd].rightChild = nodes++; build(nodes - 1, depth + 1, progressMid, progressEnd); } } bool BVH::partition(BuildNode &n, SplitInfo &split) { switch (m_mode) { case SplitMode::SAH: return sahSplit(n, split); break; case SplitMode::SpatialMedian: return spatialMedianSplit(n, split); break; case SplitMode::ObjectMedian: return objectMedianSplit(n, split); break; default: std::cout << "Selected split mode not implemented!" << std::endl; throw std::runtime_error("Selected split mode not implemented!"); break; } } void BVH::sortReferences(U32 s, U32 e, U32 dim) { auto start = m_refs.begin() + s; auto end = m_refs.begin() + e + 1; // Sort the range [s, e[ by triangle centroid //std::sort(start, end, [dim](TriRef &r1, TriRef &r2) { return r1.pos[dim] < r2.pos[dim]; }); std::sort(start, end, [dim](TriRef &r1, TriRef &r2) { F32 ca = r1.box.min[dim] + r1.box.max[dim]; F32 cb = r2.box.min[dim] + r2.box.max[dim]; return (ca < cb || (ca == cb && r1.ind < r2.ind)); }); } bool BVH::objectMedianSplit(BuildNode &n, SplitInfo &split) { return objectMedianSplit(n, n.box.maxDim(), split); } bool BVH::objectMedianSplit(BuildNode &n, U32 dim, SplitInfo &split) { sortReferences(n.iStart, n.iEnd, dim); split.i = n.iStart + n.spannedTris() / 2; return true; } // Use centroids bounds in spatial median split (reduces bad split amount) AABB_t BVH::centroudBounds(std::vector<TriRef>::const_iterator begin, std::vector<TriRef>::const_iterator end) const { AABB_t bounds; for (auto i = begin; i != end; i++) { bounds.min = vmin(bounds.min, i->pos); bounds.max = vmax(bounds.max, i->pos); } return bounds; } bool BVH::spatialMedianSplit(BuildNode &n, SplitInfo &info) { auto s = m_refs.begin() + n.iStart; auto e = m_refs.begin() + n.iEnd; AABB_t centroidBox = centroudBounds(s, e); U32 dim = centroidBox.maxDim(); F32 splitCoord = centroidBox.centroid()[dim]; // Partition the range [s, e[ auto it = std::partition(s, e, [dim, splitCoord](TriRef &r) { return r.pos[dim] < splitCoord; }); info.i = (U32)(it - m_refs.begin()); // Index of split point in index list (first elem. of second group) // Fix bad splits (use midpoint) if (info.i == n.iStart || info.i == n.iEnd) { metrics.bad_splits++; objectMedianSplit(n, info); } return true; } F32 BVH::sahCost(U32 N1, F32 area1, U32 N2, F32 area2, F32 area_root) const { F32 lcost = N1 * area1 / area_root; F32 rcost = N2 * area2 / area_root; return 2 * sahParams.costBox + sahParams.costTri * (lcost + rcost); } // lookup[n] = AABB with last n + 1 triangles void BVH::buildBoxLookup(BuildNode &n) { AABB_t box; for (U32 i = 0; i < n.spannedTris(); i++) { box.expand(m_refs[n.iEnd - i].box); rightBoxes[i] = box; } } bool BVH::sahSplit(BuildNode &n, SplitInfo &info) { F32 parentArea = n.box.area(); assert(parentArea > 0.0f); F32 parentCost = sahParams.costBox + n.spannedTris() * sahParams.costTri; // Loop over all three axes to find best split for (U32 dim = 0; dim < 3; dim++) { // Sort along axis sortReferences(n.iStart, n.iEnd, dim); // Create AABB lookup buildBoxLookup(n); AABB_t leftBox; U32 leftCount = 0; U32 spanSize = n.spannedTris(); // Try different split points along axis for (U32 s = n.iStart; s < n.iEnd; s++) // exclude last (all on left side) { leftBox.expand(m_refs[s].box); leftCount++; AABB_t &rightBox = rightBoxes[n.iEnd - s - 1]; F32 areaRight = rightBox.area(); F32 areaLeft = leftBox.area(); // New best split? F32 cost = sahCost(leftCount, areaLeft, spanSize - leftCount, areaRight, parentArea); if (cost < info.cost) { info.cost = cost; info.i = s; info.leftBounds = leftBox; info.rightBounds = rightBox; info.dim = dim; } } // END LOOP SPLIT POINTS } // END LOOP AXES assert(info.cost != FLT_MAX); assert(info.i > -1); // Worse than parent? if (info.cost > parentCost && n.spannedTris() < MaxLeafElems) return false; // Re-sort along best axis, if necessary if (info.dim != 2) sortReferences(n.iStart, n.iEnd, info.dim); // Fix indexing if only one triangle on either side if (info.i == n.iStart) { info.i++; metrics.bad_splits++; } else if (info.i == n.iEnd) { info.i--; metrics.bad_splits++; } return true; }
c++
code
9,975
2,945
/****************************************************************************** / AutoRename.cpp / / Copyright (c) 2009 Tim Payne (SWS), original code by Xenakios / / / 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 "stdafx.h" #include "../Breeder/BR_Util.h" #include "../SnM/SnM_Dlg.h" #include <WDL/localize/localize.h> #define LAST_AUTORENAME_STR_KEY "Last autorename string" using namespace std; vector<MediaItem_Take*> g_VecTakesToRename; vector<MediaItem_Take*> g_VecTakesToRenameTimeOrdered; int stringFindAndErase(string& str, const char* findStr) { string::size_type pos; pos = str.find(findStr); if (pos == string::npos) return -1; str.erase(pos, strlen(findStr)); return (int)pos; } string GetNewTakeNameFromFormatString(const char *formatString, MediaItem_Take *take, int takeNumber) { string newName = formatString; int pos; // Use "while" for everything to ensure multiples of the same tag are taken care of while((pos = stringFindAndErase(newName, "[takename]")) >= 0) { const char* name = (const char*)GetSetMediaItemTakeInfo(take, "P_NAME", NULL); if (name) newName.insert(pos, name); } while((pos = stringFindAndErase(newName, "[takenamenoext]")) >= 0) { const char* name = (const char*)GetSetMediaItemTakeInfo(take, "P_NAME", NULL); if (name) { char str[256]; lstrcpyn(str, name, 256); char* pExt = strrchr(str, '.'); if (pExt) *pExt = 0; newName.insert(pos, str); } } while((pos = stringFindAndErase(newName, "[trackname]")) >= 0) { const char* name = (const char*)GetSetMediaTrackInfo((MediaTrack*)GetSetMediaItemTakeInfo(take, "P_TRACK", NULL), "P_NAME", NULL); if (name) newName.insert(pos, name); } while((pos = stringFindAndErase(newName, "[foldername]")) >= 0) { MediaTrack* tr = (MediaTrack*)GetSetMediaTrackInfo((MediaTrack*)GetSetMediaItemTakeInfo(take, "P_TRACK", NULL), "P_PARTRACK", NULL); if (tr) { const char* name = (const char*)GetSetMediaTrackInfo(tr, "P_NAME", NULL); if (name) newName.insert(pos, name); } } while((pos = stringFindAndErase(newName, "[tracknum]")) >= 0) { char str[16]; sprintf(str, "%.2d", CSurf_TrackToID((MediaTrack*)GetSetMediaItemTakeInfo(take, "P_TRACK", NULL), false)); newName.insert(pos, str); } while((pos = stringFindAndErase(newName, "[GUID]")) >= 0) { char cGUID[64]; guidToString((GUID*)GetSetMediaItemTakeInfo(take, "GUID", NULL), cGUID); newName.insert(pos, cGUID); } while((pos = stringFindAndErase(newName, "[inctrackorder]")) >= 0 || (pos = stringFindAndErase(newName, "[inctimeorder]")) >= 0) { char str[16]; sprintf(str, "%.2d", takeNumber); newName.insert(pos, str); } return newName; } void UpdateSampleNameList(HWND hDlg, const char* formatString) { vector<MediaItem_Take*>* pTakes = &g_VecTakesToRename; bool bTimeOrder = false; if (strstr(formatString, "[inctimeorder]")) { bTimeOrder = true; pTakes = &g_VecTakesToRenameTimeOrdered; } ListView_DeleteAllItems(GetDlgItem(hDlg,IDC_AUTONAMEOUTPUT)); int trackItemCounter = 0; MediaTrack* trPrev = NULL; for (int i = 0; i < (int)pTakes->size();i++) { MediaTrack* tr = (MediaTrack*)GetSetMediaItemTakeInfo((*pTakes)[i], "P_TRACK", NULL); if (!bTimeOrder && tr != trPrev) { trackItemCounter = 0; trPrev = tr; } LVITEM item; item.mask = LVIF_TEXT; item.iItem = i; item.iSubItem = 0; item.pszText = (char*)GetSetMediaItemTakeInfo((*pTakes)[i], "P_NAME", NULL); ListView_InsertItem(GetDlgItem(hDlg, IDC_AUTONAMEOUTPUT), &item); string SampleName = GetNewTakeNameFromFormatString(formatString,(*pTakes)[i], trackItemCounter + 1); ListView_SetItemText(GetDlgItem(hDlg, IDC_AUTONAMEOUTPUT), i, 1, (char*)SampleName.c_str()); trackItemCounter++; } } typedef struct { string Description; string FormattingString; } t_autorenamepreset; vector<t_autorenamepreset> g_AutoNamePresets; void InitPresets() { char file[512]; FILE* f; snprintf(file, 512, "%s%cSWS-RenamePresets.txt", GetResourcePath(), PATH_SLASH_CHAR); if (!FileExists(file)) { // Generate defaults f = fopen(file, "w"); if (f) { char buf[512]; strcpy(buf, "Increasing suffix, track-by-track==[takename]-[inctrackorder]\n"); fwrite(buf, strlen(buf), 1, f); strcpy(buf, "Increasing suffix, time order across all tracks==[takename]-[inctimeorder]\n"); fwrite(buf, strlen(buf), 1, f); strcpy(buf, "Folder.Track.Increasing suffix==[foldername].[trackname].[inctrackorder]\n"); fwrite(buf, strlen(buf), 1, f); strcpy(buf, "Strip file extension==[takenamenoext]\n"); fwrite(buf, strlen(buf), 1, f); fclose(f); } } f = fopen(file, "r"); if (f) { g_AutoNamePresets.clear(); char buf[512]; while (fgets(buf, 512, f)) { char* pFormat = strstr(buf, "=="); if (pFormat) { *pFormat=0; pFormat += 2; int iFL = (int)strlen(pFormat); if (pFormat[iFL-1] == '\n') pFormat[iFL-1] = 0; if (buf[0] && pFormat[0]) { t_autorenamepreset preset; preset.Description = buf; preset.FormattingString = pFormat; g_AutoNamePresets.push_back(preset); } } } fclose(f); } } WDL_DLGRET AutoRenameDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { if (ThemeListViewInProc(hwnd, Message, lParam, GetDlgItem(hwnd,IDC_AUTONAMEOUTPUT), true)) return 1; if (INT_PTR r = SNM_HookThemeColorsMessage(hwnd, Message, wParam, lParam)) return r; switch(Message) { case WM_INITDIALOG: { WDL_UTF8_HookComboBox(GetDlgItem(hwnd,IDC_AUTONAMEPRESETS)); if (SWS_THEMING) SNM_ThemeListView(GetDlgItem(hwnd,IDC_AUTONAMEOUTPUT)); for (int i = 0; i < (int)g_AutoNamePresets.size(); i++) { // fill preset combobox SendMessage(GetDlgItem(hwnd,IDC_AUTONAMEPRESETS), CB_ADDSTRING, 0, (LPARAM)g_AutoNamePresets[i].Description.c_str()); SendMessage(GetDlgItem(hwnd,IDC_AUTONAMEPRESETS), CB_SETITEMDATA, i, (LPARAM)&g_AutoNamePresets[i].FormattingString); } char buf[500]; GetPrivateProfileString(SWS_INI, LAST_AUTORENAME_STR_KEY, "[trackname]-Take[inctrackorder]", buf, 500, get_ini_file()); SetDlgItemText(hwnd,IDC_EDIT1,buf); LVCOLUMN col; col.mask=LVCF_TEXT|LVCF_WIDTH; col.cx=242; col.pszText=(char*)__LOCALIZE("Current take name","sws_DLG_136"); ListView_InsertColumn(GetDlgItem(hwnd,IDC_AUTONAMEOUTPUT), 0 , &col); col.mask=LVCF_TEXT|LVCF_WIDTH; col.cx=242; col.pszText=(char*)__LOCALIZE("New take name","sws_DLG_136"); ListView_InsertColumn(GetDlgItem(hwnd,IDC_AUTONAMEOUTPUT), 1 , &col); UpdateSampleNameList(hwnd, buf); break; } case WM_COMMAND: { if (HIWORD(wParam) == EN_CHANGE && LOWORD(wParam) == IDC_EDIT1) { char buf[500]; GetDlgItemText(hwnd, IDC_EDIT1, buf, 500); UpdateSampleNameList(hwnd, buf); break; } if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == IDC_AUTONAMEPRESETS) { int comboIndex = (int)SendMessage(GetDlgItem(hwnd, IDC_AUTONAMEPRESETS), CB_GETCURSEL, 0, 0); if (comboIndex >= 0 && comboIndex < (int)g_AutoNamePresets.size()) { string* formattingString = (string*)SendMessage(GetDlgItem(hwnd,IDC_AUTONAMEPRESETS),CB_GETITEMDATA, comboIndex, 0); if (formattingString) SetDlgItemText(hwnd, IDC_EDIT1, formattingString->c_str()); } break; } switch(LOWORD(wParam)) { case IDCANCEL: EndDialog(hwnd, 0); break; case IDOK: { char buf[500]; GetDlgItemText(hwnd, IDC_EDIT1, buf, 500); WritePrivateProfileString(SWS_INI, LAST_AUTORENAME_STR_KEY, buf, get_ini_file()); // Do the work! string NewTakeName; MediaTrack* PrevTrack = NULL; int TrackItemCounter = 0; bool bTimeOrder = false; if (strstr(buf, "[inctimeorder]")) { g_VecTakesToRename = g_VecTakesToRenameTimeOrdered; bTimeOrder = true; } for (int i = 0; i < (int)g_VecTakesToRename.size(); i++) { NewTakeName.assign(""); MediaItem* CurItem = (MediaItem*)GetSetMediaItemTakeInfo(g_VecTakesToRename[i],"P_ITEM",NULL); MediaTrack* CurTrack = (MediaTrack*)GetSetMediaItemInfo(CurItem,"P_TRACK",NULL); if (!bTimeOrder && CurTrack != PrevTrack) { TrackItemCounter = 0; PrevTrack = CurTrack; } string SampleName = GetNewTakeNameFromFormatString(buf, g_VecTakesToRename[i], TrackItemCounter+1); GetSetMediaItemTakeInfo(g_VecTakesToRename[i], "P_NAME", (void*)SampleName.c_str()); TrackItemCounter++; } Undo_OnStateChangeEx(__LOCALIZE("Autorename takes","sws_undo"),4,-1); UpdateTimeline(); EndDialog(hwnd,0); break; } } } } return 0; } bool MyTakeSortByTimeFunc (MediaItem_Take *a,MediaItem_Take *b) { MediaItem *CompaItem; CompaItem=(MediaItem*)GetSetMediaItemTakeInfo(a,"P_ITEM",NULL); double ItemPosA=*(double*)GetSetMediaItemInfo(CompaItem,"D_POSITION",NULL); CompaItem=(MediaItem*)GetSetMediaItemTakeInfo(b,"P_ITEM",NULL); double ItemPosB=*(double*)GetSetMediaItemInfo(CompaItem,"D_POSITION",NULL); if (ItemPosA<ItemPosB) return true; return false; } void DoAutoRename(COMMAND_T*) { g_VecTakesToRename.clear(); const int cnt=CountSelectedMediaItems(NULL); for (int i = 0; i < cnt; i++) { MediaItem* item = GetSelectedMediaItem(NULL, i); MediaItem_Take* take = GetMediaItemTake(item, -1); if (take) g_VecTakesToRename.push_back(take); } if (g_VecTakesToRename.size() > 0) { g_VecTakesToRenameTimeOrdered.assign(g_VecTakesToRename.begin(),g_VecTakesToRename.end()); sort(g_VecTakesToRenameTimeOrdered.begin(),g_VecTakesToRenameTimeOrdered.end(),MyTakeSortByTimeFunc); InitPresets(); DialogBox(g_hInst, MAKEINTRESOURCE(IDD_AUTORENAMETAKES), g_hwndParent, (DLGPROC)AutoRenameDlgProc); } else MessageBox(g_hwndParent, __LOCALIZE("No selected item!","sws_mbox"), __LOCALIZE("Xenakios - Error","sws_mbox"), MB_OK); }
c++
code
10,939
2,719
/* see copyright notice in squirrel.h */ #include "sqpcheader.h" #ifndef NO_COMPILER #include <stdarg.h> #include <setjmp.h> #include "sqopcodes.h" #include "sqstring.h" #include "sqfuncproto.h" #include "sqcompiler.h" #include "sqfuncstate.h" #include "sqlexer.h" #include "sqvm.h" #include "sqtable.h" #define EXPR 1 #define OBJECT 2 #define BASE 3 #define LOCAL 4 #define OUTER 5 struct SQExpState { SQInteger etype; /* expr. type; one of EXPR, OBJECT, BASE, OUTER or LOCAL */ SQInteger epos; /* expr. location on stack; -1 for OBJECT and BASE */ bool donot_get; /* signal not to deref the next value */ }; #define MAX_COMPILER_ERROR_LEN 256 struct SQScope { SQInteger outers; SQInteger stacksize; }; #define BEGIN_SCOPE() SQScope __oldscope__ = _scope; \ _scope.outers = _fs->_outers; \ _scope.stacksize = _fs->GetStackSize(); #define RESOLVE_OUTERS() if(_fs->GetStackSize() != _scope.stacksize) { \ if(_fs->CountOuters(_scope.stacksize)) { \ _fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \ } \ } #define END_SCOPE_NO_CLOSE() { if(_fs->GetStackSize() != _scope.stacksize) { \ _fs->SetStackSize(_scope.stacksize); \ } \ _scope = __oldscope__; \ } #define END_SCOPE() { SQInteger oldouters = _fs->_outers;\ if(_fs->GetStackSize() != _scope.stacksize) { \ _fs->SetStackSize(_scope.stacksize); \ if(oldouters != _fs->_outers) { \ _fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \ } \ } \ _scope = __oldscope__; \ } #define BEGIN_BREAKBLE_BLOCK() SQInteger __nbreaks__=_fs->_unresolvedbreaks.size(); \ SQInteger __ncontinues__=_fs->_unresolvedcontinues.size(); \ _fs->_breaktargets.push_back(0);_fs->_continuetargets.push_back(0); #define END_BREAKBLE_BLOCK(continue_target) {__nbreaks__=_fs->_unresolvedbreaks.size()-__nbreaks__; \ __ncontinues__=_fs->_unresolvedcontinues.size()-__ncontinues__; \ if(__ncontinues__>0)ResolveContinues(_fs,__ncontinues__,continue_target); \ if(__nbreaks__>0)ResolveBreaks(_fs,__nbreaks__); \ _fs->_breaktargets.pop_back();_fs->_continuetargets.pop_back();} class SQCompiler { public: SQCompiler(SQVM *v, SQLEXREADFUNC rg, SQUserPointer up, const SQChar* sourcename, bool raiseerror, bool lineinfo) { _vm=v; _lex.Init(_ss(v), rg, up,ThrowError,this); _sourcename = SQString::Create(_ss(v), sourcename); _lineinfo = lineinfo;_raiseerror = raiseerror; _scope.outers = 0; _scope.stacksize = 0; _compilererror[0] = NULL; } static void ThrowError(void *ud, const SQChar *s) { SQCompiler *c = (SQCompiler *)ud; c->Error(s); } void Error(const SQChar *s, ...) { va_list vl; va_start(vl, s); scvsprintf(_compilererror, s, vl); va_end(vl); longjmp(_errorjmp,1); } void Lex(){ _token = _lex.Lex();} SQObject Expect(SQInteger tok) { if(_token != tok) { if(_token == TK_CONSTRUCTOR && tok == TK_IDENTIFIER) { //do nothing } else { const SQChar *etypename; if(tok > 255) { switch(tok) { case TK_IDENTIFIER: etypename = _SC("IDENTIFIER"); break; case TK_STRING_LITERAL: etypename = _SC("STRING_LITERAL"); break; case TK_INTEGER: etypename = _SC("INTEGER"); break; case TK_FLOAT: etypename = _SC("FLOAT"); break; default: etypename = _lex.Tok2Str(tok); } Error(_SC("expected '%s'"), etypename); } Error(_SC("expected '%c'"), tok); } } SQObjectPtr ret; switch(tok) { case TK_IDENTIFIER: ret = _fs->CreateString(_lex._svalue); break; case TK_STRING_LITERAL: ret = _fs->CreateString(_lex._svalue,_lex._longstr.size()-1); break; case TK_INTEGER: ret = SQObjectPtr(_lex._nvalue); break; case TK_FLOAT: ret = SQObjectPtr(_lex._fvalue); break; } Lex(); return ret; } bool IsEndOfStatement() { return ((_lex._prevtoken == _SC('\n')) || (_token == SQUIRREL_EOB) || (_token == _SC('}')) || (_token == _SC(';'))); } void OptionalSemicolon() { if(_token == _SC(';')) { Lex(); return; } if(!IsEndOfStatement()) { Error(_SC("end of statement expected (; or lf)")); } } void MoveIfCurrentTargetIsLocal() { SQInteger trg = _fs->TopTarget(); if(_fs->IsLocal(trg)) { trg = _fs->PopTarget(); //no pops the target and move it _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), trg); } } bool Compile(SQObjectPtr &o) { _debugline = 1; _debugop = 0; SQFuncState funcstate(_ss(_vm), NULL,ThrowError,this); funcstate._name = SQString::Create(_ss(_vm), _SC("main")); _fs = &funcstate; _fs->AddParameter(_fs->CreateString(_SC("this"))); _fs->AddParameter(_fs->CreateString(_SC("vargv"))); _fs->_varparams = true; _fs->_sourcename = _sourcename; SQInteger stacksize = _fs->GetStackSize(); if(setjmp(_errorjmp) == 0) { Lex(); while(_token > 0){ Statement(); if(_lex._prevtoken != _SC('}') && _lex._prevtoken != _SC(';')) OptionalSemicolon(); } _fs->SetStackSize(stacksize); _fs->AddLineInfos(_lex._currentline, _lineinfo, true); _fs->AddInstruction(_OP_RETURN, 0xFF); _fs->SetStackSize(0); o =_fs->BuildProto(); #ifdef _DEBUG_DUMP _fs->Dump(_funcproto(o)); #endif } else { if(_raiseerror && _ss(_vm)->_compilererrorhandler) { _ss(_vm)->_compilererrorhandler(_vm, _compilererror, type(_sourcename) == OT_STRING?_stringval(_sourcename):_SC("unknown"), _lex._currentline, _lex._currentcolumn); } _vm->_lasterror = SQString::Create(_ss(_vm), _compilererror, -1); return false; } return true; } void Statements() { while(_token != _SC('}') && _token != TK_DEFAULT && _token != TK_CASE) { Statement(); if(_lex._prevtoken != _SC('}') && _lex._prevtoken != _SC(';')) OptionalSemicolon(); } } void Statement(bool closeframe = true) { _fs->AddLineInfos(_lex._currentline, _lineinfo); switch(_token){ case _SC(';'): Lex(); break; case TK_IF: IfStatement(); break; case TK_WHILE: WhileStatement(); break; case TK_DO: DoWhileStatement(); break; case TK_FOR: ForStatement(); break; case TK_FOREACH: ForEachStatement(); break; case TK_SWITCH: SwitchStatement(); break; case TK_LOCAL: LocalDeclStatement(); break; case TK_RETURN: case TK_YIELD: { SQOpcode op; if(_token == TK_RETURN) { op = _OP_RETURN; } else { op = _OP_YIELD; _fs->_bgenerator = true; } Lex(); if(!IsEndOfStatement()) { SQInteger retexp = _fs->GetCurrentPos()+1; CommaExpr(); if(op == _OP_RETURN && _fs->_traps > 0) _fs->AddInstruction(_OP_POPTRAP, _fs->_traps, 0); _fs->_returnexp = retexp; _fs->AddInstruction(op, 1, _fs->PopTarget(),_fs->GetStackSize()); } else{ if(op == _OP_RETURN && _fs->_traps > 0) _fs->AddInstruction(_OP_POPTRAP, _fs->_traps ,0); _fs->_returnexp = -1; _fs->AddInstruction(op, 0xFF,0,_fs->GetStackSize()); } break;} case TK_BREAK: if(_fs->_breaktargets.size() <= 0)Error(_SC("'break' has to be in a loop block")); if(_fs->_breaktargets.top() > 0){ _fs->AddInstruction(_OP_POPTRAP, _fs->_breaktargets.top(), 0); } RESOLVE_OUTERS(); _fs->AddInstruction(_OP_JMP, 0, -1234); _fs->_unresolvedbreaks.push_back(_fs->GetCurrentPos()); Lex(); break; case TK_CONTINUE: if(_fs->_continuetargets.size() <= 0)Error(_SC("'continue' has to be in a loop block")); if(_fs->_continuetargets.top() > 0) { _fs->AddInstruction(_OP_POPTRAP, _fs->_continuetargets.top(), 0); } RESOLVE_OUTERS(); _fs->AddInstruction(_OP_JMP, 0, -1234); _fs->_unresolvedcontinues.push_back(_fs->GetCurrentPos()); Lex(); break; case TK_FUNCTION: FunctionStatement(); break; case TK_CLASS: ClassStatement(); break; case TK_ENUM: EnumStatement(); break; case _SC('{'):{ BEGIN_SCOPE(); Lex(); Statements(); Expect(_SC('}')); if(closeframe) { END_SCOPE(); } else { END_SCOPE_NO_CLOSE(); } } break; case TK_TRY: TryCatchStatement(); break; case TK_THROW: Lex(); CommaExpr(); _fs->AddInstruction(_OP_THROW, _fs->PopTarget()); break; case TK_CONST: { Lex(); SQObject id = Expect(TK_IDENTIFIER); Expect('='); SQObject val = ExpectScalar(); OptionalSemicolon(); SQTable *enums = _table(_ss(_vm)->_consts); SQObjectPtr strongid = id; enums->NewSlot(strongid,SQObjectPtr(val)); strongid.Null(); } break; default: CommaExpr(); _fs->DiscardTarget(); //_fs->PopTarget(); break; } _fs->SnoozeOpt(); } void EmitDerefOp(SQOpcode op) { SQInteger val = _fs->PopTarget(); SQInteger key = _fs->PopTarget(); SQInteger src = _fs->PopTarget(); _fs->AddInstruction(op,_fs->PushTarget(),src,key,val); } void Emit2ArgsOP(SQOpcode op, SQInteger p3 = 0) { SQInteger p2 = _fs->PopTarget(); //src in OP_GET SQInteger p1 = _fs->PopTarget(); //key in OP_GET _fs->AddInstruction(op,_fs->PushTarget(), p1, p2, p3); } void EmitCompoundArith(SQInteger tok, SQInteger etype, SQInteger pos) { /* Generate code depending on the expression type */ switch(etype) { case LOCAL:{ SQInteger p2 = _fs->PopTarget(); //src in OP_GET SQInteger p1 = _fs->PopTarget(); //key in OP_GET _fs->PushTarget(p1); //EmitCompArithLocal(tok, p1, p1, p2); _fs->AddInstruction(ChooseArithOpByToken(tok),p1, p2, p1, 0); _fs->SnoozeOpt(); } break; case OBJECT: case BASE: { SQInteger val = _fs->PopTarget(); SQInteger key = _fs->PopTarget(); SQInteger src = _fs->PopTarget(); /* _OP_COMPARITH mixes dest obj and source val in the arg1 */ _fs->AddInstruction(_OP_COMPARITH, _fs->PushTarget(), (src<<16)|val, key, ChooseCompArithCharByToken(tok)); } break; case OUTER: { SQInteger val = _fs->TopTarget(); SQInteger tmp = _fs->PushTarget(); _fs->AddInstruction(_OP_GETOUTER, tmp, pos); _fs->AddInstruction(ChooseArithOpByToken(tok), tmp, val, tmp, 0); _fs->AddInstruction(_OP_SETOUTER, tmp, pos, tmp); } break; } } void CommaExpr() { for(Expression();_token == ',';_fs->PopTarget(), Lex(), CommaExpr()); } void Expression() { SQExpState es = _es; _es.etype = EXPR; _es.epos = -1; _es.donot_get = false; LogicalOrExp(); switch(_token) { case _SC('='): case TK_NEWSLOT: case TK_MINUSEQ: case TK_PLUSEQ: case TK_MULEQ: case TK_DIVEQ: case TK_MODEQ:{ SQInteger op = _token; SQInteger ds = _es.etype; SQInteger pos = _es.epos; if(ds == EXPR) Error(_SC("can't assign expression")); else if(ds == BASE) Error(_SC("'base' cannot be modified")); Lex(); Expression(); switch(op){ case TK_NEWSLOT: if(ds == OBJECT || ds == BASE) EmitDerefOp(_OP_NEWSLOT); else //if _derefstate != DEREF_NO_DEREF && DEREF_FIELD so is the index of a local Error(_SC("can't 'create' a local slot")); break; case _SC('='): //ASSIGN switch(ds) { case LOCAL: { SQInteger src = _fs->PopTarget(); SQInteger dst = _fs->TopTarget(); _fs->AddInstruction(_OP_MOVE, dst, src); } break; case OBJECT: case BASE: EmitDerefOp(_OP_SET); break; case OUTER: { SQInteger src = _fs->PopTarget(); SQInteger dst = _fs->PushTarget(); _fs->AddInstruction(_OP_SETOUTER, dst, pos, src); } } break; case TK_MINUSEQ: case TK_PLUSEQ: case TK_MULEQ: case TK_DIVEQ: case TK_MODEQ: EmitCompoundArith(op, ds, pos); break; } } break; case _SC('?'): { Lex(); _fs->AddInstruction(_OP_JZ, _fs->PopTarget()); SQInteger jzpos = _fs->GetCurrentPos(); SQInteger trg = _fs->PushTarget(); Expression(); SQInteger first_exp = _fs->PopTarget(); if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp); SQInteger endfirstexp = _fs->GetCurrentPos(); _fs->AddInstruction(_OP_JMP, 0, 0); Expect(_SC(':')); SQInteger jmppos = _fs->GetCurrentPos(); Expression(); SQInteger second_exp = _fs->PopTarget(); if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp); _fs->SetIntructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos); _fs->SetIntructionParam(jzpos, 1, endfirstexp - jzpos + 1); _fs->SnoozeOpt(); } break; } _es = es; } template<typename T> void INVOKE_EXP(T f) { SQExpState es = _es; _es.etype = EXPR; _es.epos = -1; _es.donot_get = false; (this->*f)(); _es = es; } template<typename T> void BIN_EXP(SQOpcode op, T f,SQInteger op3 = 0) { Lex(); INVOKE_EXP(f); SQInteger op1 = _fs->PopTarget();SQInteger op2 = _fs->PopTarget(); _fs->AddInstruction(op, _fs->PushTarget(), op1, op2, op3); } void LogicalOrExp() { LogicalAndExp(); for(;;) if(_token == TK_OR) { SQInteger first_exp = _fs->PopTarget(); SQInteger trg = _fs->PushTarget(); _fs->AddInstruction(_OP_OR, trg, 0, first_exp, 0); SQInteger jpos = _fs->GetCurrentPos(); if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp); Lex(); INVOKE_EXP(&SQCompiler::LogicalOrExp); _fs->SnoozeOpt(); SQInteger second_exp = _fs->PopTarget(); if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp); _fs->SnoozeOpt(); _fs->SetIntructionParam(jpos, 1, (_fs->GetCurrentPos() - jpos)); break; }else return; } void LogicalAndExp() { BitwiseOrExp(); for(;;) switch(_token) { case TK_AND: { SQInteger first_exp = _fs->PopTarget(); SQInteger trg = _fs->PushTarget(); _fs->AddInstruction(_OP_AND, trg, 0, first_exp, 0); SQInteger jpos = _fs->GetCurrentPos(); if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp); Lex(); INVOKE_EXP(&SQCompiler::LogicalAndExp); _fs->SnoozeOpt(); SQInteger second_exp = _fs->PopTarget(); if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp); _fs->SnoozeOpt(); _fs->SetIntructionParam(jpos, 1, (_fs->GetCurrentPos() - jpos)); break; } default: return; } } void BitwiseOrExp() { BitwiseXorExp(); for(;;) if(_token == _SC('|')) {BIN_EXP(_OP_BITW, &SQCompiler::BitwiseXorExp,BW_OR); }else return; } void BitwiseXorExp() { BitwiseAndExp(); for(;;) if(_token == _SC('^')) {BIN_EXP(_OP_BITW, &SQCompiler::BitwiseAndExp,BW_XOR); }else return; } void BitwiseAndExp() { EqExp(); for(;;) if(_token == _SC('&')) {BIN_EXP(_OP_BITW, &SQCompiler::EqExp,BW_AND); }else return; } void EqExp() { CompExp(); for(;;) switch(_token) { case TK_EQ: BIN_EXP(_OP_EQ, &SQCompiler::CompExp); break; case TK_NE: BIN_EXP(_OP_NE, &SQCompiler::CompExp); break; case TK_3WAYSCMP: BIN_EXP(_OP_CMP, &SQCompiler::CompExp,CMP_3W); break; default: return; } } void CompExp() { ShiftExp(); for(;;) switch(_token) { case _SC('>'): BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_G); break; case _SC('<'): BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_L); break; case TK_GE: BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_GE); break; case TK_LE: BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_LE); break; case TK_IN: BIN_EXP(_OP_EXISTS, &SQCompiler::ShiftExp); break; case TK_INSTANCEOF: BIN_EXP(_OP_INSTANCEOF, &SQCompiler::ShiftExp); break; default: return; } } void ShiftExp() { PlusExp(); for(;;) switch(_token) { case TK_USHIFTR: BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_USHIFTR); break; case TK_SHIFTL: BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_SHIFTL); break; case TK_SHIFTR: BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_SHIFTR); break; default: return; } } SQOpcode ChooseArithOpByToken(SQInteger tok) { switch(tok) { case TK_PLUSEQ: case '+': return _OP_ADD; case TK_MINUSEQ: case '-': return _OP_SUB; case TK_MULEQ: case '*': return _OP_MUL; case TK_DIVEQ: case '/': return _OP_DIV; case TK_MODEQ: case '%': return _OP_MOD; default: assert(0); } return _OP_ADD; } SQInteger ChooseCompArithCharByToken(SQInteger tok) { SQInteger oper; switch(tok){ case TK_MINUSEQ: oper = '-'; break; case TK_PLUSEQ: oper = '+'; break; case TK_MULEQ: oper = '*'; break; case TK_DIVEQ: oper = '/'; break; case TK_MODEQ: oper = '%'; break; default: oper = 0; //shut up compiler assert(0); break; }; return oper; } void PlusExp() { MultExp(); for(;;) switch(_token) { case _SC('+'): case _SC('-'): BIN_EXP(ChooseArithOpByToken(_token), &SQCompiler::MultExp); break; default: return; } } void MultExp() { PrefixedExpr(); for(;;) switch(_token) { case _SC('*'): case _SC('/'): case _SC('%'): BIN_EXP(ChooseArithOpByToken(_token), &SQCompiler::PrefixedExpr); break; default: return; } } //if 'pos' != -1 the previous variable is a local variable void PrefixedExpr() { SQInteger pos = Factor(); for(;;) { switch(_token) { case _SC('.'): pos = -1; Lex(); _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(Expect(TK_IDENTIFIER))); if(_es.etype==BASE) { Emit2ArgsOP(_OP_GET); pos = _fs->TopTarget(); _es.etype = EXPR; _es.epos = pos; } else { if(NeedGet()) { Emit2ArgsOP(_OP_GET); } _es.etype = OBJECT; } break; case _SC('['): if(_lex._prevtoken == _SC('\n')) Error(_SC("cannot brake deref/or comma needed after [exp]=exp slot declaration")); Lex(); Expression(); Expect(_SC(']')); pos = -1; if(_es.etype==BASE) { Emit2ArgsOP(_OP_GET); pos = _fs->TopTarget(); _es.etype = EXPR; _es.epos = pos; } else { if(NeedGet()) { Emit2ArgsOP(_OP_GET); } _es.etype = OBJECT; } break; case TK_MINUSMINUS: case TK_PLUSPLUS: { if(IsEndOfStatement()) return; SQInteger diff = (_token==TK_MINUSMINUS) ? -1 : 1; Lex(); switch(_es.etype) { case EXPR: Error(_SC("can't '++' or '--' an expression")); break; case OBJECT: case BASE: Emit2ArgsOP(_OP_PINC, diff); break; case LOCAL: { SQInteger src = _fs->PopTarget(); _fs->AddInstruction(_OP_PINCL, _fs->PushTarget(), src, 0, diff); } break; case OUTER: { SQInteger tmp1 = _fs->PushTarget(); SQInteger tmp2 = _fs->PushTarget(); _fs->AddInstruction(_OP_GETOUTER, tmp2, _es.epos); _fs->AddInstruction(_OP_PINCL, tmp1, tmp2, 0, diff); _fs->AddInstruction(_OP_SETOUTER, tmp2, _es.epos, tmp2); _fs->PopTarget(); } } } return; break; case _SC('('): switch(_es.etype) { case OBJECT: { SQInteger key = _fs->PopTarget(); /* location of the key */ SQInteger table = _fs->PopTarget(); /* location of the object */ SQInteger closure = _fs->PushTarget(); /* location for the closure */ SQInteger ttarget = _fs->PushTarget(); /* location for 'this' pointer */ _fs->AddInstruction(_OP_PREPCALL, closure, key, table, ttarget); } break; case BASE: //Emit2ArgsOP(_OP_GET); _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0); break; case OUTER: _fs->AddInstruction(_OP_GETOUTER, _fs->PushTarget(), _es.epos); _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0); break; default: _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0); } _es.etype = EXPR; Lex(); FunctionCallArgs(); break; default: return; } } } SQInteger Factor() { _es.etype = EXPR; switch(_token) { case TK_STRING_LITERAL: _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_fs->CreateString(_lex._svalue,_lex._longstr.size()-1))); Lex(); break; case TK_BASE: Lex(); _fs->AddInstruction(_OP_GETBASE, _fs->PushTarget()); _es.etype = BASE; _es.epos = _fs->TopTarget(); return (_es.epos); break; case TK_IDENTIFIER: case TK_CONSTRUCTOR: case TK_THIS:{ SQObject id; SQObject constant; switch(_token) { case TK_IDENTIFIER: id = _fs->Crea
c++
code
20,000
5,130
#ifdef _WIN32 #define _CRT_SECURE_NO_WARNINGS // to use freopen #endif #include "Win32Service.h" #include <assert.h> #include <strsafe.h> #include <windows.h> #include "Daemon.h" #include "Log.h" DotNetService *DotNetService::s_service = NULL; BOOL DotNetService::isService() { BOOL bIsService = FALSE; HWINSTA hWinStation = GetProcessWindowStation(); if (hWinStation != NULL) { USEROBJECTFLAGS uof = { 0 }; if (GetUserObjectInformation(hWinStation, UOI_FLAGS, &uof, sizeof(USEROBJECTFLAGS), NULL) && ((uof.dwFlags & WSF_VISIBLE) == 0)) { bIsService = TRUE; } } return bIsService; } BOOL DotNetService::Run(DotNetService &service) { s_service = &service; SERVICE_TABLE_ENTRY serviceTable[] = { { service.m_name, ServiceMain }, { NULL, NULL } }; return StartServiceCtrlDispatcher(serviceTable); } void WINAPI DotNetService::ServiceMain(DWORD dwArgc, PSTR *pszArgv) { assert(s_service != NULL); s_service->m_statusHandle = RegisterServiceCtrlHandler( s_service->m_name, ServiceCtrlHandler); if (s_service->m_statusHandle == NULL) { throw GetLastError(); } s_service->Start(dwArgc, pszArgv); } void WINAPI DotNetService::ServiceCtrlHandler(DWORD dwCtrl) { switch (dwCtrl) { case SERVICE_CONTROL_STOP: s_service->Stop(); break; case SERVICE_CONTROL_PAUSE: s_service->Pause(); break; case SERVICE_CONTROL_CONTINUE: s_service->Continue(); break; case SERVICE_CONTROL_SHUTDOWN: s_service->Shutdown(); break; case SERVICE_CONTROL_INTERROGATE: break; default: break; } } DotNetService::DotNetService(PSTR pszServiceName, BOOL fCanStop, BOOL fCanShutdown, BOOL fCanPauseContinue) { m_name = (pszServiceName == NULL) ? (PSTR)"" : pszServiceName; m_statusHandle = NULL; m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; m_status.dwCurrentState = SERVICE_START_PENDING; DWORD dwControlsAccepted = 0; if (fCanStop) dwControlsAccepted |= SERVICE_ACCEPT_STOP; if (fCanShutdown) dwControlsAccepted |= SERVICE_ACCEPT_SHUTDOWN; if (fCanPauseContinue) dwControlsAccepted |= SERVICE_ACCEPT_PAUSE_CONTINUE; m_status.dwControlsAccepted = dwControlsAccepted; m_status.dwWin32ExitCode = NO_ERROR; m_status.dwServiceSpecificExitCode = 0; m_status.dwCheckPoint = 0; m_status.dwWaitHint = 0; m_fStopping = FALSE; // Create a manual-reset event that is not signaled at first to indicate // the stopped signal of the service. m_hStoppedEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (m_hStoppedEvent == NULL) { throw GetLastError(); } } DotNetService::~DotNetService(void) { if (m_hStoppedEvent) { CloseHandle(m_hStoppedEvent); m_hStoppedEvent = NULL; } } void DotNetService::Start(DWORD dwArgc, PSTR *pszArgv) { try { SetServiceStatus(SERVICE_START_PENDING); OnStart(dwArgc, pszArgv); SetServiceStatus(SERVICE_RUNNING); } catch (DWORD dwError) { LogPrint(eLogError, "Win32Service Start", dwError); SetServiceStatus(SERVICE_STOPPED, dwError); } catch (...) { LogPrint(eLogError, "Win32Service failed to start.", EVENTLOG_ERROR_TYPE); SetServiceStatus(SERVICE_STOPPED); } } void DotNetService::OnStart(DWORD dwArgc, PSTR *pszArgv) { LogPrint(eLogInfo, "Win32Service in OnStart", EVENTLOG_INFORMATION_TYPE); Daemon.start(); //dotnet::util::config::OptionParser(dwArgc, pszArgv); //dotnet::util::filesystem::ReadConfigFile(dotnet::util::config::mapArgs, dotnet::util::config::mapMultiArgs); //dotnet::context.OverrideNTCPAddress(dotnet::util::config::GetCharArg("-host", "127.0.0.1"), // dotnet::util::config::GetArg("-port", 17070)); _worker = new std::thread(std::bind(&DotNetService::WorkerThread, this)); } void DotNetService::WorkerThread() { while (!m_fStopping) { ::Sleep(1000); // Simulate some lengthy operations. } // Signal the stopped event. SetEvent(m_hStoppedEvent); } void DotNetService::Stop() { DWORD dwOriginalState = m_status.dwCurrentState; try { SetServiceStatus(SERVICE_STOP_PENDING); OnStop(); SetServiceStatus(SERVICE_STOPPED); } catch (DWORD dwError) { LogPrint(eLogInfo, "Win32Service Stop", dwError); SetServiceStatus(dwOriginalState); } catch (...) { LogPrint(eLogError, "Win32Service failed to stop.", EVENTLOG_ERROR_TYPE); SetServiceStatus(dwOriginalState); } } void DotNetService::OnStop() { // Log a service stop message to the Application log. LogPrint(eLogInfo, "Win32Service in OnStop", EVENTLOG_INFORMATION_TYPE); Daemon.stop(); m_fStopping = TRUE; if (WaitForSingleObject(m_hStoppedEvent, INFINITE) != WAIT_OBJECT_0) { throw GetLastError(); } _worker->join(); delete _worker; } void DotNetService::Pause() { try { SetServiceStatus(SERVICE_PAUSE_PENDING); OnPause(); SetServiceStatus(SERVICE_PAUSED); } catch (DWORD dwError) { LogPrint(eLogError, "Win32Service Pause", dwError); SetServiceStatus(SERVICE_RUNNING); } catch (...) { LogPrint(eLogError, "Win32Service failed to pause.", EVENTLOG_ERROR_TYPE); SetServiceStatus(SERVICE_RUNNING); } } void DotNetService::OnPause() { } void DotNetService::Continue() { try { SetServiceStatus(SERVICE_CONTINUE_PENDING); OnContinue(); SetServiceStatus(SERVICE_RUNNING); } catch (DWORD dwError) { LogPrint(eLogError, "Win32Service Continue", dwError); SetServiceStatus(SERVICE_PAUSED); } catch (...) { LogPrint(eLogError, "Win32Service failed to resume.", EVENTLOG_ERROR_TYPE); SetServiceStatus(SERVICE_PAUSED); } } void DotNetService::OnContinue() { } void DotNetService::Shutdown() { try { OnShutdown(); SetServiceStatus(SERVICE_STOPPED); } catch (DWORD dwError) { LogPrint(eLogError, "Win32Service Shutdown", dwError); } catch (...) { LogPrint(eLogError, "Win32Service failed to shut down.", EVENTLOG_ERROR_TYPE); } } void DotNetService::OnShutdown() { } void DotNetService::SetServiceStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint) { static DWORD dwCheckPoint = 1; m_status.dwCurrentState = dwCurrentState; m_status.dwWin32ExitCode = dwWin32ExitCode; m_status.dwWaitHint = dwWaitHint; m_status.dwCheckPoint = ((dwCurrentState == SERVICE_RUNNING) || (dwCurrentState == SERVICE_STOPPED)) ? 0 : dwCheckPoint++; ::SetServiceStatus(m_statusHandle, &m_status); } //***************************************************************************** void FreeHandles(SC_HANDLE schSCManager, SC_HANDLE schService) { if (schSCManager) { CloseServiceHandle(schSCManager); schSCManager = NULL; } if (schService) { CloseServiceHandle(schService); schService = NULL; } } void InstallService(PCSTR pszServiceName, PCSTR pszDisplayName, DWORD dwStartType, PCSTR pszDependencies, PCSTR pszAccount, PCSTR pszPassword) { printf("Try to install Win32Service (%s).\n", pszServiceName); char szPath[MAX_PATH]; SC_HANDLE schSCManager = NULL; SC_HANDLE schService = NULL; if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)) == 0) { printf("GetModuleFileName failed w/err 0x%08lx\n", GetLastError()); FreeHandles(schSCManager, schService); return; } char SvcOpt[] = " --daemon"; strncat(szPath, SvcOpt, strlen(SvcOpt)); // Open the local default service control manager database schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE); if (schSCManager == NULL) { printf("OpenSCManager failed w/err 0x%08lx\n", GetLastError()); FreeHandles(schSCManager, schService); return; } // Install the service into SCM by calling CreateService schService = CreateService( schSCManager, // SCManager database pszServiceName, // Name of service pszDisplayName, // Name to display SERVICE_QUERY_STATUS, // Desired access SERVICE_WIN32_OWN_PROCESS, // Service type dwStartType, // Service start type SERVICE_ERROR_NORMAL, // Error control type szPath, // Service's binary NULL, // No load ordering group NULL, // No tag identifier pszDependencies, // Dependencies pszAccount, // Service running account pszPassword // Password of the account ); if (schService == NULL) { printf("CreateService failed w/err 0x%08lx\n", GetLastError()); FreeHandles(schSCManager, schService); return; } printf("Win32Service is installed as %s.\n", pszServiceName); // Centralized cleanup for all allocated resources. FreeHandles(schSCManager, schService); } void UninstallService(PCSTR pszServiceName) { printf("Try to uninstall Win32Service (%s).\n", pszServiceName); SC_HANDLE schSCManager = NULL; SC_HANDLE schService = NULL; SERVICE_STATUS ssSvcStatus = {}; // Open the local default service control manager database schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); if (schSCManager == NULL) { printf("OpenSCManager failed w/err 0x%08lx\n", GetLastError()); FreeHandles(schSCManager, schService); return; } // Open the service with delete, stop, and query status permissions schService = OpenService(schSCManager, pszServiceName, SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE); if (schService == NULL) { printf("OpenService failed w/err 0x%08lx\n", GetLastError()); FreeHandles(schSCManager, schService); return; } // Try to stop the service if (ControlService(schService, SERVICE_CONTROL_STOP, &ssSvcStatus)) { printf("Stopping %s.\n", pszServiceName); Sleep(1000); while (QueryServiceStatus(schService, &ssSvcStatus)) { if (ssSvcStatus.dwCurrentState == SERVICE_STOP_PENDING) { printf("."); Sleep(1000); } else break; } if (ssSvcStatus.dwCurrentState == SERVICE_STOPPED) { printf("\n%s is stopped.\n", pszServiceName); } else { printf("\n%s failed to stop.\n", pszServiceName); } } // Now remove the service by calling DeleteService. if (!DeleteService(schService)) { printf("DeleteService failed w/err 0x%08lx\n", GetLastError()); FreeHandles(schSCManager, schService); return; } printf("%s is removed.\n", pszServiceName); // Centralized cleanup for all allocated resources. FreeHandles(schSCManager, schService); }
c++
code
10,161
2,048
// Copyright (c) 2022 Sapphire's Suite. All Rights Reserved. #pragma once #ifndef SAPPHIRE_LOGGER_CONSOLE_COLOR_THEME_GUARD #define SAPPHIRE_LOGGER_CONSOLE_COLOR_THEME_GUARD #include <SA/Logger/Log/LogLevel.hpp> #include <SA/Logger/Streams/Console/ConsoleColor.hpp> /** * \file ConsoleColorTheme.hpp * * \brief Define color theme by LogLevel. * * \ingroup Logger_Console * \{ */ namespace Sa { /** * Console color theme by LogLevel. */ struct ConsoleColorTheme { /// Normal level color. uint8_t normal = CslColor::Bright_FG; /// Infos level color. uint8_t infos = CslColor::Blue_FG | CslColor::Bright_FG; /// Warning level color. uint8_t warning = CslColor::Yellow_FG; /// Error level color. uint8_t error = CslColor::Red_FG | CslColor::Bright_FG; /// Assert Success level color. uint8_t assertSuccess = CslColor::Green_FG | CslColor::Bright_FG; /// Assert Failure level color. uint8_t assertFailure = CslColor::Magenta_FG | CslColor::Bright_FG; /** * \brief convert theme to data type. * * \returns this as uint8_t data. */ const uint8_t* Data() const; /** * \brief Set console color from log level using theme. * * \param[in] _lvl LogLevel to use for theme. */ void SetConsoleColorFromLevel(LogLevel _lvl) const; }; } /** \} */ #endif // GUARD
c++
code
1,320
255
// 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 <memory> #include "base/run_loop.h" #include "base/scoped_observation.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/extensions/extension_action_test_helper.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/toolbar_actions_model.h" #include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "components/sessions/content/session_tab_helper.h" #include "components/zoom/test/zoom_test_utils.h" #include "components/zoom/zoom_controller.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" #include "content/public/test/download_test_observer.h" #include "extensions/browser/extension_action.h" #include "extensions/browser/extension_action_manager.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_host_registry.h" #include "extensions/browser/extension_host_test_helper.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension.h" #include "extensions/common/extension_set.h" #include "extensions/common/mojom/view_type.mojom.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" #include "net/dns/mock_host_resolver.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/base/buildflags.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/scrollbar_size.h" #include "ui/views/widget/widget.h" #if defined(OS_WIN) #include "ui/views/win/hwnd_util.h" #endif namespace extensions { namespace { // Helper to ensure all extension hosts are destroyed during the test. If a host // is still alive, the Profile can not be destroyed in // BrowserProcessImpl::StartTearDown(). // TODO(tapted): The existence of this helper is probably a bug. Extension // hosts do not currently block shutdown the way a browser tab does. Maybe they // should. See http://crbug.com/729476. class PopupHostWatcher : public ExtensionHostRegistry::Observer { public: explicit PopupHostWatcher(content::BrowserContext* browser_context) { host_registry_observation_.Observe( ExtensionHostRegistry::Get(browser_context)); } PopupHostWatcher(const PopupHostWatcher&) = delete; PopupHostWatcher& operator=(const PopupHostWatcher&) = delete; void Wait() { if (created_ == destroyed_) return; base::RunLoop run_loop; quit_closure_ = run_loop.QuitClosure(); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, quit_closure_, TestTimeouts::action_timeout()); run_loop.Run(); } int created() const { return created_; } int destroyed() const { return destroyed_; } // ExtensionHostRegistry::Observer: void OnExtensionHostRenderProcessReady( content::BrowserContext* browser_context, ExtensionHost* host) override { // Only track lifetimes for popup window ExtensionHost instances. if (host->extension_host_type() != mojom::ViewType::kExtensionPopup) return; ++created_; QuitIfSatisfied(); } void OnExtensionHostDestroyed(content::BrowserContext* browser_context, ExtensionHost* host) override { // Only track lifetimes for popup window ExtensionHost instances. if (host->extension_host_type() != mojom::ViewType::kExtensionPopup) return; ++destroyed_; QuitIfSatisfied(); } private: void QuitIfSatisfied() { if (!quit_closure_.is_null() && created_ == destroyed_) quit_closure_.Run(); } base::RepeatingClosure quit_closure_; int created_ = 0; int destroyed_ = 0; base::ScopedObservation<ExtensionHostRegistry, ExtensionHostRegistry::Observer> host_registry_observation_{this}; }; // chrome.browserAction API tests that interact with the UI in such a way that // they cannot be run concurrently (i.e. openPopup API tests that require the // window be focused/active). class BrowserActionInteractiveTest : public ExtensionApiTest { public: BrowserActionInteractiveTest() {} BrowserActionInteractiveTest(const BrowserActionInteractiveTest&) = delete; BrowserActionInteractiveTest& operator=(const BrowserActionInteractiveTest&) = delete; ~BrowserActionInteractiveTest() override {} // BrowserTestBase: void SetUpOnMainThread() override { ExtensionApiTest::SetUpOnMainThread(); host_watcher_ = std::make_unique<PopupHostWatcher>(profile()); host_resolver()->AddRule("*", "127.0.0.1"); EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); } void TearDownOnMainThread() override { // Note browser windows are closed in PostRunTestOnMainThread(), which is // called after this. But relying on the window close to close the // extension host can cause flakes. See http://crbug.com/729476. // Waiting here requires individual tests to ensure their popup has closed. host_watcher_->Wait(); EXPECT_EQ(host_watcher_->created(), host_watcher_->destroyed()); // Destroy the PopupHostWatcher to ensure it stops watching the profile. host_watcher_.reset(); ExtensionApiTest::TearDownOnMainThread(); } protected: void EnsurePopupActive() { auto test_util = ExtensionActionTestHelper::Create(browser()); EXPECT_TRUE(test_util->HasPopup()); EXPECT_TRUE(test_util->WaitForPopup()); EXPECT_TRUE(test_util->HasPopup()); } // Open an extension popup via the chrome.browserAction.openPopup API. // If |will_reply| is true, then the listener is responsible for having a // test message listener that replies to the extension. Otherwise, this // method will create a listener and reply to the extension before returning // to avoid leaking an API function while waiting for a reply. void OpenPopupViaAPI(bool will_reply) { // Setup the notification observer to wait for the popup to finish loading. content::WindowedNotificationObserver frame_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); std::unique_ptr<ExtensionTestMessageListener> listener; if (!will_reply) listener = std::make_unique<ExtensionTestMessageListener>("ready", false); // Show first popup in first window and expect it to have loaded. ASSERT_TRUE(RunExtensionTest("browser_action/open_popup", {.page_url = "open_popup_succeeds.html"})) << message_; if (listener) EXPECT_TRUE(listener->WaitUntilSatisfied()); frame_observer.Wait(); EnsurePopupActive(); } // Open an extension popup by clicking the browser action button associated // with `id`. content::WebContents* OpenPopupViaToolbar(const std::string& id) { EXPECT_FALSE(id.empty()); content::WindowedNotificationObserver popup_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); ExtensionActionTestHelper::Create(browser())->Press(id); popup_observer.Wait(); EnsurePopupActive(); const auto& source = static_cast<const content::Source<content::WebContents>&>( popup_observer.source()); return source.ptr(); } // Close the popup window directly. bool ClosePopup() { return ExtensionActionTestHelper::Create(browser())->HidePopup(); } // Trigger a focus loss to close the popup. void ClosePopupViaFocusLoss() { EXPECT_TRUE(ExtensionActionTestHelper::Create(browser())->HasPopup()); ExtensionHostTestHelper host_helper(profile()); #if defined(OS_MAC) // ClickOnView() in an inactive window is not robust on Mac. The click does // not guarantee window activation on trybots. So activate the browser // explicitly, thus causing the bubble to lose focus and dismiss itself. // This works because bubbles on Mac are always toplevel. EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); #else // Elsewhere, click on the omnibox. Note that with aura, the browser may be // "active" the entire time when the popup is not a toplevel window. It's // aura::Window::Focus() that determines where key events go in this case. ui_test_utils::ClickOnView(browser(), VIEW_ID_OMNIBOX); #endif // The window disappears immediately. EXPECT_FALSE(ExtensionActionTestHelper::Create(browser())->HasPopup()); // Wait for the notification to achieve a consistent state and verify that // the popup was properly torn down. host_helper.WaitForHostDestroyed(); base::RunLoop().RunUntilIdle(); } int num_popup_hosts_created() const { return host_watcher_->created(); } private: std::unique_ptr<PopupHostWatcher> host_watcher_; }; // Tests opening a popup using the chrome.browserAction.openPopup API. This test // opens a popup in the starting window, closes the popup, creates a new window // and opens a popup in the new window. Both popups should succeed in opening. // TODO(crbug.com/1233996): Test flaking frequently. IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, DISABLED_TestOpenPopup) { auto browserActionBar = ExtensionActionTestHelper::Create(browser()); // Setup extension message listener to wait for javascript to finish running. ExtensionTestMessageListener listener("ready", true); { OpenPopupViaAPI(true); EXPECT_TRUE(browserActionBar->HasPopup()); browserActionBar->HidePopup(); } EXPECT_TRUE(listener.WaitUntilSatisfied()); Browser* new_browser = NULL; { content::WindowedNotificationObserver frame_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); // Open a new window. new_browser = chrome::FindBrowserWithWebContents(browser()->OpenURL( content::OpenURLParams(GURL("about:blank"), content::Referrer(), WindowOpenDisposition::NEW_WINDOW, ui::PAGE_TRANSITION_TYPED, false))); // Pin the extension to test that it opens when the action is on the // toolbar. ToolbarActionsModel::Get(profile())->SetActionVisibility( last_loaded_extension_id(), true); frame_observer.Wait(); } EXPECT_TRUE(new_browser != NULL); ResultCatcher catcher; { content::WindowedNotificationObserver frame_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); // Show second popup in new window. listener.Reply("show another"); frame_observer.Wait(); EXPECT_TRUE(ExtensionActionTestHelper::Create(new_browser)->HasPopup()); } ASSERT_TRUE(catcher.GetNextResult()) << message_; ExtensionActionTestHelper::Create(new_browser)->HidePopup(); } // Tests opening a popup in an incognito window. IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, TestOpenPopupIncognito) { content::WindowedNotificationObserver frame_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); ASSERT_TRUE(RunExtensionTest( "browser_action/open_popup", {.page_url = "open_popup_succeeds.html", .open_in_incognito = true}, {.allow_in_incognito = true})) << message_; frame_observer.Wait(); // Non-Aura Linux uses a singleton for the popup, so it looks like all windows // have popups if there is any popup open. #if !((defined(OS_LINUX) || defined(OS_CHROMEOS)) && !defined(USE_AURA)) // Starting window does not have a popup. EXPECT_FALSE(ExtensionActionTestHelper::Create(browser())->HasPopup()); #endif // Incognito window should have a popup. auto test_util = ExtensionActionTestHelper::Create( BrowserList::GetInstance()->GetLastActive()); EXPECT_TRUE(test_util->HasPopup()); test_util->HidePopup(); } // Tests that an extension can open a popup in the last active incognito window // even from a background page with a non-incognito profile. // (crbug.com/448853) IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, TestOpenPopupIncognitoFromBackground) { const Extension* extension = LoadExtension(test_data_dir_.AppendASCII("browser_action") .AppendASCII("open_popup_background"), {.allow_in_incognito = true}); ASSERT_TRUE(extension); ExtensionTestMessageListener listener(false); listener.set_extension_id(extension->id()); Browser* incognito_browser = OpenURLOffTheRecord(profile(), GURL("chrome://newtab/")); EXPECT_TRUE(listener.WaitUntilSatisfied()); EXPECT_EQ(std::string("opened"), listener.message()); auto test_util = ExtensionActionTestHelper::Create(incognito_browser); EXPECT_TRUE(test_util->HasPopup()); test_util->HidePopup(); } // Tests if there is already a popup open (by a user click or otherwise), that // the openPopup API does not override it. IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, TestOpenPopupDoesNotCloseOtherPopups) { // Load a first extension that can open a popup. const Extension* first_extension = LoadExtension(test_data_dir_.AppendASCII("browser_action/popup")); ASSERT_TRUE(first_extension) << message_; ExtensionTestMessageListener listener("ready", true); // Load the test extension which will do nothing except notifyPass() to // return control here. ASSERT_TRUE(RunExtensionTest("browser_action/open_popup", {.page_url = "open_popup_fails.html"})) << message_; EXPECT_TRUE(listener.WaitUntilSatisfied()); // Open a popup with the first extension. OpenPopupViaToolbar(first_extension->id()); ResultCatcher catcher; // Now, try to open a popup with the second extension. It should fail since // there's an active popup. listener.Reply("show another"); ASSERT_TRUE(catcher.GetNextResult()) << message_; EXPECT_TRUE(ClosePopup()); } // Test that openPopup does not grant tab permissions like for browser action // clicks if the activeTab permission is set. IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, TestOpenPopupDoesNotGrantTabPermissions) { OpenPopupViaAPI(false); ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); ASSERT_FALSE(registry ->GetExtensionById(last_loaded_extension_id(), ExtensionRegistry::ENABLED) ->permissions_data() ->HasAPIPermissionForTab( sessions::SessionTabHelper::IdForTab( browser()->tab_strip_model()->GetActiveWebContents()) .id(), mojom::APIPermissionID::kTab)); EXPECT_TRUE(ClosePopup()); } // Test that the extension popup is closed when the browser window is focused. IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, FocusLossClosesPopup1) { OpenPopupViaAPI(false); ClosePopupViaFocusLoss(); } // Test that the extension popup is closed when the browser window is focused. IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, FocusLossClosesPopup2) { // Load a first extension that can open a popup. ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( "browser_action/popup"))); const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; OpenPopupViaToolbar(extension->id()); ClosePopupViaFocusLoss(); } // Test that the extension popup is closed on browser tab switches. IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, TabSwitchClosesPopup) { // Add a second tab to the browser and open an extension popup. chrome::NewTab(browser()); ASSERT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_EQ(browser()->tab_strip_model()->GetWebContentsAt(1), browser()->tab_strip_model()->GetActiveWebContents()); OpenPopupViaAPI(false); ExtensionHostTestHelper host_helper(profile()); // Change active tabs, the extension popup should close. browser()->tab_strip_model()->ActivateTabAt( 0, {TabStripModel::GestureType::kOther}); host_helper.WaitForHostDestroyed(); EXPECT_FALSE(ExtensionActionTestHelper::Create(browser())->HasPopup()); } IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, DeleteBrowserActionWithPopupOpen) { // First, we open a popup. OpenPopupViaAPI(false); auto browser_action_test_util = ExtensionActionTestHelper::Create(browser()); EXPECT_TRUE(browser_action_test_util->HasPopup()); // Then, find the extension that created it. content::WebContents* active_web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(active_web_contents); GURL url = active_web_contents->GetLastCommittedURL(); const Extension* extension = ExtensionRegistry::Get(browser()->profile())-> enabled_extensions().GetExtensionOrAppByURL(url); ASSERT_TRUE(extension); // Finally, uninstall the extension, which causes the view to be deleted and // the popup to go away. This should not crash. UninstallExtension(extension->id()); EXPECT_FALSE(browser_action_test_util->HasPopup()); } IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, PopupZoomsIndependently) { ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("browser_action/open_popup"))); const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; // Navigate to one of the extension's pages in a tab. ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), extension->GetResourceURL("popup.html"))); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); // Zoom the extension page in the tab. zoom::ZoomController* zoom_controller = zoom::ZoomController::FromWebContents(tab_contents); double tab_old_zoom_level = zoom_controller->GetZoomLevel(); double tab_new_zoom_level = tab_old_zoom_level + 1.0; zoom::ZoomController::ZoomChangedEventData zoom_change_data( tab_contents, tab_old_zoom_level, tab_new_zoom_level, zoom::ZoomController::ZOOM_MODE_DEFAULT, true); zoom::ZoomChangedWatcher zoom_change_watcher(tab_contents, zoom_change_data); zoom_controller->SetZoomLevel(tab_new_zoom_level); zoom_change_watcher.Wait(); // Open the extension's popup. ExtensionHostTestHelper host_helper(profile(), extension->id()); OpenPopupViaToolbar(extension->id()); ExtensionHost* extension_host = host_helper.WaitForRenderProcessReady(); ASSERT_TRUE(extension_host); content::WebContents* popup_contents = extension_host->host_contents(); // The popup should not use the per-origin zoom level that was set by zooming // the tab. const double default_zoom_level = content::HostZoomMap::GetForWebContents(popup_contents) ->GetDefaultZoomLevel(); double popup_zoom_level = content::HostZoomMap::GetZoomLevel(popup_contents); EXPECT_TRUE(blink::PageZoomValuesEqual(popup_zoom_level, default_zoom_level)) << popup_zoom_level << " vs " << default_zoom_level; // Preventing the use
c++
code
20,000
3,459
/** * Copyright (c) 2014, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav_log.cc */ #include "config.h" #include <time.h> #include <ctype.h> #include <fcntl.h> #include <stdio.h> #include <assert.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <libgen.h> #include <pthread.h> #include <sys/resource.h> #ifdef HAVE_EXECINFO_H #include <execinfo.h> #endif #include <sys/types.h> #include <sys/time.h> #include <sys/utsname.h> #include <sys/wait.h> #include <sys/param.h> #include <thread> #ifdef HAVE_PCRE_H #include <pcre.h> #elif HAVE_PCRE_PCRE_H #include <pcre/pcre.h> #else #error "pcre.h not found?" #endif #if defined HAVE_NCURSESW_CURSES_H # include <ncursesw/termcap.h> # include <ncursesw/curses.h> #elif defined HAVE_NCURSESW_H # include <termcap.h> # include <ncursesw.h> #elif defined HAVE_NCURSES_CURSES_H # include <ncurses/termcap.h> # include <ncurses/curses.h> #elif defined HAVE_NCURSES_H # include <termcap.h> # include <ncurses.h> #elif defined HAVE_CURSES_H # include <termcap.h> # include <curses.h> #else # error "SysV or X/Open-compatible Curses header file required" #endif #include "lnav_log.hh" #include "pthreadpp.hh" #include "enum_util.hh" static const size_t BUFFER_SIZE = 256 * 1024; static const size_t MAX_LOG_LINE_SIZE = 2048; static const char *CRASH_MSG = "\n" "\n" "==== GURU MEDITATION ====\n" "Unfortunately, lnav has crashed, sorry for the inconvenience.\n" "\n" "You can help improve lnav by sending the following file to " PACKAGE_BUGREPORT " :\n" " %s\n" "=========================\n"; nonstd::optional<FILE *> lnav_log_file; lnav_log_level_t lnav_log_level = lnav_log_level_t::DEBUG; const char *lnav_log_crash_dir; nonstd::optional<const struct termios *> lnav_log_orig_termios; static pthread_mutex_t lnav_log_mutex = PTHREAD_MUTEX_INITIALIZER; log_state_dumper::log_state_list log_state_dumper::DUMPER_LIST; log_crash_recoverer::log_crash_list log_crash_recoverer::CRASH_LIST; static struct { size_t lr_length; off_t lr_frag_start; off_t lr_frag_end; char lr_data[BUFFER_SIZE]; } log_ring = { 0, BUFFER_SIZE, 0, }; static const char *LEVEL_NAMES[] = { "T", "D", "I", "W", "E", }; static char *log_alloc() { off_t data_end = log_ring.lr_length + MAX_LOG_LINE_SIZE; if (data_end >= (off_t)BUFFER_SIZE) { const char *new_start = &log_ring.lr_data[MAX_LOG_LINE_SIZE]; new_start = (const char *)memchr( new_start, '\n', log_ring.lr_length - MAX_LOG_LINE_SIZE); log_ring.lr_frag_start = new_start - log_ring.lr_data; log_ring.lr_frag_end = log_ring.lr_length; log_ring.lr_length = 0; assert(log_ring.lr_frag_start >= 0); assert(log_ring.lr_frag_start <= (off_t)BUFFER_SIZE); } else if (data_end >= log_ring.lr_frag_start) { const char *new_start = &log_ring.lr_data[log_ring.lr_frag_start]; new_start = (const char *)memchr( new_start, '\n', log_ring.lr_frag_end - log_ring.lr_frag_start); assert(new_start != nullptr); log_ring.lr_frag_start = new_start - log_ring.lr_data; assert(log_ring.lr_frag_start >= 0); assert(log_ring.lr_frag_start <= (off_t)BUFFER_SIZE); } return &log_ring.lr_data[log_ring.lr_length]; } void log_argv(int argc, char *argv[]) { const char *log_path = getenv("LNAV_LOG_PATH"); if (log_path != nullptr) { lnav_log_file = fopen(log_path, "a"); } log_info("argv[%d] =", argc); for (int lpc = 0; lpc < argc; lpc++) { log_info(" [%d] = %s", lpc, argv[lpc]); } } void log_host_info() { char cwd[MAXPATHLEN]; const char *jittarget; struct utsname un; struct rusage ru; int pcre_jit; uname(&un); pcre_config(PCRE_CONFIG_JIT, &pcre_jit); pcre_config(PCRE_CONFIG_JITTARGET, &jittarget); log_info("uname:"); log_info(" sysname=%s", un.sysname); log_info(" nodename=%s", un.nodename); log_info(" machine=%s", un.machine); log_info(" release=%s", un.release); log_info(" version=%s", un.version); log_info("PCRE:"); log_info(" jit=%d", pcre_jit); log_info(" jittarget=%s", jittarget); log_info("Environment:"); log_info(" HOME=%s", getenv("HOME")); log_info(" XDG_CONFIG_HOME=%s", getenv("XDG_CONFIG_HOME")); log_info(" LANG=%s", getenv("LANG")); log_info(" PATH=%s", getenv("PATH")); log_info(" TERM=%s", getenv("TERM")); log_info(" TZ=%s", getenv("TZ")); log_info("Process:"); log_info(" pid=%d", getpid()); log_info(" ppid=%d", getppid()); log_info(" pgrp=%d", getpgrp()); log_info(" uid=%d", getuid()); log_info(" gid=%d", getgid()); log_info(" euid=%d", geteuid()); log_info(" egid=%d", getegid()); if (getcwd(cwd, sizeof(cwd)) == nullptr) { log_info(" ERROR: getcwd failed"); } else { log_info(" cwd=%s", cwd); } log_info("Executable:"); log_info(" version=%s", VCS_PACKAGE_STRING); getrusage(RUSAGE_SELF, &ru); log_rusage(lnav_log_level_t::INFO, ru); } void log_rusage_raw(enum lnav_log_level_t level, const char *src_file, int line_number, const struct rusage &ru) { log_msg(level, src_file, line_number, "rusage:"); log_msg(level, src_file, line_number, " utime=%d.%06d", ru.ru_utime.tv_sec, ru.ru_utime.tv_usec); log_msg(level, src_file, line_number, " stime=%d.%06d", ru.ru_stime.tv_sec, ru.ru_stime.tv_usec); log_msg(level, src_file, line_number, " maxrss=%ld", ru.ru_maxrss); log_msg(level, src_file, line_number, " ixrss=%ld", ru.ru_ixrss); log_msg(level, src_file, line_number, " idrss=%ld", ru.ru_idrss); log_msg(level, src_file, line_number, " isrss=%ld", ru.ru_isrss); log_msg(level, src_file, line_number, " minflt=%ld", ru.ru_minflt); log_msg(level, src_file, line_number, " majflt=%ld", ru.ru_majflt); log_msg(level, src_file, line_number, " nswap=%ld", ru.ru_nswap); log_msg(level, src_file, line_number, " inblock=%ld", ru.ru_inblock); log_msg(level, src_file, line_number, " oublock=%ld", ru.ru_oublock); log_msg(level, src_file, line_number, " msgsnd=%ld", ru.ru_msgsnd); log_msg(level, src_file, line_number, " msgrcv=%ld", ru.ru_msgrcv); log_msg(level, src_file, line_number, " nsignals=%ld", ru.ru_nsignals); log_msg(level, src_file, line_number, " nvcsw=%ld", ru.ru_nvcsw); log_msg(level, src_file, line_number, " nivcsw=%ld", ru.ru_nivcsw); } void log_msg(lnav_log_level_t level, const char *src_file, int line_number, const char *fmt, ...) { struct timeval curr_time; struct tm localtm; ssize_t prefix_size; va_list args; ssize_t rc; if (level < lnav_log_level) { return; } mutex_guard mg(lnav_log_mutex); va_start(args, fmt); gettimeofday(&curr_time, nullptr); localtime_r(&curr_time.tv_sec, &localtm); auto line = log_alloc(); prefix_size = snprintf( line, MAX_LOG_LINE_SIZE, "%4d-%02d-%02dT%02d:%02d:%02d.%03d %s %s:%d ", localtm.tm_year + 1900, localtm.tm_mon + 1, localtm.tm_mday, localtm.tm_hour, localtm.tm_min, localtm.tm_sec, (int)(curr_time.tv_usec / 1000), LEVEL_NAMES[to_underlying(level)], basename((char *)src_file), line_number); rc = vsnprintf(&line[prefix_size], MAX_LOG_LINE_SIZE - prefix_size, fmt, args); if (rc >= (ssize_t)(MAX_LOG_LINE_SIZE - prefix_size)) { rc = MAX_LOG_LINE_SIZE - prefix_size - 1; } line[prefix_size + rc] = '\n'; log_ring.lr_length += prefix_size + rc + 1; lnav_log_file | [&](auto file) { fwrite(line, 1, prefix_size + rc + 1, file); fflush(file); }; va_end(args); } void log_msg_extra(const char *fmt, ...) { mutex_guard mg(lnav_log_mutex); va_list args; va_start(args, fmt); auto line = log_alloc(); auto rc = vsnprintf(line, MAX_LOG_LINE_SIZE - 1, fmt, args); log_ring.lr_length += rc; lnav_log_file | [&](auto file) { fwrite(line, 1, rc, file); fflush(file); }; va_end(args); } void log_msg_extra_complete() { mutex_guard mg(lnav_log_mutex); auto line = log_alloc(); line[0] = '\n'; log_ring.lr_length += 1; lnav_log_file | [&](auto file) { fwrite(line, 1, 1, file); fflush(file); }; } #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-result" static void sigabrt(int sig) { char crash_path[1024], latest_crash_path[1024]; int fd, frame_count; void *frames[128]; struct tm localtm; time_t curr_time; if (lnav_log_crash_dir == nullptr) { printf("%*s", (int) log_ring.lr_length, log_ring.lr_data); return; } log_error("Received signal: %d", sig); #ifdef HAVE_EXECINFO_H frame_count = backtrace(frames, 128); #endif curr_time = time(nullptr); localtime_r(&curr_time, &localtm); snprintf(crash_path, sizeof(crash_path), "%s/crash-%4d-%02d-%02d-%02d-%02d-%02d.%d.log", lnav_log_crash_dir, localtm.tm_year + 1900, localtm.tm_mon + 1, localtm.tm_mday, localtm.tm_hour, localtm.tm_min, localtm.tm_sec, getpid()); snprintf(latest_crash_path, sizeof(latest_crash_path), "%s/latest-crash.log", lnav_log_crash_dir); if ((fd = open(crash_path, O_CREAT|O_TRUNC|O_WRONLY, 0600)) != -1) { if (log_ring.lr_frag_start < (off_t)BUFFER_SIZE) { (void)write(fd, &log_ring.lr_data[log_ring.lr_frag_start], log_ring.lr_frag_end - log_ring.lr_frag_start); } (void)write(fd, log_ring.lr_data, log_ring.lr_length); #ifdef HAVE_EXECINFO_H backtrace_symbols_fd(frames, frame_count, fd); #endif log_ring.lr_length = 0; log_ring.lr_frag_start = BUFFER_SIZE; log_ring.lr_frag_end = 0; log_host_info(); { log_state_dumper *lsd; for (lsd = LIST_FIRST(&log_state_dumper::DUMPER_LIST.lsl_list); lsd != nullptr; lsd = LIST_NEXT(lsd, lsd_link)) { lsd->log_state(); } } if (log_ring.lr_frag_start < (off_t)BUFFER_SIZE) { write(fd, &log_ring.lr_data[log_ring.lr_frag_start], log_ring.lr_frag_end - log_ring.lr_frag_start); } write(fd, log_ring.lr_data, log_ring.lr_length); close(fd); remove(latest_crash_path); symlink(crash_path, latest_crash_path); } lnav_log_orig_termios | [](auto termios) { { log_crash_recoverer *lcr; for (lcr = LIST_FIRST(&log_crash_recoverer::CRASH_LIST.lcl_list); lcr != nullptr; lcr = LIST_NEXT(lcr, lcr_link)) { lcr->log_crash_recover(); } } tcsetattr(STDOUT_FILENO, TCSAFLUSH, termios); dup2(STDOUT_FILENO, STDERR_FILENO); }; fprintf(stderr, CRASH_MSG, crash_path); #ifndef ATTACH_ON_SIGNAL if (isatty(STDIN_FILENO)) { char response; fprintf(stderr, "\nWould you like to attach a debugger? (y/N) "); fflush(stderr); if (scanf("%c", &response) > 0 && tolower(response) == 'y') { pid_t lnav_pid = getpid(); pid_t child_pid; switch ((child_pid = fork())) { case 0: { char pid_str[32]; snprintf(pid_str, sizeof(pid_str), "--pid=%d", lnav_pid); execlp("gdb", "gdb", pid_str, nullptr); snprintf(pid_str, sizeof(pid_str), "%d", lnav_pid); execlp("lldb", "lldb", "--attach-pid", pid_str, nullptr); fprintf(stderr, "Could not attach gdb or lldb, exiting.\n"); _exit(1); break; } case -1: { break; } default: { int status; while (wait(&status) < 0) { } break; } } } } #endif _exit(1); } #pragma GCC diagnostic pop void log_install_handlers() { signal(SIGABRT, sigabrt); signal(SIGSEGV, sigabrt); signal(SIGBUS, sigabrt); signal(SIGILL, sigabrt); signal(SIGFPE, sigabrt); } void log_abort() { sigabrt(SIGABRT); _exit(1); } void log_pipe_err(int fd) { std::thread reader([fd] () { char buffer[1024]; bool done = false; while (!done) { int rc = read(fd, buffer, sizeof(buffer)); switch (rc) { case -1: case 0: done = true; break; default: while (buffer[rc - 1] == '\n' || buffer[rc - 1] == '\r') { rc -= 1; } log_error("%.*s", rc, buffer); break; } } close(fd); }); reader.detach(); }
c++
code
14,779
3,225
// Copyright (c) 2014-2016 The Dash developers // Copyright (c) 2016-2017 The PIVX developers // Copyright (c) 2021 The Retrex developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "spork.h" #include "base58.h" #include "key.h" #include "main.h" #include "masternode-budget.h" #include "net.h" #include "protocol.h" #include "sync.h" #include "sporkdb.h" #include "util.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; class CSporkMessage; class CSporkManager; CSporkManager sporkManager; std::map<uint256, CSporkMessage> mapSporks; std::map<int, CSporkMessage> mapSporksActive; // Retrex: on startup load spork values from previous session if they exist in the sporkDB void LoadSporksFromDB() { for (int i = SPORK_START; i <= SPORK_END; ++i) { // Since not all spork IDs are in use, we have to exclude undefined IDs std::string strSpork = sporkManager.GetSporkNameByID(i); if (strSpork == "Unknown") continue; // attempt to read spork from sporkDB CSporkMessage spork; if (!pSporkDB->ReadSpork(i, spork)) { LogPrintf("%s : no previous value for %s found in database\n", __func__, strSpork); continue; } // add spork to memory mapSporks[spork.GetHash()] = spork; mapSporksActive[spork.nSporkID] = spork; std::time_t result = spork.nValue; // If SPORK Value is greater than 1,000,000 assume it's actually a Date and then convert to a more readable format if (spork.nValue > 1000000) { LogPrintf("%s : loaded spork %s with value %d : %s", __func__, sporkManager.GetSporkNameByID(spork.nSporkID), spork.nValue, std::ctime(&result)); } else { LogPrintf("%s : loaded spork %s with value %d\n", __func__, sporkManager.GetSporkNameByID(spork.nSporkID), spork.nValue); } } } void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (fLiteMode) return; //disable all obfuscation/masternode related functionality if (strCommand == "spork") { //LogPrintf("ProcessSpork::spork\n"); CDataStream vMsg(vRecv); CSporkMessage spork; vRecv >> spork; if (chainActive.Tip() == NULL) return; // Ignore spork messages about unknown/deleted sporks std::string strSpork = sporkManager.GetSporkNameByID(spork.nSporkID); if (strSpork == "Unknown") return; uint256 hash = spork.GetHash(); if (mapSporksActive.count(spork.nSporkID)) { if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) { if (fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight); return; } else { if (fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight); } } LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight); if (!sporkManager.CheckSignature(spork)) { LogPrintf("spork - invalid signature\n"); Misbehaving(pfrom->GetId(), 100); return; } mapSporks[hash] = spork; mapSporksActive[spork.nSporkID] = spork; sporkManager.Relay(spork); // Retrex: add to spork database. pSporkDB->WriteSpork(spork.nSporkID, spork); } if (strCommand == "getsporks") { std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin(); while (it != mapSporksActive.end()) { pfrom->PushMessage("spork", it->second); it++; } } } // grab the value of the spork on the network, or the default int64_t GetSporkValue(int nSporkID) { int64_t r = -1; if (mapSporksActive.count(nSporkID)) { r = mapSporksActive[nSporkID].nValue; } else { if (nSporkID == SPORK_2_SWIFTTX) r = SPORK_2_SWIFTTX_DEFAULT; if (nSporkID == SPORK_3_SWIFTTX_BLOCK_FILTERING) r = SPORK_3_SWIFTTX_BLOCK_FILTERING_DEFAULT; if (nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT; if (nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT; if (nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT; if (nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT; if (nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT; if (nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT; if (nSporkID == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) r = SPORK_14_NEW_PROTOCOL_ENFORCEMENT_DEFAULT; if (nSporkID == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) r = SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2_DEFAULT; if (nSporkID == SPORK_16_ZEROCOIN_MAINTENANCE_MODE) r = SPORK_16_ZEROCOIN_MAINTENANCE_MODE_DEFAULT; if (nSporkID == SPORK_17_NEW_PROTOCOL_TARGETTIME) r = SPORK_17_NEW_PROTOCOL_TARGETTIME_DEFAULT; if (r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID); } return r; } // grab the spork value, and see if it's off bool IsSporkActive(int nSporkID) { int64_t r = GetSporkValue(nSporkID); if (r == -1) return false; return r < GetTime(); } void ReprocessBlocks(int nBlocks) { std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin(); while (it != mapRejectedBlocks.end()) { //use a window twice as large as is usual for the nBlocks we want to reset if ((*it).second > GetTime() - (nBlocks * 60 * 5)) { BlockMap::iterator mi = mapBlockIndex.find((*it).first); if (mi != mapBlockIndex.end() && (*mi).second) { LOCK(cs_main); CBlockIndex* pindex = (*mi).second; LogPrintf("ReprocessBlocks - %s\n", (*it).first.ToString()); CValidationState state; ReconsiderBlock(state, pindex); } } ++it; } CValidationState state; { LOCK(cs_main); DisconnectBlocksAndReprocess(nBlocks); } if (state.IsValid()) { ActivateBestChain(state); } } bool CSporkManager::CheckSignature(CSporkMessage& spork) { //note: need to investigate why this is failing std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned); CPubKey pubkeynew(ParseHex(Params().SporkKey())); std::string errorMessage = ""; if (obfuScationSigner.VerifyMessage(pubkeynew, spork.vchSig, strMessage, errorMessage)) { return true; } return false; } bool CSporkManager::Sign(CSporkMessage& spork) { std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned); CKey key2; CPubKey pubkey2; std::string errorMessage = ""; if (!obfuScationSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2)) { LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage); return false; } if (!obfuScationSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) { LogPrintf("CMasternodePayments::Sign - Sign message failed"); return false; } if (!obfuScationSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) { LogPrintf("CMasternodePayments::Sign - Verify message failed"); return false; } return true; } bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue) { CSporkMessage msg; msg.nSporkID = nSporkID; msg.nValue = nValue; msg.nTimeSigned = GetTime(); if (Sign(msg)) { Relay(msg); mapSporks[msg.GetHash()] = msg; mapSporksActive[nSporkID] = msg; return true; } return false; } void CSporkManager::Relay(CSporkMessage& msg) { CInv inv(MSG_SPORK, msg.GetHash()); RelayInv(inv); } bool CSporkManager::SetPrivKey(std::string strPrivKey) { CSporkMessage msg; // Test signing successful, proceed strMasterPrivKey = strPrivKey; Sign(msg); if (CheckSignature(msg)) { LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n"); return true; } else { return false; } } int CSporkManager::GetSporkIDByName(std::string strName) { if (strName == "SPORK_2_SWIFTTX") return SPORK_2_SWIFTTX; if (strName == "SPORK_3_SWIFTTX_BLOCK_FILTERING") return SPORK_3_SWIFTTX_BLOCK_FILTERING; if (strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE; if (strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING; if (strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT; if (strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT; if (strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES; if (strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS; if (strName == "SPORK_14_NEW_PROTOCOL_ENFORCEMENT") return SPORK_14_NEW_PROTOCOL_ENFORCEMENT; if (strName == "SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2") return SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2; if (strName == "SPORK_16_ZEROCOIN_MAINTENANCE_MODE") return SPORK_16_ZEROCOIN_MAINTENANCE_MODE; if (strName == "SPORK_17_NEW_PROTOCOL_TARGETTIME") return SPORK_17_NEW_PROTOCOL_TARGETTIME; return -1; } std::string CSporkManager::GetSporkNameByID(int id) { if (id == SPORK_2_SWIFTTX) return "SPORK_2_SWIFTTX"; if (id == SPORK_3_SWIFTTX_BLOCK_FILTERING) return "SPORK_3_SWIFTTX_BLOCK_FILTERING"; if (id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE"; if (id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING"; if (id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"; if (id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT"; if (id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES"; if (id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS"; if (id == SPORK_14_NEW_PROTOCOL_ENFORCEMENT) return "SPORK_14_NEW_PROTOCOL_ENFORCEMENT"; if (id == SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) return "SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2"; if (id == SPORK_16_ZEROCOIN_MAINTENANCE_MODE) return "SPORK_16_ZEROCOIN_MAINTENANCE_MODE"; if (id == SPORK_17_NEW_PROTOCOL_TARGETTIME) return "SPORK_17_NEW_PROTOCOL_TARGETTIME"; return "Unknown"; }
c++
code
11,103
2,080
/* Copyright (c) 2021 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "graph/optimizer/rule/OptimizeTagIndexScanByFilterRule.h" #include "graph/context/QueryContext.h" #include "graph/optimizer/OptContext.h" #include "graph/optimizer/OptGroup.h" #include "graph/optimizer/OptimizerUtils.h" #include "graph/optimizer/rule/IndexScanRule.h" #include "graph/planner/plan/PlanNode.h" #include "graph/planner/plan/Scan.h" #include "graph/util/ExpressionUtils.h" using nebula::graph::Filter; using nebula::graph::OptimizerUtils; using nebula::graph::QueryContext; using nebula::graph::TagIndexFullScan; using nebula::graph::TagIndexPrefixScan; using nebula::graph::TagIndexRangeScan; using nebula::graph::TagIndexScan; using nebula::storage::cpp2::IndexColumnHint; using nebula::storage::cpp2::IndexQueryContext; using Kind = nebula::graph::PlanNode::Kind; using ExprKind = nebula::Expression::Kind; using TransformResult = nebula::opt::OptRule::TransformResult; namespace nebula { namespace opt { std::unique_ptr<OptRule> OptimizeTagIndexScanByFilterRule::kInstance = std::unique_ptr<OptimizeTagIndexScanByFilterRule>(new OptimizeTagIndexScanByFilterRule()); OptimizeTagIndexScanByFilterRule::OptimizeTagIndexScanByFilterRule() { RuleSet::DefaultRules().addRule(this); } const Pattern& OptimizeTagIndexScanByFilterRule::pattern() const { static Pattern pattern = Pattern::create(Kind::kFilter, {Pattern::create(Kind::kTagIndexFullScan)}); return pattern; } // Match 2 kinds of expressions: // // 1. Relational expr. If it is an IN expr, its list MUST have only 1 element, so it could always be // transformed to an relEQ expr. i.g. A in [B] => A == B // It the list has more than 1 element, the expr will be matched with UnionAllIndexScanBaseRule. // // 2. Logical AND expr. If the AND expr contains an operand that is an IN expr, the label attribute // in the IN expr SHOULD NOT have a valid index, otherwise the expression should be matched with // UnionAllIndexScanBaseRule. bool OptimizeTagIndexScanByFilterRule::match(OptContext* ctx, const MatchedResult& matched) const { if (!OptRule::match(ctx, matched)) { return false; } auto filter = static_cast<const Filter*>(matched.planNode()); auto scan = static_cast<const TagIndexFullScan*>(matched.planNode({0, 0})); for (auto& ictx : scan->queryContext()) { if (ictx.column_hints_ref().is_set()) { return false; } } auto condition = filter->condition(); // Case1: relational expr if (condition->isRelExpr()) { auto relExpr = static_cast<const RelationalExpression*>(condition); // If the container in the IN expr has only 1 element, it will be converted to an relEQ // expr. If more than 1 element found in the container, UnionAllIndexScanBaseRule will be // applied. if (relExpr->kind() == ExprKind::kRelIn && relExpr->right()->isContainerExpr()) { auto ContainerOperands = graph::ExpressionUtils::getContainerExprOperands(relExpr->right()); return ContainerOperands.size() == 1; } return relExpr->left()->kind() == ExprKind::kTagProperty && relExpr->right()->kind() == ExprKind::kConstant; } // Case2: logical AND expr return condition->kind() == ExprKind::kLogicalAnd; } TagIndexScan* makeTagIndexScan(QueryContext* qctx, const TagIndexScan* scan, bool isPrefixScan) { TagIndexScan* tagScan = nullptr; if (isPrefixScan) { tagScan = TagIndexPrefixScan::make(qctx, nullptr, scan->tagName()); } else { tagScan = TagIndexRangeScan::make(qctx, nullptr, scan->tagName()); } OptimizerUtils::copyIndexScanData(scan, tagScan, qctx); return tagScan; } StatusOr<TransformResult> OptimizeTagIndexScanByFilterRule::transform( OptContext* ctx, const MatchedResult& matched) const { auto filter = static_cast<const Filter*>(matched.planNode()); auto scan = static_cast<const TagIndexFullScan*>(matched.planNode({0, 0})); auto metaClient = ctx->qctx()->getMetaClient(); auto status = metaClient->getTagIndexesFromCache(scan->space()); NG_RETURN_IF_ERROR(status); auto indexItems = std::move(status).value(); OptimizerUtils::eraseInvalidIndexItems(scan->schemaId(), &indexItems); auto condition = filter->condition(); auto conditionType = condition->kind(); Expression* transformedExpr = condition->clone(); // Stand alone IN expr with only 1 element in the list, no need to check index if (conditionType == ExprKind::kRelIn) { transformedExpr = graph::ExpressionUtils::rewriteInExpr(condition); DCHECK(transformedExpr->kind() == ExprKind::kRelEQ); } // case2: logical AND expr if (condition->kind() == ExprKind::kLogicalAnd) { for (auto& operand : static_cast<const LogicalExpression*>(condition)->operands()) { if (operand->kind() == ExprKind::kRelIn) { auto inExpr = static_cast<RelationalExpression*>(operand); // Do not apply this rule if the IN expr has a valid index or it has only 1 element in the // list if (static_cast<ListExpression*>(inExpr->right())->size() > 1) { return TransformResult::noTransform(); } else { transformedExpr = graph::ExpressionUtils::rewriteInExpr(condition); } if (OptimizerUtils::relExprHasIndex(inExpr, indexItems)) { return TransformResult::noTransform(); } } } } IndexQueryContext ictx; bool isPrefixScan = false; if (!OptimizerUtils::findOptimalIndex(transformedExpr, indexItems, &isPrefixScan, &ictx)) { return TransformResult::noTransform(); } std::vector<IndexQueryContext> idxCtxs = {ictx}; auto scanNode = makeTagIndexScan(ctx->qctx(), scan, isPrefixScan); scanNode->setIndexQueryContext(std::move(idxCtxs)); scanNode->setOutputVar(filter->outputVar()); scanNode->setColNames(filter->colNames()); auto filterGroup = matched.node->group(); auto optScanNode = OptGroupNode::create(ctx, scanNode, filterGroup); for (auto group : matched.dependencies[0].node->dependencies()) { optScanNode->dependsOn(group); } TransformResult result; result.newGroupNodes.emplace_back(optScanNode); result.eraseCurr = true; return result; } std::string OptimizeTagIndexScanByFilterRule::toString() const { return "OptimizeTagIndexScanByFilterRule"; } } // namespace opt } // namespace nebula
c++
code
6,368
1,395
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2018 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 "NFCGameServerToDBModule.h" #include "NFGameServerNet_ClientPlugin.h" #include "NFComm/NFMessageDefine/NFMsgDefine.h" #include "NFComm/NFPluginModule/NFINetClientModule.h" #include "NFComm/NFMessageDefine/NFProtocolDefine.hpp" bool NFCGameServerToDBModule::Init() { m_pNetClientModule = pPluginManager->FindModule<NFINetClientModule>(); m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>(); m_pClassModule = pPluginManager->FindModule<NFIClassModule>(); m_pElementModule = pPluginManager->FindModule<NFIElementModule>(); m_pLogModule = pPluginManager->FindModule<NFILogModule>(); m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>(); return true; } bool NFCGameServerToDBModule::Shut() { return true; } bool NFCGameServerToDBModule::Execute() { return true; } bool NFCGameServerToDBModule::AfterInit() { //m_pNetClientModule->AddReceiveCallBack(NF_SERVER_TYPES::NF_ST_WORLD, this, &NFCGameServerToDBModule::TransPBToProxy); //m_pNetClientModule->AddEventCallBack(NF_SERVER_TYPES::NF_ST_WORLD, this, &NFCGameServerToDBModule::OnSocketWSEvent); m_pNetClientModule->ExpandBufferSize(); return true; } void NFCGameServerToDBModule::OnSocketWSEvent(const NFSOCK nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet) { if (eEvent & NF_NET_EVENT_EOF) { } else if (eEvent & NF_NET_EVENT_ERROR) { } else if (eEvent & NF_NET_EVENT_TIMEOUT) { } else if (eEvent & NF_NET_EVENT_CONNECTED) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connected success", __FUNCTION__, __LINE__); } } void NFCGameServerToDBModule::TransPBToProxy(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { m_pNetClientModule->SendBySuitWithOutHead(NF_SERVER_TYPES::NF_ST_DB, nSockIndex, nMsgID, std::string(msg, nLen)); return; } void NFCGameServerToDBModule::TransmitToDB(const int nHashKey, const int nMsgID, const google::protobuf::Message& xData) { m_pNetClientModule->SendSuitByPB(NF_SERVER_TYPES::NF_ST_DB, nHashKey, nMsgID, xData); }
c++
code
3,058
497
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "base58.h" #include "bitcoinrpc.h" #include "txdb.h" #include "init.h" #include "main.h" #include "net.h" #include "wallet.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(type))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("time", (int64_t)tx.nTime)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o, false); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash; hash.SetHex(params[0].get_str()); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Aseancoin address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if(setAddress.size()) { CTxDestination address; if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64_t nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address])); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Aseancoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value decodescript(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript <hex string>\n" "Decode a hex-encoded script."); RPCTypeCheck(params, list_of(str_type)); Object r; CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString())); return r; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the blockchain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" + HelpRequiringPassphrase()); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): map<COutPoint, CScript> mapPrevOut; for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTransaction tempTx; MapPrevTx mapPrevTx; CTxDB txdb("r"); map<uint256, CTxIndex> unused; bool fInvalid; // FetchInputs aborts on failure, so we go one at a time. tempTx.vin.push_back(mergedTx.vin[i]); tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid); // Copy results into mapPrevOut: BOOST_FOREACH(const CTxIn& txin, tempTx.vin) { const uint256& prevHash = txin.prevout.hash; if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n) mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey; } } // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); string txidHex = find_value(prevOut, "txid").get_str(); if (!IsHex(txidHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal"); uint256 txid; txid.SetHex(txidHex); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); string pkHex = find_value(prevOut, "scriptPubKey").get_str(); if (!IsHex(pkHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal"); vector<unsigned char> pkData(ParseHex(pkHex)); CScript scriptPubKey(pkData.begin(), pkData.end()); COutPoint outpoint(txid, nOut); if (mapPrevOut.count(outpoint)) { // Complain if scriptPubKey doesn't match if (mapPrevOut[outpoint] != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } } else mapPrevOut[outpoint] = scriptPubKey; } } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); tempKeystore.AddKey(key); } } else EnsureWalletIsUnlocked(); const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain); int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; if (mapPrevOut.count(txin.prevout) == 0) { fComplete = false; continue; } const CScript& prevPubKey = mapPrevOut[txin.prevout]; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "sendrawtransaction <hex string>\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); RPCTypeCheck(params, list_of(str_type)); // parse hex string from parameter vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); // See if the transaction is already in a block // or in the memory pool: CTransaction existingTx; uint256 hashBlock = 0; if (GetTransaction(hashTx, existingTx, hashBlock)) { if (hashBlock != 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex()); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { // push to local node if (!AcceptToMemo
c++
code
20,000
4,406
#include <AK/FileSystemPath.h> #include <AK/StdLibExtras.h> #include <AK/StringBuilder.h> #include <AK/Time.h> #include <AK/Types.h> #include <Kernel/Arch/i386/CPU.h> #include <Kernel/Arch/i386/PIT.h> #include <Kernel/Console.h> #include <Kernel/Devices/NullDevice.h> #include <Kernel/Devices/RandomDevice.h> #include <Kernel/FileSystem/Custody.h> #include <Kernel/FileSystem/DevPtsFS.h> #include <Kernel/FileSystem/Ext2FileSystem.h> #include <Kernel/FileSystem/FIFO.h> #include <Kernel/FileSystem/FileDescription.h> #include <Kernel/FileSystem/InodeWatcher.h> #include <Kernel/FileSystem/ProcFS.h> #include <Kernel/FileSystem/SharedMemory.h> #include <Kernel/FileSystem/TmpFS.h> #include <Kernel/FileSystem/VirtualFileSystem.h> #include <Kernel/Heap/kmalloc.h> #include <Kernel/IO.h> #include <Kernel/KBufferBuilder.h> #include <Kernel/KSyms.h> #include <Kernel/Multiboot.h> #include <Kernel/Net/Socket.h> #include <Kernel/Process.h> #include <Kernel/ProcessTracer.h> #include <Kernel/RTC.h> #include <Kernel/Scheduler.h> #include <Kernel/SharedBuffer.h> #include <Kernel/StdLib.h> #include <Kernel/Syscall.h> #include <Kernel/TTY/MasterPTY.h> #include <Kernel/Thread.h> #include <Kernel/VM/InodeVMObject.h> #include <LibC/errno_numbers.h> #include <LibC/signal_numbers.h> #include <LibELF/ELFLoader.h> #include <LibELF/exec_elf.h> //#define DEBUG_POLL_SELECT //#define DEBUG_IO //#define TASK_DEBUG //#define FORK_DEBUG //#define SIGNAL_DEBUG //#define SHARED_BUFFER_DEBUG static void create_signal_trampolines(); static pid_t next_pid; InlineLinkedList<Process>* g_processes; static String* s_hostname; static Lock* s_hostname_lock; VirtualAddress g_return_to_ring3_from_signal_trampoline; VirtualAddress g_return_to_ring0_from_signal_trampoline; void Process::initialize() { next_pid = 0; g_processes = new InlineLinkedList<Process>; s_hostname = new String("courage"); s_hostname_lock = new Lock; create_signal_trampolines(); } Vector<pid_t> Process::all_pids() { Vector<pid_t> pids; InterruptDisabler disabler; pids.ensure_capacity(g_processes->size_slow()); for (auto& process : *g_processes) pids.append(process.pid()); return pids; } Vector<Process*> Process::all_processes() { Vector<Process*> processes; InterruptDisabler disabler; processes.ensure_capacity(g_processes->size_slow()); for (auto& process : *g_processes) processes.append(&process); return processes; } bool Process::in_group(gid_t gid) const { return m_gids.contains(gid); } Range Process::allocate_range(VirtualAddress vaddr, size_t size) { vaddr.mask(PAGE_MASK); size = PAGE_ROUND_UP(size); if (vaddr.is_null()) return page_directory().range_allocator().allocate_anywhere(size); return page_directory().range_allocator().allocate_specific(vaddr, size); } static unsigned prot_to_region_access_flags(int prot) { unsigned access = 0; if (prot & PROT_READ) access |= Region::Access::Read; if (prot & PROT_WRITE) access |= Region::Access::Write; if (prot & PROT_EXEC) access |= Region::Access::Execute; return access; } Region& Process::allocate_split_region(const Region& source_region, const Range& range, size_t offset_in_vmo) { m_regions.append(Region::create_user_accessible(range, source_region.vmobject(), offset_in_vmo, source_region.name(), source_region.access())); return m_regions.last(); } Region* Process::allocate_region(VirtualAddress vaddr, size_t size, const String& name, int prot, bool commit) { auto range = allocate_range(vaddr, size); if (!range.is_valid()) return nullptr; m_regions.append(Region::create_user_accessible(range, name, prot_to_region_access_flags(prot))); m_regions.last().map(page_directory()); if (commit) m_regions.last().commit(); return &m_regions.last(); } Region* Process::allocate_file_backed_region(VirtualAddress vaddr, size_t size, NonnullRefPtr<Inode> inode, const String& name, int prot) { auto range = allocate_range(vaddr, size); if (!range.is_valid()) return nullptr; m_regions.append(Region::create_user_accessible(range, inode, name, prot_to_region_access_flags(prot))); m_regions.last().map(page_directory()); return &m_regions.last(); } Region* Process::allocate_region_with_vmo(VirtualAddress vaddr, size_t size, NonnullRefPtr<VMObject> vmo, size_t offset_in_vmo, const String& name, int prot) { auto range = allocate_range(vaddr, size); if (!range.is_valid()) return nullptr; offset_in_vmo &= PAGE_MASK; m_regions.append(Region::create_user_accessible(range, move(vmo), offset_in_vmo, name, prot_to_region_access_flags(prot))); m_regions.last().map(page_directory()); return &m_regions.last(); } bool Process::deallocate_region(Region& region) { InterruptDisabler disabler; for (int i = 0; i < m_regions.size(); ++i) { if (&m_regions[i] == &region) { m_regions.remove(i); return true; } } return false; } Region* Process::region_from_range(const Range& range) { size_t size = PAGE_ROUND_UP(range.size()); for (auto& region : m_regions) { if (region.vaddr() == range.base() && region.size() == size) return &region; } return nullptr; } Region* Process::region_containing(const Range& range) { for (auto& region : m_regions) { if (region.contains(range)) return &region; } return nullptr; } int Process::sys$set_mmap_name(void* addr, size_t size, const char* name) { if (!validate_read_str(name)) return -EFAULT; auto* region = region_from_range({ VirtualAddress((u32)addr), size }); if (!region) return -EINVAL; if (!region->is_mmap()) return -EPERM; region->set_name(String(name)); return 0; } void* Process::sys$mmap(const Syscall::SC_mmap_params* params) { if (!validate_read(params, sizeof(Syscall::SC_mmap_params))) return (void*)-EFAULT; auto& [addr, size, prot, flags, fd, offset, name] = *params; if (name && !validate_read_str(name)) return (void*)-EFAULT; if (size == 0) return (void*)-EINVAL; if ((u32)addr & ~PAGE_MASK) return (void*)-EINVAL; if ((flags & MAP_SHARED) && (flags & MAP_PRIVATE)) return (void*)-EINVAL; // EINVAL: MAP_STACK cannot be used with shared or file-backed mappings if ((flags & MAP_STACK) && ((flags & MAP_SHARED) || !(flags & MAP_PRIVATE) || !(flags & MAP_ANONYMOUS))) return (void*)-EINVAL; // EINVAL: MAP_STACK cannot be used with non-readable or non-writable memory if ((flags & MAP_STACK) && (!(prot & PROT_READ) || !(prot & PROT_WRITE))) return (void*)-EINVAL; // FIXME: The rest of this function seems like it could share more code.. if (flags & MAP_ANONYMOUS) { auto* region = allocate_region(VirtualAddress((u32)addr), size, name ? name : "mmap", prot, false); if (!region) return (void*)-ENOMEM; if (flags & MAP_SHARED) region->set_shared(true); if (flags & MAP_STACK) region->set_stack(true); region->set_mmap(true); return region->vaddr().as_ptr(); } if (offset & ~PAGE_MASK) return (void*)-EINVAL; auto* description = file_description(fd); if (!description) return (void*)-EBADF; auto region_or_error = description->mmap(*this, VirtualAddress((u32)addr), offset, size, prot); if (region_or_error.is_error()) return (void*)(int)region_or_error.error(); auto region = region_or_error.value(); if (flags & MAP_SHARED) region->set_shared(true); if (name) region->set_name(name); region->set_mmap(true); return region->vaddr().as_ptr(); } int Process::sys$munmap(void* addr, size_t size) { Range range_to_unmap { VirtualAddress((u32)addr), size }; if (auto* whole_region = region_from_range(range_to_unmap)) { if (!whole_region->is_mmap()) return -EPERM; bool success = deallocate_region(*whole_region); ASSERT(success); return 0; } if (auto* old_region = region_containing(range_to_unmap)) { if (!old_region->is_mmap()) return -EPERM; Range old_region_range = old_region->range(); auto remaining_ranges_after_unmap = old_region_range.carve(range_to_unmap); ASSERT(!remaining_ranges_after_unmap.is_empty()); auto make_replacement_region = [&](const Range& new_range) -> Region& { ASSERT(new_range.base() >= old_region_range.base()); ASSERT(new_range.end() <= old_region_range.end()); size_t new_range_offset_in_vmobject = old_region->offset_in_vmobject() + (new_range.base().get() - old_region_range.base().get()); return allocate_split_region(*old_region, new_range, new_range_offset_in_vmobject); }; Vector<Region*, 2> new_regions; for (auto& new_range : remaining_ranges_after_unmap) { new_regions.unchecked_append(&make_replacement_region(new_range)); } // We manually unmap the old region here, specifying that we *don't* want the VM deallocated. old_region->unmap(Region::ShouldDeallocateVirtualMemoryRange::No); deallocate_region(*old_region); // Instead we give back the unwanted VM manually. page_directory().range_allocator().deallocate(range_to_unmap); // And finally we map the new region(s). for (auto* new_region : new_regions) { new_region->map(page_directory()); } return 0; } // FIXME: We should also support munmap() across multiple regions. (#175) return -EINVAL; } int Process::sys$mprotect(void* addr, size_t size, int prot) { auto* region = region_from_range({ VirtualAddress((u32)addr), size }); if (!region) return -EINVAL; if (!region->is_mmap()) return -EPERM; region->set_writable(prot & PROT_WRITE); region->remap(); return 0; } int Process::sys$gethostname(char* buffer, ssize_t size) { if (size < 0) return -EINVAL; if (!validate_write(buffer, size)) return -EFAULT; LOCKER(*s_hostname_lock); if (size < (s_hostname->length() + 1)) return -ENAMETOOLONG; strcpy(buffer, s_hostname->characters()); return 0; } Process* Process::fork(RegisterDump& regs) { auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd, m_executable, m_tty, this); #ifdef FORK_DEBUG dbgprintf("fork: child=%p\n", child); #endif for (auto& region : m_regions) { #ifdef FORK_DEBUG dbg() << "fork: cloning Region{" << &region << "} '" << region.name() << "' @ " << region.vaddr(); #endif child->m_regions.append(region.clone()); child->m_regions.last().map(child->page_directory()); if (&region == m_master_tls_region) child->m_master_tls_region = &child->m_regions.last(); } for (auto gid : m_gids) child->m_gids.set(gid); auto& child_tss = child->main_thread().m_tss; child_tss.eax = 0; // fork() returns 0 in the child :^) child_tss.ebx = regs.ebx; child_tss.ecx = regs.ecx; child_tss.edx = regs.edx; child_tss.ebp = regs.ebp; child_tss.esp = regs.esp_if_crossRing; child_tss.esi = regs.esi; child_tss.edi = regs.edi; child_tss.eflags = regs.eflags; child_tss.eip = regs.eip; child_tss.cs = regs.cs; child_tss.ds = regs.ds; child_tss.es = regs.es; child_tss.fs = regs.fs; child_tss.gs = regs.gs; child_tss.ss = regs.ss_if_crossRing; #ifdef FORK_DEBUG dbgprintf("fork: child will begin executing at %w:%x with stack %w:%x, kstack %w:%x\n", child_tss.cs, child_tss.eip, child_tss.ss, child_tss.esp, child_tss.ss0, child_tss.esp0); #endif { InterruptDisabler disabler; g_processes->prepend(child); } #ifdef TASK_DEBUG kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child_tss.eip); #endif child->main_thread().set_state(Thread::State::Skip1SchedulerPass); return child; } pid_t Process::sys$fork(RegisterDump& regs) { auto* child = fork(regs); ASSERT(child); return child->pid(); } int Process::do_exec(String path, Vector<String> arguments, Vector<String> environment) { ASSERT(is_ring3()); dbgprintf("%s(%d) do_exec(%s): thread_count() = %d\n", m_name.characters(), m_pid, path.characters(), thread_count()); // FIXME(Thread): Kill any threads the moment we commit to the exec(). if (thread_count() != 1) { dbgprintf("Gonna die because I have many threads! These are the threads:\n"); for_each_thread([](Thread& thread) { dbgprintf("Thread{%p}: TID=%d, PID=%d\n", &thread, thread.tid(), thread.pid()); return IterationDecision::Continue; }); ASSERT(thread_count() == 1); ASSERT_NOT_REACHED(); } size_t total_blob_size = 0; for (auto& a : arguments) total_blob_size += a.length() + 1; for (auto& e : environment) total_blob_size += e.length() + 1; size_t total_meta_size = sizeof(char*) * (arguments.size() + 1) + sizeof(char*) * (environment.size() + 1); // FIXME: How much stack space does process startup need? if ((total_blob_size + total_meta_size) >= Thread::default_userspace_stack_size) return -E2BIG; auto parts = path.split('/'); if (parts.is_empty()) return -ENOENT; auto result = VFS::the().open(path, 0, 0, current_directory()); if (result.is_error()) return result.error(); auto description = result.value(); auto metadata = description->metadata(); if (!metadata.may_execute(m_euid, m_gids)) return -EACCES; if (!metadata.size) return -ENOTIMPL; u32 entry_eip = 0; // FIXME: Is there a race here? auto old_page_directory = move(m_page_directory); m_page_directory = PageDirectory::create_for_userspace(*this); #ifdef MM_DEBUG dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr()); #endif ProcessPagingScope paging_scope(*this); ASSERT(description->inode()); auto vmo = InodeVMObject::create_with_inode(*description->inode()); auto* region = allocate_region_with_vmo(VirtualAddress(), metadata.size, vmo, 0, description->absolute_path(), PROT_READ); ASSERT(region); // NOTE: We yank this out of 'm_regions' since we're about to manipulate the vector // and we don't want it getting lost. auto executable_region = m_regions.take_last(); Region* master_tls_region { nullptr }; size_t master_tls_size = 0; size_t master_tls_alignment = 0; OwnPtr<ELFLoader> loader; { // Okay, here comes the sleight of hand, pay close attention.. auto old_regions = move(m_regions); m_regions.append(move(executable_region)); loader = make<ELFLoader>(region->vaddr().as_ptr()); loader->map_section_hook = [&](VirtualAddress vaddr, size_t size, size_t alignment, size_t offset_in_image, bool is_readable, bool is_writable, bool is_executable, const String& name) -> u8* { ASSERT(size); ASSERT(alignment == PAGE_SIZE); int prot = 0; if (is_readable) prot |= PROT_READ; if (is_writable) prot |= PROT_WRITE; if (is_executable) prot |= PROT_EXEC; if (!allocate_region_with_vmo(vaddr, size, vmo, offset_in_image, String(name), prot)) return nullptr; return vaddr.as_ptr(); }; loader->alloc_section_hook = [&](VirtualAddress vaddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) -> u8* { ASSERT(size); ASSERT(alignment == PAGE_SIZE); int prot = 0; if (is_readable) prot |= PROT_READ; if (is_writable) prot |= PROT_WRITE; if (!allocate_region(vaddr, size, String(name), prot)) return nullptr; return vaddr.as_ptr(); }; loader->tls_section_hook = [&](size_t size, size_t alignment) { ASSERT(size); master_tls_region = allocate_region({}, size, String(), PROT_READ | PROT_WRITE); master_tls_size = size; master_tls_alignment = alignment; return master_tls_region->vaddr().as_ptr(); }; bool success = loader->load(); if (!success || !loader->entry().get()) { m_page_directory = move(old_page_directory); // FIXME: RAII this somehow instead. ASSERT(&current->process() == this); MM.enter_process_paging_scope(*this); executable_region = m_regions.take_first(); m_regions = move(old_regions); kprintf("do_exec: Failure loading %s\n", path.characters()); return -ENOEXEC; } // NOTE: At this point, we've committed to the new executable. entry_eip = loader->entry().get(); } m_elf_loader = move(loader); m_executable = description->custody(); // Copy of the master TLS region that we will clone for new threads m_master_tls_region = master_tls_region; if (metadata.is_setuid()) m_euid = metadata.uid; if (metadata.is_setgid()) m_egid = metadata.gid; current->set_default_signal_dispositions(); current->m_signal_mask = 0; current->m_pending_signals = 0; for (int i = 0; i < m_fds.size(); ++i) { auto& daf = m_fds[i]; if (daf.description && daf.flags & FD_CLOEXEC) { daf.description->close(); daf = {}; } } // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield(). // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec(). if (&current->process() == this) cli(); Scheduler::prepare_to_modify_tss(main_thread()); m_name = parts.take_last(); // ss0 sp!!!!!!!!! u32 old_esp0 = main_thread().m_tss.esp0; m_master_tls_size = master_tls_size; m_master_tls_alignment = master_tls_alignment; main_thread().make_thread_specific_region({}); memset(&main_thread().m_tss, 0, sizeof(main_thread().m_tss)); main_thread().m_tss.eflags = 0x0202; main_thread().m_tss.eip = entry_eip; main_thread().m_tss.cs = 0x1b; main_thread().m_tss.ds = 0x23; main_thread().m_tss.es = 0x23; main_thread().m_tss.fs = 0x23; main_thread().m_tss.gs = thread_specific_selector() | 3; main_thread().m_tss.ss = 0x23; main_thread().m_tss.cr3 = page_directory().cr3(); main_thread().make_userspace_stack_for_main_thread(move(arguments), move(environment)); main_thread().m_tss.ss0 = 0x10; main_thread().m_tss.esp0 = old_esp0; main_thread().m_tss.ss2 = m_pid; #ifdef TASK_DEBUG kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), main_thread().tss().eip); #endif main_thread().set_state(Thread::State::Skip1SchedulerPass); big_lock().unlock_if_locked(); return 0; } KResultOr<Vector<String>> Process::find_shebang_interpreter_for_executable(const String& executable_path) { // FIXME: It's a bit sad that we'll open the executable twice (in case there's no shebang) // Maybe we can find a way to plumb this opened FileDescription to the rest of the // exec implementation.. auto result = VFS::the().open(executable_path, 0, 0, current_directory()); if (result.is_error()) return result.error(); auto description = result.value(); auto metad
c++
code
20,000
4,446
/* Isolation forests and variations thereof, with adjustments for incorporation * of categorical variables and missing values. * Writen for C++11 standard and aimed at being used in R and Python. * * This library is based on the following works: * [1] Liu, Fei Tony, Kai Ming Ting, and Zhi-Hua Zhou. * "Isolation forest." * 2008 Eighth IEEE International Conference on Data Mining. IEEE, 2008. * [2] Liu, Fei Tony, Kai Ming Ting, and Zhi-Hua Zhou. * "Isolation-based anomaly detection." * ACM Transactions on Knowledge Discovery from Data (TKDD) 6.1 (2012): 3. * [3] Hariri, Sahand, Matias Carrasco Kind, and Robert J. Brunner. * "Extended Isolation Forest." * arXiv preprint arXiv:1811.02141 (2018). * [4] Liu, Fei Tony, Kai Ming Ting, and Zhi-Hua Zhou. * "On detecting clustered anomalies using SCiForest." * Joint European Conference on Machine Learning and Knowledge Discovery in Databases. Springer, Berlin, Heidelberg, 2010. * [5] https://sourceforge.net/projects/iforest/ * [6] https://math.stackexchange.com/questions/3388518/expected-number-of-paths-required-to-separate-elements-in-a-binary-tree * [7] Quinlan, J. Ross. C4. 5: programs for machine learning. Elsevier, 2014. * [8] Cortes, David. * "Distance approximation using Isolation Forests." * arXiv preprint arXiv:1910.12362 (2019). * [9] Cortes, David. * "Imputing missing values with unsupervised random trees." * arXiv preprint arXiv:1911.06646 (2019). * [10] https://math.stackexchange.com/questions/3333220/expected-average-depth-in-random-binary-tree-constructed-top-to-bottom * [11] Cortes, David. * "Revisiting randomized choices in isolation forests." * arXiv preprint arXiv:2110.13402 (2021). * [12] Guha, Sudipto, et al. * "Robust random cut forest based anomaly detection on streams." * International conference on machine learning. PMLR, 2016. * [13] Cortes, David. * "Isolation forests: looking beyond tree depth." * arXiv preprint arXiv:2111.11639 (2021). * [14] Ting, Kai Ming, Yue Zhu, and Zhi-Hua Zhou. * "Isolation kernel and its effect on SVM" * Proceedings of the 24th ACM SIGKDD * International Conference on Knowledge Discovery & Data Mining. 2018. * * BSD 2-Clause License * Copyright (c) 2019-2022, David Cortes * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*********************************************************************************** --------------------- IsoTree OOP interface --------------------- This is provided as an alternative easier-to-use interface for this library which follows scikit-learn-style methods with a single C++ class. It is a wrapper over the non-OOP header 'isotree.hpp', providing the same functionality in a perhaps more comprehensible structure, while still offering direct access to the underlying objects so as to allow using the functions from 'isotree.hpp'. It is a more limited interface as it does not implement all the functionality for serialization, distance prediction, oproducing predictions in the same call as the model is fit, or fitting/predicting on data with types other than 'double' and 'int'. The descriptions here do not contain the full documentation, but rather only some hints so as to make them more comprehensible, aiming at producing function signatures that are self-descriptive instead (if you are familiar with the scikit-learn library for Python). For detailed documentation see the same or similar-looking methods in the 'isotree.hpp' header instead. ***********************************************************************************/ #if !defined(_FOR_R) && !defined(_FOR_PYTHON) #include "isotree.hpp" namespace isotree { class ISOTREE_EXPORTED IsolationForest { public: int nthreads = -1; uint64_t random_seed = 1; size_t ndim = 3; size_t ntry = 1; CoefType coef_type = Normal; bool with_replacement = false; bool weight_as_sample = true; size_t sample_size = 0; size_t ntrees = 500; size_t max_depth = 0; size_t ncols_per_tree = 0; bool limit_depth = true; bool penalize_range = false; bool standardize_data = true; ScoringMetric scoring_metric = Depth; bool fast_bratio = true; bool weigh_by_kurt = false; double prob_pick_by_gain_pl = 0.; double prob_pick_by_gain_avg = 0.; double prob_pick_col_by_range = 0.; double prob_pick_col_by_var = 0.; double prob_pick_col_by_kurt = 0.; double min_gain = 0.; MissingAction missing_action = Impute; CategSplit cat_split_type = SubSet; NewCategAction new_cat_action = Weighted; bool coef_by_prop = false; bool all_perm = false; bool build_imputer = false; size_t min_imp_obs = 3; UseDepthImp depth_imp = Higher; WeighImpRows weigh_imp_rows = Inverse; IsoForest model; ExtIsoForest model_ext; Imputer imputer; TreesIndexer indexer; IsolationForest() = default; ~IsolationForest() = default; IsolationForest ( size_t ndim, size_t ntry, CoefType coef_type, bool coef_by_prop, bool with_replacement, bool weight_as_sample, size_t sample_size, size_t ntrees, size_t max_depth, size_t ncols_per_tree, bool limit_depth, bool penalize_range, bool standardize_datam, ScoringMetric scoring_metric, bool fast_bratio, bool weigh_by_kurt, double prob_pick_by_gain_pl, double prob_pick_by_gain_avg, double prob_pick_col_by_range, double prob_pick_col_by_var, double prob_pick_col_by_kurt, double min_gain, MissingAction missing_action, CategSplit cat_split_type, NewCategAction new_cat_action, bool all_perm, bool build_imputer, size_t min_imp_obs, UseDepthImp depth_imp, WeighImpRows weigh_imp_rows, uint64_t random_seed, int nthreads ); void fit(double X[], size_t nrows, size_t ncols); void fit(double numeric_data[], size_t ncols_numeric, size_t nrows, int categ_data[], size_t ncols_categ, int ncat[], double sample_weights[], double col_weights[]); void fit(double Xc[], int Xc_ind[], int Xc_indptr[], size_t ncols_numeric, size_t nrows, int categ_data[], size_t ncols_categ, int ncat[], double sample_weights[], double col_weights[]); std::vector<double> predict(double X[], size_t nrows, bool standardize); void predict(double numeric_data[], int categ_data[], bool is_col_major, size_t nrows, size_t ld_numeric, size_t ld_categ, bool standardize, double output_depths[], int tree_num[], double per_tree_depths[]); void predict(double X_sparse[], int X_ind[], int X_indptr[], bool is_csc, int categ_data[], bool is_col_major, size_t ld_categ, size_t nrows, bool standardize, double output_depths[], int tree_num[], double per_tree_depths[]); std::vector<double> predict_distance(double X[], size_t nrows, bool as_kernel, bool assume_full_distr, bool standardize, bool triangular); void predict_distance(double numeric_data[], int categ_data[], size_t nrows, bool as_kernel, bool assume_full_distr, bool standardize, bool triangular, double dist_matrix[]); void predict_distance(double Xc[], int Xc_ind[], int Xc_indptr[], int categ_data[], size_t nrows, bool as_kernel, bool assume_full_distr, bool standardize, bool triangular, double dist_matrix[]); void impute(double X[], size_t nrows); void impute(double numeric_data[], int categ_data[], bool is_col_major, size_t nrows); void impute(double Xr[], int Xr_ind[], int Xr_indptr[], int categ_data[], bool is_col_major, size_t nrows); void build_indexer(const bool with_distances); void set_as_reference_points(double numeric_data[], int categ_data[], bool is_col_major, size_t nrows, size_t ld_numeric, size_t ld_categ, const bool with_distances); void set_as_reference_points(double Xc[], int Xc_ind[], int Xc_indptr[], int categ_data[], size_t nrows, const bool with_distances); size_t get_num_reference_points() const noexcept; void predict_distance_to_ref_points(double numeric_data[], int categ_data[], double Xc[], int Xc_ind[], int Xc_indptr[], size_t nrows, bool is_col_major, size_t ld_numeric, size_t ld_categ, bool as_kernel, bool standardize, double dist_matrix[]); void serialize(FILE *out) const; void serialize(std::ostream &out) const; static IsolationForest deserialize(FILE *inp, int nthreads); static IsolationForest deserialize(std::istream &inp, int nthreads); friend std::ostream& operator<<(std::ostream &ost, const IsolationForest &model); friend std::istream& operator>>(std::istream &ist, IsolationForest &model); IsoForest& get_model(); ExtIsoForest& get_model_ext(); Imputer& get_imputer(); TreesIndexer& get_indexer(); void check_nthreads(); size_t get_ntrees() const; bool check_can_predict_per_tree() const; private: bool is_fitted = false; void override_previous_fit(); void check_params(); void check_is_fitted() const; IsolationForest(int nthreads, size_t ndim, size_t ntrees, bool build_imputer); template <class otype> void serialize_template(otype &out) const; template <class itype> static IsolationForest deserialize_template(itype &inp, int nthreads); }; ISOTREE_EXPORTED std::ostream& operator<<(std::ostream &ost, const IsolationForest &model); ISOTREE_EXPORTED std::istream& operator>>(std::istream &ist, IsolationForest &model); } #endif
c++
code
11,831
2,135
/* * Copyright 2013 Google 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. */ // Author: [email protected] (Joshua Marantz) #include "net/instaweb/http/public/async_fetch.h" #include "net/instaweb/http/public/request_context.h" #include "pagespeed/kernel/base/basictypes.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/mock_message_handler.h" #include "pagespeed/kernel/base/null_mutex.h" #include "pagespeed/kernel/http/http_names.h" #include "pagespeed/kernel/http/http_options.h" #include "pagespeed/kernel/http/response_headers.h" namespace net_instaweb { namespace { const char kUrl[] = "http://www.example.com/"; class TestSharedAsyncFetch : public SharedAsyncFetch { public: explicit TestSharedAsyncFetch(AsyncFetch* base_fetch) : SharedAsyncFetch(base_fetch) { } virtual ~TestSharedAsyncFetch() { } private: DISALLOW_COPY_AND_ASSIGN(TestSharedAsyncFetch); }; // Tests the AsyncFetch class and some of its derivations. class AsyncFetchTest : public testing::Test { protected: AsyncFetchTest() : request_context_(new RequestContext( kDefaultHttpOptionsForTests, new NullMutex, NULL)), string_fetch_(request_context_), handler_(new NullMutex) { } bool CheckCacheControlPublicWithVia(const char* via) { StringAsyncFetch fetch(request_context_); fetch.response_headers()->Add(HttpAttributes::kCacheControl, "max-age:100"); if (via != nullptr) { fetch.request_headers()->Add(HttpAttributes::kVia, via); } fetch.FixCacheControlForGoogleCache(); return fetch.response_headers()->HasValue( HttpAttributes::kCacheControl, "public"); } protected: RequestContextPtr request_context_; StringAsyncFetch string_fetch_; HTTPValue fallback_value_; MockMessageHandler handler_; }; TEST_F(AsyncFetchTest, LackOfContentLengthPropagatesToShared) { TestSharedAsyncFetch fetch(&string_fetch_); fetch.response_headers()->set_status_code(HttpStatus::kOK); EXPECT_FALSE(fetch.content_length_known()); fetch.HeadersComplete(); EXPECT_FALSE(string_fetch_.content_length_known()); } TEST_F(AsyncFetchTest, ContentLengthPropagatesToShared) { TestSharedAsyncFetch fetch(&string_fetch_); fetch.response_headers()->set_status_code(HttpStatus::kOK); fetch.set_content_length(42); EXPECT_TRUE(fetch.content_length_known()); fetch.HeadersComplete(); EXPECT_TRUE(string_fetch_.content_length_known()); EXPECT_EQ(42, string_fetch_.content_length()); } TEST_F(AsyncFetchTest, LackOfContentLengthPropagatesToFallback) { FallbackSharedAsyncFetch fetch(&string_fetch_, &fallback_value_, &handler_); fetch.response_headers()->set_status_code(HttpStatus::kOK); EXPECT_FALSE(fetch.content_length_known()); fetch.HeadersComplete(); EXPECT_FALSE(string_fetch_.content_length_known()); } TEST_F(AsyncFetchTest, ContentLengthPropagatesToFallback) { FallbackSharedAsyncFetch fetch(&string_fetch_, &fallback_value_, &handler_); fetch.response_headers()->set_status_code(HttpStatus::kOK); fetch.set_content_length(42); EXPECT_TRUE(fetch.content_length_known()); fetch.HeadersComplete(); EXPECT_TRUE(string_fetch_.content_length_known()); EXPECT_EQ(42, string_fetch_.content_length()); } TEST_F(AsyncFetchTest, LackOfContentLengthPropagatesToConditional) { ConditionalSharedAsyncFetch fetch(&string_fetch_, &fallback_value_, &handler_); fetch.response_headers()->set_status_code(HttpStatus::kOK); EXPECT_FALSE(fetch.content_length_known()); fetch.HeadersComplete(); EXPECT_FALSE(string_fetch_.content_length_known()); } TEST_F(AsyncFetchTest, ContentLengthPropagatesToConditional) { ConditionalSharedAsyncFetch fetch(&string_fetch_, &fallback_value_, &handler_); fetch.response_headers()->set_status_code(HttpStatus::kOK); fetch.set_content_length(42); EXPECT_TRUE(fetch.content_length_known()); fetch.HeadersComplete(); EXPECT_TRUE(string_fetch_.content_length_known()); EXPECT_EQ(42, string_fetch_.content_length()); } TEST_F(AsyncFetchTest, ViaHandling) { EXPECT_FALSE(CheckCacheControlPublicWithVia(nullptr)); EXPECT_TRUE(CheckCacheControlPublicWithVia("1.1 google")); EXPECT_TRUE(CheckCacheControlPublicWithVia("2.0 google")); EXPECT_TRUE(CheckCacheControlPublicWithVia("2 google")); EXPECT_TRUE(CheckCacheControlPublicWithVia("1.0 GOOGLE")); EXPECT_FALSE(CheckCacheControlPublicWithVia("varnish")); EXPECT_FALSE(CheckCacheControlPublicWithVia("NotReallyGoogle")); } } // namespace } // namespace net_instaweb
c++
code
5,105
869
// // AGAST, an adaptive and generic corner detector based on the // accelerated segment test for a 8 pixel mask // // Copyright (C) 2010 Elmar Mair // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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. // Machine generated code. // Probability of an equal pixel on the Bresenham's circle: 0.33 and 0.1. // Number of equal pixels to switch: 1. // Number of unequal pixels to switch: 6. // Memory costs: cache = 0.2. // same line = 1. // memory = 4. #include <stdint.h> #include <stdlib.h> #include <agast/agast5-8.h> namespace agast { void AgastDetector5_8::detect(const unsigned char* im, std::vector<cv::KeyPoint>& corners_all, const cv::Mat* /*thrmap*/) { int total = 0; int nExpectedCorners = corners_all.capacity(); cv::KeyPoint h; int x, y; int xsizeB = xsize - 2; int ysizeB = ysize - 1; int_fast16_t offset0, offset1, offset2, offset3, offset4, offset5, offset6, offset7; int width; corners_all.resize(0); offset0 = s_offset0; offset1 = s_offset1; offset2 = s_offset2; offset3 = s_offset3; offset4 = s_offset4; offset5 = s_offset5; offset6 = s_offset6; offset7 = s_offset7; width = xsize; for (y = 1; y < ysizeB; y++) { x = 0; while (1) { homogeneous: { x++; if (x > xsizeB) break; else { const unsigned char* const p = im + y * width + x; const int cb = *p + b; const int c_b = *p - b; if (p[offset0] > cb) if (p[offset2] > cb) if (p[offset3] > cb) if (p[offset5] > cb) if (p[offset1] > cb) if (p[offset4] > cb) goto success_structured; else if (p[offset7] > cb) goto success_structured; else goto homogeneous; else if (p[offset4] > cb) if (p[offset6] > cb) goto success_structured; else goto homogeneous; else goto homogeneous; else if (p[offset1] > cb) if (p[offset4] > cb) goto success_homogeneous; else if (p[offset7] > cb) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset7] > cb) if (p[offset6] > cb) if (p[offset5] > cb) if (p[offset1] > cb) goto success_structured; else if (p[offset4] > cb) goto success_structured; else goto homogeneous; else if (p[offset1] > cb) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset5] < c_b) if (p[offset3] < c_b) if (p[offset7] < c_b) if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto structured; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset5] > cb) if (p[offset7] > cb) if (p[offset6] > cb) if (p[offset1] > cb) goto success_homogeneous; else if (p[offset4] > cb) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset5] < c_b) if (p[offset3] < c_b) if (p[offset2] < c_b) if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_structured; else goto homogeneous; else if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto homogeneous; else goto homogeneous; else if (p[offset7] < c_b) if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset0] < c_b) if (p[offset2] < c_b) if (p[offset7] > cb) if (p[offset3] < c_b) if (p[offset5] < c_b) if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_structured; else goto structured; else if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto structured; else goto homogeneous; else if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_structured; else goto homogeneous; else goto homogeneous; else if (p[offset5] > cb) if (p[offset3] > cb) if (p[offset4] > cb) if (p[offset6] > cb) goto success_structured; else goto structured; else goto homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset7] < c_b) if (p[offset3] < c_b) if (p[offset5] < c_b) if (p[offset1] < c_b) goto success_structured; else if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto structured; else goto homogeneous; else if (p[offset1] < c_b) goto success_homogeneous; else goto homogeneous; else if (p[offset6] < c_b) if (p[offset5] < c_b) if (p[offset1] < c_b) goto success_structured; else if (p[offset4] < c_b) goto success_structured; else goto homogeneous; else if (p[offset1] < c_b) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset3] < c_b) if (p[offset5] < c_b) if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_structured; else goto homogeneous; else if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto homogeneous; else goto homogeneous; else if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset5] > cb) if (p[offset3] > cb) if (p[offset2] > cb) if (p[offset1] > cb) if (p[offset4] > cb) goto success_structured; else goto homogeneous; else if (p[offset4] > cb) if (p[offset6] > cb) goto success_structured; else goto homogeneous; else goto homogeneous; else if (p[offset7] > cb) if (p[offset4] > cb) if (p[offset6] > cb) goto success_structured; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset5] < c_b) if (p[offset7] < c_b) if (p[offset6] < c_b) if (p[offset1] < c_b) goto success_homogeneous; else if (p[offset4] < c_b) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset3] > cb) if (p[offset5] > cb) if (p[offset2] > cb) if (p[offset1] > cb) if (p[offset4] > cb) goto success_homogeneous; else goto homogeneous; else if (p[offset4] > cb) if (p[offset6] > cb) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset7] > cb) if (p[offset4] > cb) if (p[offset6] > cb) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset3] < c_b) if (p[offset5] < c_b) if (p[offset2] < c_b) if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_homogeneous; else goto homogeneous; else if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else if (p[offset7] < c_b) if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; } } structured: { x++; if (x > xsizeB) break; else { const unsigned char* const p = im + y * width + x; const int cb = *p + b; const int c_b = *p - b; if (p[offset0] > cb) if (p[offset2] > cb) if (p[offset3] > cb) if (p[offset5] > cb) if (p[offset7] > cb) if (p[offset1] > cb) goto success_structured; else if (p[offset4] > cb) if (p[offset6] > cb) goto success_structured; else goto structured; else goto structured; else if (p[offset1] > cb) if (p[offset4] > cb) goto success_structured; else goto structured; else if (p[offset4] > cb) if (p[offset6] > cb) goto success_structured; else goto structured; else goto structured; else if (p[offset7] > cb) if (p[offset1] > cb) goto success_structured; else goto structured; else if (p[offset1] > cb) if (p[offset4] > cb) goto success_structured; else goto structured; else goto structured; else if (p[offset7] > cb) if (p[offset6] > cb) if (p[offset5] > cb) if (p[offset1] > cb) goto success_structured; else if (p[offset4] > cb) goto success_structured; else goto structured; else if (p[offset1] > cb) goto success_structured; else goto structured; else goto structured; else if (p[offset5] < c_b) if (p[offset3] < c_b) if (p[offset7] < c_b) if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto structured; else goto structured; else goto homogeneous; else goto homogeneous; else goto structured; else if (p[offset5] > cb) if (p[offset7] > cb) if (p[offset6] > cb) if (p[offset1] > cb) goto success_structured; else if (p[offset4] > cb) goto success_structured; else goto structured; else goto structured; else goto structured; else if (p[offset5] < c_b) if (p[offset3] < c_b) if (p[offset2] < c_b) if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_structured; else goto structured; else if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto structured; else goto structured; else if (p[offset7] < c_b) if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_homogeneous; else goto homogeneous; else goto homogeneous; else goto homogeneous; else goto structured; else goto homogeneous; else if (p[offset0] < c_b) if (p[offset2] < c_b) if (p[offset7] > cb) if (p[offset3] < c_b) if (p[offset5] < c_b) if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_structured; else goto structured; else if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto structured; else goto structured; else if (p[offset1] < c_b) if (p[offset4] < c_b) goto success_structured; else goto structured; else goto structured; else if (p[offset5] > cb) if (p[offset3] > cb) if (p[offset4] > cb) if (p[offset6] > cb) goto success_structured; else goto structured; else goto structured; else goto homogeneous; else goto structured; else if (p[offset7] < c_b) if (p[offset3] < c_b) if (p[offset5] < c_b) if (p[offset1] < c_b) goto success_structured; else if (p[offset4] < c_b) if (p[offset6] < c_b) goto success_structured; else goto structured; else goto structured; else if (p[offset1] < c_b) goto success_structured; else goto structured; else if (p[offset6] < c_b) if (p[offset5] < c_b) if (p[offset1] < c_b) goto success_structured; else if (p[offset4] < c_b) goto success_structured;
c++
code
19,980
2,919
/* american fuzzy lop++ - LLVM CmpLog instrumentation -------------------------------------------------- Written by Andrea Fioraldi <[email protected]> Copyright 2015, 2016 Google Inc. All rights reserved. Copyright 2019-2020 AFLplusplus Project. 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 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <list> #include <string> #include <fstream> #include <sys/time.h> #include "llvm/Config/llvm-config.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Pass.h" #include "llvm/Analysis/ValueTracking.h" #if LLVM_VERSION_MAJOR > 3 || \ (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR > 4) #include "llvm/IR/Verifier.h" #include "llvm/IR/DebugInfo.h" #else #include "llvm/Analysis/Verifier.h" #include "llvm/DebugInfo.h" #define nullptr 0 #endif #include <set> #include "afl-llvm-common.h" using namespace llvm; namespace { class CmpLogRoutines : public ModulePass { public: static char ID; CmpLogRoutines() : ModulePass(ID) { initWhitelist(); } bool runOnModule(Module &M) override; #if LLVM_VERSION_MAJOR < 4 const char *getPassName() const override { #else StringRef getPassName() const override { #endif return "cmplog routines"; } protected: int be_quiet = 0; private: bool hookRtns(Module &M); }; } // namespace char CmpLogRoutines::ID = 0; bool CmpLogRoutines::hookRtns(Module &M) { std::vector<CallInst *> calls; LLVMContext & C = M.getContext(); Type *VoidTy = Type::getVoidTy(C); // PointerType *VoidPtrTy = PointerType::get(VoidTy, 0); IntegerType *Int8Ty = IntegerType::getInt8Ty(C); PointerType *i8PtrTy = PointerType::get(Int8Ty, 0); #if LLVM_VERSION_MAJOR < 9 Constant * #else FunctionCallee #endif c = M.getOrInsertFunction("__cmplog_rtn_hook", VoidTy, i8PtrTy, i8PtrTy #if LLVM_VERSION_MAJOR < 5 , NULL #endif ); #if LLVM_VERSION_MAJOR < 9 Function *cmplogHookFn = cast<Function>(c); #else FunctionCallee cmplogHookFn = c; #endif /* iterate over all functions, bbs and instruction and add suitable calls */ for (auto &F : M) { if (!isInWhitelist(&F)) continue; for (auto &BB : F) { for (auto &IN : BB) { CallInst *callInst = nullptr; if ((callInst = dyn_cast<CallInst>(&IN))) { Function *Callee = callInst->getCalledFunction(); if (!Callee) continue; if (callInst->getCallingConv() != llvm::CallingConv::C) continue; FunctionType *FT = Callee->getFunctionType(); bool isPtrRtn = FT->getNumParams() >= 2 && !FT->getReturnType()->isVoidTy() && FT->getParamType(0) == FT->getParamType(1) && FT->getParamType(0)->isPointerTy(); if (!isPtrRtn) continue; calls.push_back(callInst); } } } } if (!calls.size()) return false; if (!be_quiet) errs() << "Hooking " << calls.size() << " calls with pointers as arguments\n"; for (auto &callInst : calls) { Value *v1P = callInst->getArgOperand(0), *v2P = callInst->getArgOperand(1); IRBuilder<> IRB(callInst->getParent()); IRB.SetInsertPoint(callInst); std::vector<Value *> args; Value * v1Pcasted = IRB.CreatePointerCast(v1P, i8PtrTy); Value * v2Pcasted = IRB.CreatePointerCast(v2P, i8PtrTy); args.push_back(v1Pcasted); args.push_back(v2Pcasted); IRB.CreateCall(cmplogHookFn, args); // errs() << callInst->getCalledFunction()->getName() << "\n"; } return true; } bool CmpLogRoutines::runOnModule(Module &M) { if (getenv("AFL_QUIET") == NULL) llvm::errs() << "Running cmplog-routines-pass by [email protected]\n"; else be_quiet = 1; hookRtns(M); verifyModule(M); return true; } static void registerCmpLogRoutinesPass(const PassManagerBuilder &, legacy::PassManagerBase &PM) { auto p = new CmpLogRoutines(); PM.add(p); } static RegisterStandardPasses RegisterCmpLogRoutinesPass( PassManagerBuilder::EP_OptimizerLast, registerCmpLogRoutinesPass); static RegisterStandardPasses RegisterCmpLogRoutinesPass0( PassManagerBuilder::EP_EnabledOnOptLevel0, registerCmpLogRoutinesPass);
c++
code
4,870
993
/* Copyright 2019 The MathWorks, Inc. */ #ifndef _MW_ARMNEON_SEQINPUT_LAYER_IMPL_ #define _MW_ARMNEON_SEQINPUT_LAYER_IMPL_ #include "MWCNNLayerImpl.hpp" /** * Codegen class for Sequence Input layer implementation */ class MWSequenceInputLayerImpl : public MWCNNLayerImpl { public: MWSequenceInputLayerImpl(MWCNNLayer*, MWTargetNetworkImpl*); ~MWSequenceInputLayerImpl(); void predict(); void allocateOutputData(int); void deallocateOutputData(int); private: bool isPaddingEnabled; float* m_inputData; private: void propagateSize(); }; #endif
c++
code
587
93
#include <inspurcloud/oss/model/GetObjectTaggingResult.h> #include <tinyxml2/tinyxml2.h> #include "../utils/Utils.h" using namespace InspurCloud::OSS; using namespace tinyxml2; GetObjectTaggingResult::GetObjectTaggingResult() : OssResult() { } GetObjectTaggingResult::GetObjectTaggingResult(const std::string& result): GetObjectTaggingResult() { *this = result; } GetObjectTaggingResult::GetObjectTaggingResult(const std::shared_ptr<std::iostream>& result): GetObjectTaggingResult() { std::istreambuf_iterator<char> isb(*result.get()), end; std::string str(isb, end); *this = str; } GetObjectTaggingResult& GetObjectTaggingResult::operator =(const std::string& result) { XMLDocument doc; XMLError xml_err; if ((xml_err = doc.Parse(result.c_str(), result.size())) == XML_SUCCESS) { XMLElement* root =doc.RootElement(); if (root && !std::strncmp("Tagging", root->Name(), 7)) { XMLElement* tagSet_node = root->FirstChildElement("TagSet"); if (tagSet_node) { XMLElement *tag_node = tagSet_node->FirstChildElement("Tag"); for (; tag_node; tag_node = tag_node->NextSiblingElement("Tag")) { XMLElement *subNode; Tag tag; //Key subNode = tag_node->FirstChildElement("Key"); if (subNode && subNode->GetText()) { tag.setKey(subNode->GetText()); } //Value subNode = tag_node->FirstChildElement("Value"); if (subNode && subNode->GetText()) { tag.setValue(subNode->GetText()); } tagging_.addTag(tag); } } //TODO check the result and the parse flag; parseDone_ = true; } } return *this; }
c++
code
1,926
374
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <gmock/gmock.h> #include "velox/core/Expressions.h" #include "velox/expression/Expr.h" #include "velox/functions/prestosql/registration/RegistrationFunctions.h" #include "velox/parse/Expressions.h" #include "velox/parse/ExpressionsParser.h" #include "velox/parse/TypeResolver.h" #include "velox/vector/tests/VectorTestBase.h" using namespace facebook::velox; using namespace facebook::velox::test; class ExprStatsTest : public testing::Test, public VectorTestBase { protected: void SetUp() override { functions::prestosql::registerAllScalarFunctions(); parse::registerTypeResolver(); } static RowTypePtr asRowType(const TypePtr& type) { return std::dynamic_pointer_cast<const RowType>(type); } std::shared_ptr<const core::ITypedExpr> parseExpression( const std::string& text, const RowTypePtr& rowType) { auto untyped = parse::parseExpr(text); return core::Expressions::inferTypes(untyped, rowType, execCtx_->pool()); } std::unique_ptr<exec::ExprSet> compileExpressions( const std::vector<std::string>& exprs, const RowTypePtr& rowType) { std::vector<std::shared_ptr<const core::ITypedExpr>> expressions; expressions.reserve(exprs.size()); for (const auto& expr : exprs) { expressions.emplace_back(parseExpression(expr, rowType)); } return std::make_unique<exec::ExprSet>( std::move(expressions), execCtx_.get()); } VectorPtr evaluate(exec::ExprSet& exprSet, const RowVectorPtr& input) { exec::EvalCtx context(execCtx_.get(), &exprSet, input.get()); SelectivityVector rows(input->size()); std::vector<VectorPtr> result(1); exprSet.eval(rows, &context, &result); return result[0]; } std::shared_ptr<core::QueryCtx> queryCtx_{core::QueryCtx::createForTest()}; std::unique_ptr<memory::MemoryPool> pool_{ memory::getDefaultScopedMemoryPool()}; std::unique_ptr<core::ExecCtx> execCtx_{ std::make_unique<core::ExecCtx>(pool_.get(), queryCtx_.get())}; }; TEST_F(ExprStatsTest, printWithStats) { vector_size_t size = 1'024; auto data = makeRowVector({ makeFlatVector<int32_t>(size, [](auto row) { return row; }), makeFlatVector<int32_t>(size, [](auto row) { return row % 7; }), }); auto rowType = asRowType(data->type()); { auto exprSet = compileExpressions({"(c0 + 3) * c1", "(c0 + c1) % 2 = 0"}, rowType); // Check stats before evaluation. ASSERT_EQ( exec::printExprWithStats(*exprSet), "multiply [cpu time: 0ns, rows: 0] -> BIGINT\n" " plus [cpu time: 0ns, rows: 0] -> BIGINT\n" " cast(c0 as BIGINT) [cpu time: 0ns, rows: 0] -> BIGINT\n" " c0 [cpu time: 0ns, rows: 0] -> INTEGER\n" " 3:BIGINT [cpu time: 0ns, rows: 0] -> BIGINT\n" " cast(c1 as BIGINT) [cpu time: 0ns, rows: 0] -> BIGINT\n" " c1 [cpu time: 0ns, rows: 0] -> INTEGER\n" "\n" "eq [cpu time: 0ns, rows: 0] -> BOOLEAN\n" " mod [cpu time: 0ns, rows: 0] -> BIGINT\n" " cast(plus as BIGINT) [cpu time: 0ns, rows: 0] -> BIGINT\n" " plus [cpu time: 0ns, rows: 0] -> INTEGER\n" " c0 [cpu time: 0ns, rows: 0] -> INTEGER\n" " c1 [cpu time: 0ns, rows: 0] -> INTEGER\n" " 2:BIGINT [cpu time: 0ns, rows: 0] -> BIGINT\n" " 0:BIGINT [cpu time: 0ns, rows: 0] -> BIGINT\n"); evaluate(*exprSet, data); // Check stats after evaluation. ASSERT_THAT( exec::printExprWithStats(*exprSet), ::testing::MatchesRegex( "multiply .cpu time: .+, rows: 1024. -> BIGINT\n" " plus .cpu time: .+, rows: 1024. -> BIGINT\n" " cast.c0 as BIGINT. .cpu time: .+, rows: 1024. -> BIGINT\n" " c0 .cpu time: 0ns, rows: 0. -> INTEGER\n" " 3:BIGINT .cpu time: 0ns, rows: 0. -> BIGINT\n" " cast.c1 as BIGINT. .cpu time: .+, rows: 1024. -> BIGINT\n" " c1 .cpu time: 0ns, rows: 0. -> INTEGER\n" "\n" "eq .cpu time: .+, rows: 1024. -> BOOLEAN\n" " mod .cpu time: .+, rows: 1024. -> BIGINT\n" " cast.plus as BIGINT. .cpu time: .+, rows: 1024. -> BIGINT\n" " plus .cpu time: .+, rows: 1024. -> INTEGER\n" " c0 .cpu time: 0ns, rows: 0. -> INTEGER\n" " c1 .cpu time: 0ns, rows: 0. -> INTEGER\n" " 2:BIGINT .cpu time: 0ns, rows: 0. -> BIGINT\n" " 0:BIGINT .cpu time: 0ns, rows: 0. -> BIGINT\n")); } // Use dictionary encoding to repeat each row 5 times. auto indices = makeIndices(size, [](auto row) { return row / 5; }); data = makeRowVector({ wrapInDictionary(indices, size, data->childAt(0)), wrapInDictionary(indices, size, data->childAt(1)), }); { auto exprSet = compileExpressions({"(c0 + 3) * c1", "(c0 + c1) % 2 = 0"}, rowType); evaluate(*exprSet, data); ASSERT_THAT( exec::printExprWithStats(*exprSet), ::testing::MatchesRegex( "multiply .cpu time: .+, rows: 205. -> BIGINT\n" " plus .cpu time: .+, rows: 205. -> BIGINT\n" " cast.c0 as BIGINT. .cpu time: .+, rows: 205. -> BIGINT\n" " c0 .cpu time: 0ns, rows: 0. -> INTEGER\n" " 3:BIGINT .cpu time: 0ns, rows: 0. -> BIGINT\n" " cast.c1 as BIGINT. .cpu time: .+, rows: 205. -> BIGINT\n" " c1 .cpu time: 0ns, rows: 0. -> INTEGER\n" "\n" "eq .cpu time: .+, rows: 205. -> BOOLEAN\n" " mod .cpu time: .+, rows: 205. -> BIGINT\n" " cast.plus as BIGINT. .cpu time: .+, rows: 205. -> BIGINT\n" " plus .cpu time: .+, rows: 205. -> INTEGER\n" " c0 .cpu time: 0ns, rows: 0. -> INTEGER\n" " c1 .cpu time: 0ns, rows: 0. -> INTEGER\n" " 2:BIGINT .cpu time: 0ns, rows: 0. -> BIGINT\n" " 0:BIGINT .cpu time: 0ns, rows: 0. -> BIGINT\n")); } } struct Event { std::string uuid; std::unordered_map<std::string, exec::ExprStats> stats; }; class TestListener : public exec::ExprSetListener { public: explicit TestListener(std::vector<Event>& events) : events_{events} {} void onCompletion( const std::string& uuid, const exec::ExprSetCompletionEvent& event) override { events_.push_back({uuid, event.stats}); } private: std::vector<Event>& events_; }; TEST_F(ExprStatsTest, listener) { vector_size_t size = 1'024; // Register a listener to receive stats on ExprSet destruction. std::vector<Event> events; auto listener = std::make_shared<TestListener>(events); ASSERT_TRUE(exec::registerExprSetListener(listener)); ASSERT_FALSE(exec::registerExprSetListener(listener)); auto data = makeRowVector({ makeFlatVector<int32_t>(size, [](auto row) { return row; }), makeFlatVector<int32_t>(size, [](auto row) { return row % 7; }), }); // Evaluate a couple of expressions and sanity check the stats received by the // listener. auto rowType = asRowType(data->type()); { auto exprSet = compileExpressions({"(c0 + 3) * c1", "(c0 + c1) % 2 = 0"}, rowType); evaluate(*exprSet, data); } ASSERT_EQ(1, events.size()); auto stats = events.back().stats; ASSERT_EQ(1024 * 2, stats.at("plus").numProcessedRows); ASSERT_EQ(1024, stats.at("multiply").numProcessedRows); ASSERT_EQ(1024, stats.at("mod").numProcessedRows); // Evaluate the same expressions twice and verify that stats received by the // listener are "doubled". { auto exprSet = compileExpressions({"(c0 + 3) * c1", "(c0 + c1) % 2 = 0"}, rowType); evaluate(*exprSet, data); evaluate(*exprSet, data); } ASSERT_EQ(2, events.size()); stats = events.back().stats; ASSERT_EQ(1024 * 2 * 2, stats.at("plus").numProcessedRows); ASSERT_EQ(1024 * 2, stats.at("multiply").numProcessedRows); ASSERT_EQ(1024 * 2, stats.at("mod").numProcessedRows); ASSERT_NE(events[0].uuid, events[1].uuid); // Unregister the listener, evaluate expressions again and verify the listener // wasn't invoked. ASSERT_TRUE(exec::unregisterExprSetListener(listener)); ASSERT_FALSE(exec::unregisterExprSetListener(listener)); { auto exprSet = compileExpressions({"(c0 + 3) * c1", "(c0 + c1) % 2 = 0"}, rowType); evaluate(*exprSet, data); } ASSERT_EQ(2, events.size()); }
c++
code
9,138
2,299
#include "Decoder.h" #include "DecoderNonAudibleMultiTone.h" #include "ReedSolomon.h" #include <cstdio> #include <string.h> #include <math.h> #include <vector> #include <numeric> //accumulate #include "Globals.h" #if _MSC_VER >= 1800 #include <algorithm> #endif #include "SpectralAnalysis.h" #ifdef DEBUG_OUTPUT #include <iostream> #endif //DEBUG_OUTPUT using namespace BEEPING; DecoderNonAudibleMultiTone::DecoderNonAudibleMultiTone(float samplingRate, int windowSize) : Decoder(samplingRate, windowSize, Globals::numTokensNonAudible, Globals::numTonesNonAudibleMultiTone) { #ifdef _IOS_LOG_ ios_log("C++ DecoderNonAudibleMultiTone"); #endif //_IOS_LOG_ mFreq2Bin = mSpectralAnalysis->mFftSize / mSampleRate; mFreqsBins = new int[mNumTones]; for (int i = 0; i<mNumTones; i++) mFreqsBins[i] = (int)(Globals::getToneFromIdxNonAudibleMultiTone(i, mSampleRate, mWindowSize) * mFreq2Bin + .5); //Optimize size of block spectrogram (only needed bins in token space range) mBeginBin = (int)(Globals::getToneFromIdxNonAudibleMultiTone(0, mSampleRate, mWindowSize) * mFreq2Bin + .5); mEndBin = (int)(Globals::getToneFromIdxNonAudibleMultiTone(mNumTones - 1, mSampleRate, mWindowSize) * mFreq2Bin + .5); idxFrontDoorToken1 = Globals::getIdxFromChar(Globals::frontDoorTokens[0]); idxFrontDoorToken2 = Globals::getIdxFromChar(Globals::frontDoorTokens[1]); mIdxs = new int[2]; mBlockEnergyRatiosMaxToneIdx = new int[mSizeBlockCircularBuffer]; memset(mBlockEnergyRatiosMaxToneIdx, -1, mSizeBlockCircularBuffer*sizeof(int)); mBlockEnergyRatiosSecondToneIdx = new int[mSizeBlockCircularBuffer]; memset(mBlockEnergyRatiosSecondToneIdx, -1, mSizeBlockCircularBuffer*sizeof(int)); mToneRepetitions = new int[mNumTones]; memset(mToneRepetitions, 0, mNumTones*sizeof(int)); idxTonesFrontDoorToken1 = new int[2]; Globals::getIdxsFromIdxNonAudibleMultiTone(idxFrontDoorToken1, &idxTonesFrontDoorToken1); idxTonesFrontDoorToken2 = new int[2]; Globals::getIdxsFromIdxNonAudibleMultiTone(idxFrontDoorToken2, &idxTonesFrontDoorToken2); mDecodingMode = Globals::/*DECODING_MODE::*/DECODING_MODE_NONAUDIBLE; //0=AUDIBLE, 1=NONAUDIBLE, 2=HIDDEN, 3=CUSTOM } DecoderNonAudibleMultiTone::~DecoderNonAudibleMultiTone(void) { delete[] mFreqsBins; delete[] mIdxs; delete[] mBlockEnergyRatiosMaxToneIdx; delete[] mBlockEnergyRatiosSecondToneIdx; delete[] mToneRepetitions; delete[] idxTonesFrontDoorToken1; delete[] idxTonesFrontDoorToken2; } int DecoderNonAudibleMultiTone::getSizeFilledFrameCircularBuffer() { return Decoder::getSizeFilledFrameCircularBuffer(); } int DecoderNonAudibleMultiTone::getSizeFilledBlockCircularBuffer() { return Decoder::getSizeFilledBlockCircularBuffer(); } //Decode audioBuffer to check if begin token is found, we should keep previous buffer to check if token was started in previous //var mDecoding > 0 when token has been found, once decoding is finished, mDecoding = 0 int DecoderNonAudibleMultiTone::DecodeAudioBuffer(float *audioBuffer, int size) { int sizeWindow = mSpectralAnalysis->mWindowSize; int i; for(i=0; i<size; i++) { mCircularBufferFloat[(i+mWritePosInFrameCircularBuffer)%(mSizeFrameCircularBuffer)] = audioBuffer[i]; } mWritePosInFrameCircularBuffer = (size+mWritePosInFrameCircularBuffer)%(mSizeFrameCircularBuffer); while (getSizeFilledFrameCircularBuffer() >= sizeWindow) { //copy from circularBufferFloat to sendBuffer for (i=0;i<sizeWindow;i++) mAnalBufferFloat[i] = mCircularBufferFloat[(i+mReadPosInFrameCircularBuffer)%(mSizeFrameCircularBuffer)]; mReadPosInFrameCircularBuffer = (mReadPosInFrameCircularBuffer+mSpectralAnalysis->mHopSize)%(mSizeFrameCircularBuffer); if (mDecoding == 0) { int ret = AnalyzeStartTokens(mAnalBufferFloat); if (ret == 1) { mDecoding = 1; mConfidenceEnergyRatios = 0.f; mConfidenceRepetitions = 0.f; mConfidence = 0.f; //reset confidence mReceivedBeepsVolume = 0.f; // add frontdoor values to the input vector mDecodedValues.push_back(idxFrontDoorToken1); //front-door symbols mDecodedValues.push_back(idxFrontDoorToken2); //front-door symbols return -2; //-2 means start token found } } else if ((mDecoding > 0) && (mDecoding <= Globals::numMessageTokens)) //we already found start token, now start decoding { int ret = AnalyzeToken(mAnalBufferFloat); if (ret >= 0) { mDecodedValues.push_back(ret); mDecoding++; return ret; } } else if (mDecoding > Globals::numMessageTokens) //we have finished decoding a complete word { mDecoding = 0; mConfidenceEnergyRatios = mConfidenceEnergyRatios / Globals::numMessageTokens; mConfidenceRepetitions = mConfidenceRepetitions / Globals::numMessageTokens; mConfidenceRepetitions = (mConfidenceRepetitions / 2.f) + 0.5f; mReceivedBeepsVolume = mReceivedBeepsVolume / Globals::numMessageTokens; return -3; //-3 means that complete word has been decoded } } return -1; } int DecoderNonAudibleMultiTone::GetDecodedData(char *stringDecoded) { int messageOk = 1; // init ReedSolomon functions (set message length) mReedSolomon->msg_len = mMessageLength; // messagelength=(2 frontdoor + 9/10 digits + 1/0 correction code (if any)) //save check token int checkTokenReceived = mDecodedValues[Globals::numFrontDoorTokens+Globals::numWordTokens]; int sizeTokensNoCorrection = Globals::numTotalTokens - Globals::numCorrectionTokens; for (int i = 0; i < sizeTokensNoCorrection; i++) mDecodedValuesOrig[i] = mDecodedValues[i]; // decode ReedSolomon error correction mReedSolomon->SetCode(mDecodedValues); mReedSolomon->Decode(); mReedSolomon->GetMessage(mDecodedValues); int count = 0; for (int i = 0; i < sizeTokensNoCorrection; i++) { if (mDecodedValues[i] == mDecodedValuesOrig[i]) count++; } mConfidenceCorrection = (float)count / (float)sizeTokensNoCorrection; #ifdef DEBUG_OUTPUT //PRINT DEBUG STATISTICS std::cout << " " << " [Prob (correction):" << mConfidenceCorrection << "]" << std::endl; #endif //DEBUG_OUTPUT checkTokenReceived = mDecodedValues[Globals::numFrontDoorTokens+Globals::numWordTokens]; //check if decoded word is ok using check token int checkToken = 0; for (int i=Globals::numFrontDoorTokens;i<(Globals::numFrontDoorTokens+Globals::numWordTokens);i++) checkToken += mDecodedValues[i]; checkToken = checkToken % mNumTokens; if (checkToken != checkTokenReceived) messageOk = -1; memset(mDecodedString,0,MAX_DECODE_STRING_SIZE*sizeof(char)); int len = mDecodedValues.size()-1; for (int i=Globals::numFrontDoorTokens; i<len; ++i) { mDecodedString[i-Globals::numFrontDoorTokens] = Globals::getCharFromIdx(mDecodedValues[i]); } mDecodedString[len-Globals::numFrontDoorTokens] = '\0'; //Set terminating character, although buffer was already initialized with zeros strncpy(stringDecoded, mDecodedString, (len-Globals::numFrontDoorTokens)+1); //to include terminating character //mDecodedString[0] = '\0'; memset(mDecodedString,0,MAX_DECODE_STRING_SIZE*sizeof(char)); //initialize for next transmission mDecodedValues.clear(); //clear decoded values for next transmission return (len-Globals::numFrontDoorTokens) * messageOk; //If message is wrong (token check failed) it returns a negative value } int DecoderNonAudibleMultiTone::GetSpectrum(float *spectrumBuffer) { return Decoder::GetSpectrum(spectrumBuffer); } int DecoderNonAudibleMultiTone::AnalyzeStartTokens(float *audioBuffer) { //float *magSpectrum, float* realSpectrum, float* imagSpectrum mSpectralAnalysis->doFFT(audioBuffer, mSpectralAnalysis->mSpecMag, mSpectralAnalysis->mSpecPhase); memcpy(mBlockSpecMag[mWritePosInBlockCircularBuffer % mSizeBlockCircularBuffer], mSpectralAnalysis->mSpecMag, mSpectralAnalysis->mSpecSize*sizeof(float)); //needed because when starting decoding we need past spectrogram //computeStats ComputeStatsStartTokens(); //Get sorted mEnergyRatiosIndices for (int i = 0; i<mNumTones; i++) { mEnergyRatiosSorted[i] = mEnergyRatios[i]; mEnergyRatiosIdx[i] = i; } int c, d, idx; float swap; for (c = 0; c<mNumTones - 1; c++) { for (d = 0; d<mNumTones - c - 1; d++) { if (mEnergyRatiosSorted[d] < mEnergyRatiosSorted[d + 1]) // For increasing order use > { swap = mEnergyRatiosSorted[d]; mEnergyRatiosSorted[d] = mEnergyRatiosSorted[d + 1]; mEnergyRatiosSorted[d + 1] = swap; idx = mEnergyRatiosIdx[d]; mEnergyRatiosIdx[d] = mEnergyRatiosIdx[d + 1]; mEnergyRatiosIdx[d + 1] = idx; } } } int idx_a1 = mEnergyRatiosIdx[0]; int idx_a2 = mEnergyRatiosIdx[1]; int idx_a3 = mEnergyRatiosIdx[2]; int idx_a4 = mEnergyRatiosIdx[3]; int pos = mWritePosInBlockCircularBuffer % mSizeBlockCircularBuffer; mBlockEnergyRatiosTokenIdx[pos] = idx_a1; mBlockEnergyRatiosTokenIdx2[pos] = idx_a2; mBlockEnergyRatiosTokenIdx3[pos] = idx_a3; mBlockEnergyRatiosTokenIdx4[pos] = idx_a4; #ifdef _ANDROID_LOG_ char text[500]; sprintf(text, "mBlockEnergyRatios[%d]: %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", mSizeBlockCircularBuffer, mBlockEnergyRatiosTokenIdx[0], mBlockEnergyRatiosTokenIdx[1], mBlockEnergyRatiosTokenIdx[2], mBlockEnergyRatiosTokenIdx[3], mBlockEnergyRatiosTokenIdx[4], mBlockEnergyRatiosTokenIdx[5], mBlockEnergyRatiosTokenIdx[6], mBlockEnergyRatiosTokenIdx[7], mBlockEnergyRatiosTokenIdx[8], mBlockEnergyRatiosTokenIdx[9], mBlockEnergyRatiosTokenIdx[10], mBlockEnergyRatiosTokenIdx[11], mBlockEnergyRatiosTokenIdx[12], mBlockEnergyRatiosTokenIdx[13], mBlockEnergyRatiosTokenIdx[14], mBlockEnergyRatiosTokenIdx[15]); __android_log_write(ANDROID_LOG_INFO, "BeepingCoreLibInfo", text);//Or ANDROID_LOG_INFO, ... //__android_log_write(ANDROID_LOG_INFO, "BeepingCoreLibInfo", pStringDecoded);//Or ANDROID_LOG_INFO, ... #endif mWritePosInBlockCircularBuffer = (mWritePosInBlockCircularBuffer + 1) % (mSizeBlockCircularBuffer); #ifdef _ANDROID_LOG_ char text2[150]; sprintf(text2, "sizeFilled: %d | r:%d w:%d", getSizeFilledBlockCircularBuffer(), mReadPosInBlockCircularBuffer, mWritePosInBlockCircularBuffer); __android_log_write(ANDROID_LOG_INFO, "BeepingCoreLibInfo", text2);//Or ANDROID_LOG_INFO, ... //__android_log_write(ANDROID_LOG_INFO, "BeepingCoreLibInfo", pStringDecoded);//Or ANDROID_LOG_INFO, ... #endif while (getSizeFilledBlockCircularBuffer() >= mSizeBlockCircularBuffer - 1) { int firstTokenRepetitions = 0; for (int i = 0; i<(mSizeBlockCircularBuffer / 2); i++) { int posIdx = (mReadPosInBlockCircularBuffer + i) % mSizeBlockCircularBuffer; if ( (mBlockEnergyRatiosTokenIdx[posIdx] == idxTonesFrontDoorToken1[0])/* || (mBlockEnergyRatiosTokenIdx2[posIdx] == idxTonesFrontDoorToken1[0])*/ ) firstTokenRepetitions++; //if ((mBlockEnergyRatiosTokenIdx[posIdx] == idxTonesFrontDoorToken1[1]) || // (mBlockEnergyRatiosTokenIdx2[posIdx] == idxTonesFrontDoorToken1[1])) // firstTokenRepetitions++; } //firstTokenRepetitions = firstTokenRepetitions / 2; //Only continue if long firstToken is found if (firstTokenRepetitions >= ((mSizeBlockCircularBuffer / 2) - mnToleranceFrames)) { int secondTokenRepetitions = 0; for (int i = (mSizeBlockCircularBuffer / 2); i < mSizeBlockCircularBuffer; i++) { int posIdx = (mReadPosInBlockCircularBuffer + i) % mSizeBlockCircularBuffer; if ( (mBlockEnergyRatiosTokenIdx[posIdx] == idxTonesFrontDoorToken2[0]) || (mBlockEnergyRatiosTokenIdx2[posIdx] == idxTonesFrontDoorToken2[0])/* || (mBlockEnergyRatiosTokenIdx3[posIdx] == idxTonesFrontDoorToken2[0]) || (mBlockEnergyRatiosTokenIdx4[posIdx] == idxTonesFrontDoorToken2[0])*/ ) secondTokenRepetitions++; //if ((mBlockEnergyRatiosTokenIdx[posIdx] == idxTonesFrontDoorToken2[1]) || // (mBlockEnergyRatiosTokenIdx2[posIdx] == idxTonesFrontDoorToken2[1]) || // (mBlockEnergyRatiosTokenIdx3[posIdx] == idxTonesFrontDoorToken2[1]) || // (mBlockEnergyRatiosTokenIdx4[posIdx] == idxTonesFrontDoorToken2[1])) // secondTokenRepetitions++; } //secondTokenRepetitions = secondTokenRepetitions / 2; //if (secondTokenRepetitions >= ((mSizeBlockCircularBuffer / 2) - mnToleranceFrames)) if (secondTokenRepetitions >= ((mSizeBlockCircularBuffer / 2) - (mnToleranceFrames*2))) //allow 10% tolerance for second start token { //advance buffer read pos mReadPosInBlockCircularBuffer = mWritePosInBlockCircularBuffer; mEndStartTokenPosInBlockCircularBuffer = mReadPosInBlockCircularBuffer; mAccumulatedDecodingFrames = 0.0; return 1; } else { mReadPosInBlockCircularBuffer = (mReadPosInBlockCircularBuffer + 1) % (mSizeBlockCircularBuffer); } } else { mReadPosInBlockCircularBuffer = (mReadPosInBlockCircularBuffer + 1) % (mSizeBlockCircularBuffer); } } return 0; } int DecoderNonAudibleMultiTone::AnalyzeToken(float *audioBuffer) { //float *magSpectrum, float* realSpectrum, float* imagSpectrum mSpectralAnalysis->doFFT(audioBuffer, mSpectralAnalysis->mSpecMag, mSpectralAnalysis->mSpecPhase); //fill Spectrum CircularBuffer memcpy(mBlockSpecMag[mWritePosInBlockCircularBuffer % mSizeBlockCircularBuffer], mSpectralAnalysis->mSpecMag, mSpectralAnalysis->mSpecSize*sizeof(float)); //mBlockSpecMag mWritePosInBlockCircularBuffer = (mWritePosInBlockCircularBuffer+1)%(mSizeBlockCircularBuffer); while (getSizeFilledBlockCircularBuffer() >= (mSizeBlockCircularBuffer/2)) { //we have a new filled block of (durToken size) //Apply dereverb here! //DeReverb Spectrogram (mBlockSpecMag) //int nbins = (mEndBinBlock-mBeginBinBlock)+1; //int nbins = (mEndBin-mBeginBin)+1; //DeReverbToken(nbins, mFreqsBins); //not needed anymore, now we are varying the base freq between odd and even ComputeStats(); //NEW METHOD for (int i = 0; i<mNumTones; i++) { mToneRepetitions[i] = 0; } for (int i = 0; i<(mSizeBlockCircularBuffer / 2); i++) { int s = (mReadPosInBlockCircularBuffer + i) % mSizeBlockCircularBuffer; int idx = mBlockEnergyRatiosMaxToneIdx[s]; mToneRepetitions[idx]++; idx = mBlockEnergyRatiosSecondToneIdx[s]; mToneRepetitions[idx]++; //Statistics mBlockTokenStatistics[s].idxToken = Globals::getIdxTokenFromIdxsTonesNonAudibleMultiTone(mBlockTokenStatistics[s].idxToneMax, mBlockTokenStatistics[s].idxToneSecond); mBlockTokenStatistics[s].energyRatioToken = (mBlockTokenStatistics[s].energyRatioToneMax + mBlockTokenStatistics[s].energyRatioToneSecond) / 2.f; } int max1 = Globals::maxValueIdx(mToneRepetitions, mNumTones); int max2 = Globals::secondValueIdx(mToneRepetitions, mNumTones); int max = Globals::getIdxTokenFromIdxsTonesNonAudibleMultiTone(max1, max2); //mBlockEnergyRatiosMaxToneIdx[s], mBlockEnergyRatiosSecondToneIdx[s] //Calculate probability int count = 0; float prob = 0.f; float prob_combined = 0.f; float energy = 0.f; for (int i = 0; i < (mSizeBlockCircularBuffer / 2); i++) { int s = (mReadPosInBlockCircularBuffer + i) % mSizeBlockCircularBuffer; if (mBlockTokenStatistics[s].idxToken == max) { prob += mBlockTokenStatistics[s].energyRatioToken; energy += mBlockTokenStatistics[s].energyToken; count++; } } prob_combined = prob / (float)(mSizeBlockCircularBuffer / 2); if (count > 1) prob /= (float)count; //mConfidenceEnergyRatios += prob; mConfidenceEnergyRatios += prob_combined; mReceivedBeepsVolume += energy / (float)(mSizeBlockCircularBuffer / 2); #ifdef DEBUG_OUTPUT //PRINT DEBUG STATISTICS std::cout << " [DEBUG_OUTPUT] " << "Token: " << max << " Prob: " << (((float)mToneRepetitions[max1] + (float)mToneRepetitions[max2]) / (float)mSizeBlockCircularBuffer) << " max1:" << mToneRepetitions[max1] << " max2:" << mToneRepetitions[max2] << std::endl; std::cout << " " << " Prob2:" << prob << std::endl; std::cout << " " << " Prob3 (combined):" << prob_combined << std::endl; std::cout << " " << " energy:" << 20 * log10(energy / (float)(mSizeBlockCircularBuffer / 2)) << std::endl; #endif //DEBUG_OUTPUT //END NEW METHOD //Update statistics mConfidenceRepetitions += ((float)mToneRepetitions[max1] + (float)mToneRepetitions[max2]) / (float)mSizeBlockCircularBuffer; //OLD METHOD /* for (int i = 0; i<mNumTokens; i++) { mTokenRepetitions[i] = 0; } //remove reverb //int reverbFrames = (int)( ((float)mSizeBlockCircularBuffer / 2.f) * 0.10f + .5f); //was 0.25 int reverbFrames = 0; for (int i=reverbFrames;i<(mSizeBlockCircularBuffer/2);i++) { int idx = mBlockEnergyRatiosTokenIdx[(mReadPosInBlockCircularBuffer+i)%mSizeBlockCircularBuffer]; mTokenRepetitions[idx]++; } int max = Globals::maxValueIdx(mTokenRepetitions, mNumTokens); #ifdef DEBUG_OUTPUT //PRINT DEBUG STATISTICS std::cout << " [DEBUG_OUTPUT] " << "Token: " << max << " Prob: " << ((float)mTokenRepetitions[max]/((float)mSizeBlockCircularBuffer/2.f)) << "max:" << mTokenRepetitions[max] << std::endl; #endif //DEBUG_OUTPUT */ //END OLD METHOD //TODO: advance read pos (make sure is the correct advance!! mAccumulatedDecodingFrames += mSizeBlockCircularBuffer / 2.0; int offset = (int)(mAccumulatedDecodingFrames + .5); mReadPosInBlockCircularBuffer = (mEndStartTokenPosInBlockCircularBuffer + offset) % mSizeBlockCircularBuffer; //compute thresholds based on senitivity parameter. TODO: apply this?? /* float sensitivity = 0.5; // the higher the more sensivity has the algorithm. [0..-1] float ratiosThres = std::min(-18.f, std::max(-26.f, -26.f + (1.f-sensitivity)*12.f)); // range [-26..-18] def -20 float diffThres = std::min(-6.f, std::max( -30.f, -30.f + (1.f-sensitivity)*24.f)); // range [-13..-7] def -10 if ( (maxEnergyRatios > ratiosThres) && (maxEnergyDiff > diffThres) ) { printf("not enough energy"); }*/ return max; //token found } return -1; } //This function is called every frame int DecoderNonAudibleMultiTone::ComputeStatsStartTokens() { //energy mean in the alphabet frequency region float energyBlock = 0.f; //Old implementation using only instantaneous Spectrum for (int i=mBeginBin;i<=mEndBin;i++) { energyBlock+=mSpectralAnalysis->mSpecMag[i]; } energyBlock = energyBlock / (float)(mEndBin-mBeginBin+1); for (int i = 0; i<mNumTones; i++) { int evalToneBin = mFreqsBins[i]; for (int n = 0; n<mSizeTokenBinAnal; n++) { mEvalToneMags[n] = mSpectralAnalysis->mSpecMag[evalToneBin - mBinWidth + n]; //mEvalToneMags[n] = mBlockSpecMag[(mReadPosInBlockCircularBuffer + t) % mSizeBlockCircularBuffer][evalToneBin - mBinWidth + n]; } double sum = Globals::sum(mEvalToneMags, mSizeTokenBinAnal); double energyTone = sum / mSizeTokenBinAnal; mEnergyRatios[i] = 20.0*log10((energyTone) / energyBlock); // difference of 3dB } return 0; } //This function is called every token block, so not so frequent (every tokendur ms) int DecoderNonAudibleMultiTone::ComputeStats() { //energy mean in the alphabet frequency region double energyBlock = 0.0; //New implementation using Spectrogram for (int t=0;t<(mSizeBlockCircularBuffer/2);t++) { for (int i=mBeginBin;i<=mEndBin;i++) { energyBlock+=mBlockSpecMag[(mReadPosInBlockCircularBuffer+t)%mSizeBlockCircularBuffer][i]; } } energyBlock = energyBlock / ((d
c++
code
20,000
3,713
#include "NeoPixelEmulator.h" #include "stdio.h" #define M_PI 3.14159265358979323846 NeoPixelEmulator::NeoPixelEmulator(uint16_t numLEDs, uint8_t p, uint8_t t) : pixels(numLEDs, 0) { } NeoPixelEmulator::~NeoPixelEmulator() { } void NeoPixelEmulator::setPixelLayout(PixelLayout pixelLayout) { _pixelLayout = pixelLayout; } void NeoPixelEmulator::begin(void) { } void NeoPixelEmulator::show(void) { glClear(GL_COLOR_BUFFER_BIT); switch (_pixelLayout) { case Strip: drawLedStrip(); break; case Ring: drawLedRing(); break; case Grid: drawLedGrid(); break; } // Double buffering. glutSwapBuffers(); // GLUT process events, redrew screen. glutMainLoopEvent(); } void NeoPixelEmulator::setPin(uint8_t) { } // Set pixel color from separate R,G,B components: void NeoPixelEmulator::setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b) { if (n < pixels.size()) { setPixelColor(n, Color(r, g, b)); } } // Set pixel color from 'packed' 32-bit RGB color: void NeoPixelEmulator::setPixelColor(uint16_t n, uint32_t c) { if (n < pixels.size()) { pixels[n] = c; } } // Convert separate R,G,B into packed 32-bit RGB color. // Packed format is always RGB, regardless of LED strand color order. uint32_t NeoPixelEmulator::Color(uint8_t r, uint8_t g, uint8_t b) { return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; } // Query color from previously-set pixel (returns packed 32-bit RGB value) uint32_t NeoPixelEmulator::getPixelColor(uint16_t n) const { if (n >= pixels.size()) { return 0; } return pixels[n]; } // Returns pointer to pixels[] array. Pixel data is stored in device- // native format and is not translated here. Application will need to be // aware whether pixels are RGB vs. GRB and handle colors appropriately. // *** Interface change: Removed const on function. Don't know how // the Adafruit implementation was able to return non-const pointer from // const function there. uint8_t* NeoPixelEmulator::getPixels(void) { return reinterpret_cast<uint8_t*>(&pixels[0]); } uint16_t NeoPixelEmulator::numPixels(void) const { return pixels.size(); } void NeoPixelEmulator::setBrightness(uint8_t) { } uint8_t NeoPixelEmulator::getBrightness(void) const { return 255; } void NeoPixelEmulator::clear() { std::fill(pixels.begin(), pixels.end(), 0); } // // OpenGL. // const int maxLedRadius = 50; void NeoPixelEmulator::drawLedStrip() { float xCenter = 500.0f; float yCenter = 500.0f; float maxLedRadius = 50.0f; float maxSize = 760.0f; float ledToSpaceRatio = 1.5f; float ledRadius = maxLedRadius; float ledAndSpaceSize = ledRadius * ledToSpaceRatio; float size = numPixels() * ledAndSpaceSize; if (size > maxSize) { size = maxSize; ledRadius = size / numPixels() / ledToSpaceRatio; ledAndSpaceSize = ledRadius * ledToSpaceRatio; } for (int x = 0; x < numPixels(); ++x) { uint32_t c = pixels[x]; uint8_t R, G, B; colorPackedToScalar(&R, &G, &B, c); drawFilledCircle(xCenter - size / 2.0f + (ledAndSpaceSize / 2.0f) + x * ledAndSpaceSize, yCenter, ledRadius, R, G, B); } } void NeoPixelEmulator::drawLedRing() { float xCenter = 500.0f; float yCenter = 500.0f; float maxCircleRadius = 380.0f; float maxLedRadius = 50.0f; float ledToSpaceRatio = 2.0f; float ledRadius = maxLedRadius; float circleRadius = numPixels() * (ledRadius * ledToSpaceRatio) / (2.0f * M_PI); if (circleRadius > maxCircleRadius) { circleRadius = maxCircleRadius; float c = circleRadius * 2.0f * M_PI; ledRadius = c / numPixels() / ledToSpaceRatio; } for (int i = 0; i < numPixels(); ++i) { uint32_t c = pixels[i]; uint8_t R, G, B; colorPackedToScalar(&R, &G, &B, c); drawFilledCircle(xCenter + (circleRadius * cos(i * 2.0f * M_PI / numPixels())), yCenter + (circleRadius * sin(i * 2.0f * M_PI / numPixels())), ledRadius, R, G, B); } } // Draw LED grid where the LEDs are ordered in a continuous, back-and-forth sequence. void NeoPixelEmulator::drawLedGrid() { float xCenter = 500.0f; float yCenter = 500.0f; float maxLedRadius = 50.0f; float maxDimSize = 760.0f; float ledToSpaceRatio = 1.5f; int numLedsEachDim = sqrt(numPixels()); float ledRadius = maxLedRadius; float ledAndSpaceSize = ledRadius * ledToSpaceRatio; float dimSize = numLedsEachDim * ledAndSpaceSize; if (dimSize > maxDimSize) { dimSize = maxDimSize; ledRadius = dimSize / numLedsEachDim / ledToSpaceRatio; ledAndSpaceSize = ledRadius * ledToSpaceRatio; } int numLedsX = numLedsEachDim; int numLedsY = numLedsEachDim; for (int y = 0; y < numLedsY; ++y) { for (int x = 0; x < numLedsX; ++x) { uint32_t c; if (y & 1) { c = pixels[x + y * numLedsX]; } else { c = pixels[numLedsX - x - 1 + y * numLedsX]; } uint8_t R, G, B; colorPackedToScalar(&R, &G, &B, c); drawFilledCircle(xCenter - dimSize / 2.0f + (ledAndSpaceSize / 2.0f) + x * ledAndSpaceSize, yCenter - dimSize / 2.0f + (ledAndSpaceSize / 2.0f) + y * ledAndSpaceSize, ledRadius, R, G, B); } } } void NeoPixelEmulator::drawFilledCircle(float x, float y, float r, u8 R, u8 G, u8 B) { glColor3ub(R, G, B); glPointSize(r); glBegin(GL_POINTS); glVertex2f(x, y); glEnd(); } // When using AA with this method, I get some undrawn pixels radiating out from // the center. I'd like to find out why. void NeoPixelEmulator::__drawFilledCircle(float x, float y, float r) { int numTriangles = 30; glBegin(GL_TRIANGLE_FAN); glVertex2f(x, y); for (int i = 0; i <= numTriangles; ++i) { glVertex2f(x + (r * cos(i * 2.0f * M_PI / numTriangles)), y + (r * sin(i * 2.0f * M_PI / numTriangles))); } glEnd(); } void NeoPixelEmulator::colorPackedToScalar(uint8_t* R, uint8_t* G, uint8_t* B, uint32_t color) { *B = color; color >>= 8; *G = color; color >>= 8; *R = color; }
c++
code
6,416
1,356
#include "PixelShader.h" #include "GraphicsThrowMacros.h" #include <d3dcompiler.h> PixelShader::PixelShader(Graphics& gfx, const std::wstring& path) { INFOMAN(gfx); Microsoft::WRL::ComPtr<ID3DBlob> pBlob; GFX_THROW_INFO(D3DReadFileToBlob(path.c_str(), &pBlob)); GFX_THROW_INFO(GetDevice(gfx)->CreatePixelShader(pBlob->GetBufferPointer(), pBlob->GetBufferSize(), nullptr, &pPixelShader)); } void PixelShader::Bind(Graphics& gfx) noexcept { GetContext(gfx)->PSSetShader(pPixelShader.Get(), nullptr, 0u); }
c++
code
511
129
// Copyright Oliver Kowalke 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "boost/fiber/numa/pin_thread.hpp" extern "C" { #include <windows.h> } #include <cstring> #include <system_error> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace fibers { namespace numa { BOOST_FIBERS_DECL void pin_thread( std::uint32_t cpuid) { pin_thread( cpuid, ::GetCurrentThread() ); } BOOST_FIBERS_DECL void pin_thread( std::uint32_t cpuid, std::thread::native_handle_type h) { GROUP_AFFINITY affinity; std::memset( & affinity, 0, sizeof( affinity) ); // compute processor group // a group contains max 64 logical CPUs affinity.Group = static_cast< WORD >(cpuid / 64); // compute the ID of the logical CPU in the group uint32_t id = cpuid % 64; // set the bit mask of the logical CPU affinity.Mask = static_cast< KAFFINITY >( 1) << id; if ( BOOST_UNLIKELY( 0 == ::SetThreadGroupAffinity( h, & affinity, nullptr) ) ) { throw std::system_error( std::error_code( ::GetLastError(), std::system_category() ), "::SetThreadiGroupAffinity() failed"); } } }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif
c++
code
1,378
272
// Copyright (c) Microsoft Corporation // SPDX-License-Identifier: MIT #include <cmath> #include <iostream> #include <map> #include <sstream> #include <string> #include <vector> #include <string.h> extern "C" { #include "bpf2c.h" } #if !defined(C_NAME) #define C_NAME test_metadata_table #endif extern "C" metadata_table_t C_NAME; static uint64_t gather_bytes(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { return ((uint64_t)a << 32) | ((uint32_t)b << 24) | ((uint32_t)c << 16) | ((uint16_t)d << 8) | e; }; static uint64_t memfrob(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { uint8_t* p = reinterpret_cast<uint8_t*>(a); for (uint64_t i = 0; i < b; i++) { p[i] ^= 42; } return 0; }; static uint64_t trash_registers(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { /* Overwrite all caller-save registers */ asm("mov $0xf0, %rax;" "mov $0xf1, %rcx;" "mov $0xf2, %rdx;" "mov $0xf3, %rsi;" "mov $0xf4, %rdi;" "mov $0xf5, %r8;" "mov $0xf6, %r9;" "mov $0xf7, %r10;" "mov $0xf8, %r11;"); return 0; } static uint64_t sqrti(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { return static_cast<uint64_t>(std::sqrt(a)); } static uint64_t strcmp_ext(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { return strcmp(reinterpret_cast<char*>(a), reinterpret_cast<char*>(b)); } static uint64_t unwind(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e) { return a; } std::map<uint32_t, uint64_t (*)(uint64_t r1, uint64_t r2, uint64_t r3, uint64_t r4, uint64_t r5)> helper_functions = { {0, gather_bytes}, {1, memfrob}, {2, trash_registers}, {3, sqrti}, {4, strcmp_ext}, {5, unwind}, }; extern "C" void division_by_zero(uint32_t address) { std::cerr << "BPF program hit divide by zero at PC=" << address << std::endl; } int main(int argc, char** argv) { uint64_t expected_result = 0; std::vector<uint8_t> mem; if (argc < 2) { std::cerr << "Usage: " << argv[0] << " expected_result data" << std::endl; return -1; } expected_result = strtoull(argv[1], NULL, 16); if (argc == 3) { std::string byte; std::stringstream data_string(argv[2]); while (std::getline(data_string, byte, ' ')) { if (byte.empty()) continue; mem.push_back(static_cast<uint8_t>(std::strtoul(byte.c_str(), NULL, 16))); } } helper_function_entry_t* helper_function_entries = nullptr; size_t helper_function_entry_count = 0; map_entry_t* map_entries = nullptr; size_t map_entry_count = 0; program_entry_t* program_entries = nullptr; size_t program_entry_count = 0; C_NAME.helpers(&helper_function_entries, &helper_function_entry_count); C_NAME.maps(&map_entries, &map_entry_count); C_NAME.programs(&program_entries, &program_entry_count); if (map_entry_count != 0) { std::cout << "bpf_test doesn't support maps yet." << std::endl; return -1; } for (size_t index = 0; index < helper_function_entry_count; index++) { if (helper_function_entries[index].helper_id == -1) { std::cout << "bpf_test doesn't support resolving helpers by name yet." << std::endl; return -1; } if (helper_functions.find(helper_function_entries[index].helper_id) == helper_functions.end()) { std::cout << "bpf_test doesn't support helper id=" << helper_function_entries[index].helper_id << std::endl; return -1; } else { helper_function_entries[index].address = helper_functions[helper_function_entries[index].helper_id]; if (helper_function_entries[index].address == unwind) { helper_function_entries[index].tail_call = true; } } } uint64_t actual_result = program_entries[0].function(mem.data()); if (expected_result != actual_result) { std::cerr << argv[0] << " Expected result = " << expected_result << " Actual result = " << actual_result << std::endl; return 1; } return 0; }
c++
code
4,212
1,020
// Copyright 2021 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/fuchsia.posix.socket.packet/cpp/wire_test_base.h> #include <fidl/fuchsia.posix.socket.raw/cpp/wire_test_base.h> #include <fidl/fuchsia.posix.socket/cpp/wire_test_base.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/zx/eventpair.h> #include <lib/zx/socket.h> #include <lib/zxio/cpp/create_with_type.h> #include <lib/zxio/zxio.h> #include <zircon/types.h> #include <zxtest/zxtest.h> #include "sdk/lib/zxio/private.h" namespace { class DatagramSocketServer final : public fidl::testing::WireTestBase<fuchsia_posix_socket::DatagramSocket> { public: DatagramSocketServer() = default; void NotImplemented_(const std::string& name, ::fidl::CompleterBase& completer) final { ADD_FAILURE("unexpected message received: %s", name.c_str()); completer.Close(ZX_ERR_NOT_SUPPORTED); } void Clone(CloneRequestView request, CloneCompleter::Sync& completer) final { completer.Close(ZX_ERR_NOT_SUPPORTED); } void CloseDeprecated(CloseDeprecatedRequestView request, CloseDeprecatedCompleter::Sync& completer) final { completer.Reply(ZX_OK); completer.Close(ZX_OK); } void Close(CloseRequestView request, CloseCompleter::Sync& completer) final { completer.ReplySuccess(); completer.Close(ZX_OK); } }; class DatagramSocketTest : public zxtest::Test { public: void SetUp() final { ASSERT_OK(zx::eventpair::create(0u, &event0_, &event1_)); zx::status node_server = fidl::CreateEndpoints(&client_end_); ASSERT_OK(node_server.status_value()); fidl::BindServer(control_loop_.dispatcher(), std::move(*node_server), &server_); control_loop_.StartThread("control"); } void Init() { ASSERT_OK(zxio_datagram_socket_init(&storage_, TakeEvent(), TakeClientEnd())); zxio_ = &storage_.io; } void TearDown() final { if (zxio_) { ASSERT_OK(zxio_close(zxio_)); } control_loop_.Shutdown(); } zx::eventpair TakeEvent() { return std::move(event0_); } fidl::ClientEnd<fuchsia_posix_socket::DatagramSocket> TakeClientEnd() { return std::move(client_end_); } zxio_storage_t* storage() { return &storage_; } zxio_t* zxio() { return zxio_; } private: zxio_storage_t storage_; zxio_t* zxio_{nullptr}; zx::eventpair event0_, event1_; fidl::ClientEnd<fuchsia_posix_socket::DatagramSocket> client_end_; DatagramSocketServer server_; async::Loop control_loop_{&kAsyncLoopConfigNoAttachToCurrentThread}; }; } // namespace TEST_F(DatagramSocketTest, Basic) { Init(); } TEST_F(DatagramSocketTest, Release) { Init(); zx_handle_t handle = ZX_HANDLE_INVALID; EXPECT_OK(zxio_release(zxio(), &handle)); EXPECT_NE(handle, ZX_HANDLE_INVALID); EXPECT_OK(zx_handle_close(handle)); } TEST_F(DatagramSocketTest, Borrow) { Init(); zx_handle_t handle = ZX_HANDLE_INVALID; EXPECT_OK(zxio_borrow(zxio(), &handle)); EXPECT_NE(handle, ZX_HANDLE_INVALID); } TEST_F(DatagramSocketTest, CreateWithType) { ASSERT_OK(zxio_create_with_type(storage(), ZXIO_OBJECT_TYPE_DATAGRAM_SOCKET, TakeEvent().release(), TakeClientEnd().TakeChannel().release())); ASSERT_OK(zxio_close(&storage()->io)); } TEST_F(DatagramSocketTest, CreateWithTypeWrapper) { ASSERT_OK(zxio::CreateDatagramSocket(storage(), TakeEvent(), TakeClientEnd())); ASSERT_OK(zxio_close(&storage()->io)); } namespace { class StreamSocketServer final : public fidl::testing::WireTestBase<fuchsia_posix_socket::StreamSocket> { public: StreamSocketServer() = default; void NotImplemented_(const std::string& name, ::fidl::CompleterBase& completer) final { ADD_FAILURE("unexpected message received: %s", name.c_str()); completer.Close(ZX_ERR_NOT_SUPPORTED); } void CloseDeprecated(CloseDeprecatedRequestView request, CloseDeprecatedCompleter::Sync& completer) override { completer.Reply(ZX_OK); completer.Close(ZX_OK); } void Close(CloseRequestView request, CloseCompleter::Sync& completer) override { completer.ReplySuccess(); completer.Close(ZX_OK); } }; class StreamSocketTest : public zxtest::Test { public: void SetUp() final { ASSERT_OK(zx::socket::create(ZX_SOCKET_STREAM, &socket_, &peer_)); ASSERT_OK(socket_.get_info(ZX_INFO_SOCKET, &info_, sizeof(info_), nullptr, nullptr)); zx::status server_end = fidl::CreateEndpoints(&client_end_); ASSERT_OK(server_end.status_value()); fidl::BindServer(control_loop_.dispatcher(), std::move(*server_end), &server_); control_loop_.StartThread("control"); } void Init() { ASSERT_OK(zxio_stream_socket_init(&storage_, TakeSocket(), TakeClientEnd(), info())); zxio_ = &storage_.io; } void TearDown() final { if (zxio_) { ASSERT_OK(zxio_close(zxio_)); } control_loop_.Shutdown(); } zx_info_socket_t& info() { return info_; } zx::socket TakeSocket() { return std::move(socket_); } fidl::ClientEnd<fuchsia_posix_socket::StreamSocket> TakeClientEnd() { return std::move(client_end_); } zxio_storage_t* storage() { return &storage_; } zxio_t* zxio() { return zxio_; } private: zxio_storage_t storage_; zxio_t* zxio_{nullptr}; zx_info_socket_t info_; zx::socket socket_, peer_; fidl::ClientEnd<fuchsia_posix_socket::StreamSocket> client_end_; StreamSocketServer server_; async::Loop control_loop_{&kAsyncLoopConfigNoAttachToCurrentThread}; }; } // namespace TEST_F(StreamSocketTest, Basic) { Init(); } TEST_F(StreamSocketTest, Release) { Init(); zx_handle_t handle = ZX_HANDLE_INVALID; EXPECT_OK(zxio_release(zxio(), &handle)); EXPECT_NE(handle, ZX_HANDLE_INVALID); EXPECT_OK(zx_handle_close(handle)); } TEST_F(StreamSocketTest, Borrow) { Init(); zx_handle_t handle = ZX_HANDLE_INVALID; EXPECT_OK(zxio_borrow(zxio(), &handle)); EXPECT_NE(handle, ZX_HANDLE_INVALID); } TEST_F(StreamSocketTest, CreateWithType) { ASSERT_OK(zxio_create_with_type(storage(), ZXIO_OBJECT_TYPE_STREAM_SOCKET, TakeSocket().release(), TakeClientEnd().TakeChannel().release(), &info())); ASSERT_OK(zxio_close(&storage()->io)); } TEST_F(StreamSocketTest, CreateWithTypeWrapper) { ASSERT_OK(zxio::CreateStreamSocket(storage(), TakeSocket(), TakeClientEnd(), info())); ASSERT_OK(zxio_close(&storage()->io)); } namespace { class RawSocketServer final : public fidl::testing::WireTestBase<fuchsia_posix_socket_raw::Socket> { public: RawSocketServer() = default; void NotImplemented_(const std::string& name, ::fidl::CompleterBase& completer) final { ADD_FAILURE("unexpected message received: %s", name.c_str()); completer.Close(ZX_ERR_NOT_SUPPORTED); } void Clone(CloneRequestView request, CloneCompleter::Sync& completer) final { completer.Close(ZX_ERR_NOT_SUPPORTED); } void CloseDeprecated(CloseDeprecatedRequestView request, CloseDeprecatedCompleter::Sync& completer) final { completer.Reply(ZX_OK); completer.Close(ZX_OK); } void Close(CloseRequestView request, CloseCompleter::Sync& completer) override { completer.ReplySuccess(); completer.Close(ZX_OK); } }; class RawSocketTest : public zxtest::Test { public: void SetUp() final { ASSERT_OK(zx::eventpair::create(0u, &event_client_, &event_server_)); zx::status server_end = fidl::CreateEndpoints(&client_end_); ASSERT_OK(server_end.status_value()); fidl::BindServer(control_loop_.dispatcher(), std::move(*server_end), &server_); control_loop_.StartThread("control"); } void Init() { ASSERT_OK(zxio_raw_socket_init(&storage_, TakeEventClient(), TakeClientEnd())); zxio_ = &storage_.io; } void TearDown() final { if (zxio_) { ASSERT_OK(zxio_close(zxio_)); } control_loop_.Shutdown(); } zx::eventpair TakeEventClient() { return std::move(event_client_); } fidl::ClientEnd<fuchsia_posix_socket_raw::Socket> TakeClientEnd() { return std::move(client_end_); } zxio_storage_t* storage() { return &storage_; } zxio_t* zxio() { return zxio_; } private: zxio_storage_t storage_; zxio_t* zxio_{nullptr}; zx::eventpair event_client_, event_server_; fidl::ClientEnd<fuchsia_posix_socket_raw::Socket> client_end_; RawSocketServer server_; async::Loop control_loop_{&kAsyncLoopConfigNoAttachToCurrentThread}; }; } // namespace TEST_F(RawSocketTest, Basic) { Init(); } TEST_F(RawSocketTest, Release) { Init(); zx_handle_t handle = ZX_HANDLE_INVALID; EXPECT_OK(zxio_release(zxio(), &handle)); EXPECT_NE(handle, ZX_HANDLE_INVALID); EXPECT_OK(zx_handle_close(handle)); } TEST_F(RawSocketTest, Borrow) { Init(); zx_handle_t handle = ZX_HANDLE_INVALID; EXPECT_OK(zxio_borrow(zxio(), &handle)); EXPECT_NE(handle, ZX_HANDLE_INVALID); } TEST_F(RawSocketTest, CreateWithType) { ASSERT_OK(zxio_create_with_type(storage(), ZXIO_OBJECT_TYPE_RAW_SOCKET, TakeEventClient().release(), TakeClientEnd().TakeChannel().release())); ASSERT_OK(zxio_close(&storage()->io)); } TEST_F(RawSocketTest, CreateWithTypeWrapper) { ASSERT_OK(zxio::CreateRawSocket(storage(), TakeEventClient(), TakeClientEnd())); ASSERT_OK(zxio_close(&storage()->io)); } namespace { class PacketSocketServer final : public fidl::testing::WireTestBase<fuchsia_posix_socket_packet::Socket> { public: PacketSocketServer() = default; void NotImplemented_(const std::string& name, ::fidl::CompleterBase& completer) final { ADD_FAILURE("unexpected message received: %s", name.c_str()); completer.Close(ZX_ERR_NOT_SUPPORTED); } void Clone(CloneRequestView request, CloneCompleter::Sync& completer) final { completer.Close(ZX_ERR_NOT_SUPPORTED); } void CloseDeprecated(CloseDeprecatedRequestView request, CloseDeprecatedCompleter::Sync& completer) final { completer.Reply(ZX_OK); completer.Close(ZX_OK); } void Close(CloseRequestView request, CloseCompleter::Sync& completer) override { completer.ReplySuccess(); completer.Close(ZX_OK); } }; class PacketSocketTest : public zxtest::Test { public: void SetUp() final { ASSERT_OK(zx::eventpair::create(0u, &event_client_, &event_server_)); zx::status server_end = fidl::CreateEndpoints(&client_end_); ASSERT_OK(server_end.status_value()); fidl::BindServer(control_loop_.dispatcher(), std::move(*server_end), &server_); control_loop_.StartThread("control"); } void Init() { ASSERT_OK(zxio_packet_socket_init(&storage_, TakeEventClient(), TakeClientEnd())); zxio_ = &storage_.io; } void TearDown() final { if (zxio_) { ASSERT_OK(zxio_close(zxio_)); } control_loop_.Shutdown(); } zx::eventpair TakeEventClient() { return std::move(event_client_); } fidl::ClientEnd<fuchsia_posix_socket_packet::Socket> TakeClientEnd() { return std::move(client_end_); } zxio_storage_t* storage() { return &storage_; } zxio_t* zxio() { return zxio_; } private: zxio_storage_t storage_; zxio_t* zxio_{nullptr}; zx::eventpair event_client_, event_server_; fidl::ClientEnd<fuchsia_posix_socket_packet::Socket> client_end_; PacketSocketServer server_; async::Loop control_loop_{&kAsyncLoopConfigNoAttachToCurrentThread}; }; } // namespace TEST_F(PacketSocketTest, Basic) { Init(); } TEST_F(PacketSocketTest, Release) { Init(); zx_handle_t handle = ZX_HANDLE_INVALID; EXPECT_OK(zxio_release(zxio(), &handle)); EXPECT_NE(handle, ZX_HANDLE_INVALID); EXPECT_OK(zx_handle_close(handle)); } TEST_F(PacketSocketTest, Borrow) { Init(); zx_handle_t handle = ZX_HANDLE_INVALID; EXPECT_OK(zxio_borrow(zxio(), &handle)); EXPECT_NE(handle, ZX_HANDLE_INVALID); } TEST_F(PacketSocketTest, CreateWithType) { ASSERT_OK(zxio_create_with_type(storage(), ZXIO_OBJECT_TYPE_PACKET_SOCKET, TakeEventClient().release(), TakeClientEnd().TakeChannel().release())); ASSERT_OK(zxio_close(&storage()->io)); } TEST_F(PacketSocketTest, CreateWithTypeWrapper) { ASSERT_OK(zxio::CreatePacketSocket(storage(), TakeEventClient(), TakeClientEnd())); ASSERT_OK(zxio_close(&storage()->io)); }
c++
code
12,399
2,586
//-------------------------------------------------------------------------------------------------- // Copyright (c) YugaByte, 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. // // // Treenode definitions for ALTER TYPE statements. //-------------------------------------------------------------------------------------------------- #include "yb/yql/cql/ql/ptree/pt_alter_role.h" #include "yb/util/crypt.h" #include "yb/yql/cql/ql/ptree/sem_context.h" #include "yb/yql/cql/ql/ptree/sem_state.h" #include "yb/yql/cql/ql/ptree/yb_location.h" DECLARE_bool(use_cassandra_authentication); namespace yb { namespace ql { using strings::Substitute; using yb::util::bcrypt_hashpw; using yb::util::kBcryptHashSize; //-------------------------------------------------------------------------------------------------- // Alter Role. PTAlterRole::PTAlterRole(MemoryContext* memctx, YBLocation::SharedPtr loc, const MCSharedPtr<MCString>& name, const PTRoleOptionListNode::SharedPtr& roleOptions) : TreeNode(memctx, loc), name_(name), roleOptions_(roleOptions) { } PTAlterRole::~PTAlterRole() { } CHECKED_STATUS PTAlterRole::Analyze(SemContext* sem_context) { SemState sem_state(sem_context); RETURN_NOT_AUTH_ENABLED(sem_context); RETURN_NOT_OK(sem_context->CheckHasRolePermission(loc(), PermissionType::ALTER_PERMISSION, role_name())); // Save context state, and set "this" as current column in the context. SymbolEntry cached_entry = *sem_context->current_processing_id(); if (roleOptions_!= nullptr) { RETURN_NOT_OK(roleOptions_->Analyze(sem_context)); bool seen_password = false; bool seen_superuser = false; bool seen_login = false; for (auto& roleOption : roleOptions_->node_list()) { switch (roleOption->option_type()) { case PTRoleOptionType::kLogin : { if (seen_login) { return sem_context->Error(roleOption, ErrorCode::INVALID_ROLE_DEFINITION); } PTRoleLogin *loginOpt = static_cast<PTRoleLogin*>(roleOption.get()); login_ = loginOpt->login(); seen_login = true; break; } case PTRoleOptionType::kPassword : { if (seen_password) { return sem_context->Error(roleOption, ErrorCode::INVALID_ROLE_DEFINITION); } PTRolePassword *passwordOpt = static_cast<PTRolePassword*>(roleOption.get()); char hash[kBcryptHashSize]; int ret = bcrypt_hashpw(passwordOpt->password(), hash); if (ret != 0) { return STATUS(IllegalState, Substitute("Could not hash password, reason: $0", ret)); } salted_hash_ = MCMakeShared<MCString>(sem_context->PSemMem(), hash , kBcryptHashSize); seen_password = true; break; } case PTRoleOptionType::kSuperuser: { if (seen_superuser) { return sem_context->Error(roleOption, ErrorCode::INVALID_ROLE_DEFINITION); } PTRoleSuperuser *superuserOpt = static_cast<PTRoleSuperuser*>(roleOption.get()); superuser_ = superuserOpt->superuser(); seen_superuser = true; break; } } } } // Restore the context value as we are done with this table. sem_context->set_current_processing_id(cached_entry); if (VLOG_IS_ON(3)) { PrintSemanticAnalysisResult(sem_context); } return Status::OK(); } void PTAlterRole::PrintSemanticAnalysisResult(SemContext* sem_context) { MCString sem_output("\tAlter Role ", sem_context->PTempMem()); sem_output = sem_output + " role_name " + role_name() + " salted_hash = " + *salted_hash_; sem_output = sem_output + " login = " + (login() ? "true" : "false"); sem_output = sem_output + " superuser = " + (superuser() ? "true" : "false"); VLOG(3) << "SEMANTIC ANALYSIS RESULT (" << *loc_ << "):\n" << sem_output; } } // namespace ql } // namespace yb
c++
code
4,532
946
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2018 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #pragma once #include "vast/fwd.hpp" #include "vast/detail/flat_map.hpp" #include "vast/fbs/index.hpp" #include "vast/fbs/partition.hpp" #include "vast/ids.hpp" #include "vast/partition_synopsis.hpp" #include "vast/qualified_record_field.hpp" #include "vast/synopsis.hpp" #include "vast/system/actors.hpp" #include "vast/time_synopsis.hpp" #include "vast/type.hpp" #include "vast/uuid.hpp" #include <caf/settings.hpp> #include <caf/typed_event_based_actor.hpp> #include <map> #include <string> #include <vector> namespace vast::system { /// The state of the META INDEX actor. struct meta_index_state { public: // -- constructor ------------------------------------------------------------ meta_index_state() = default; // -- concepts --------------------------------------------------------------- constexpr static auto name = "meta-index"; // -- utility functions ------------------------------------------------------ /// Adds new synopses for a partition in bulk. Used when /// re-building the meta index state at startup. void create_from(std::map<uuid, partition_synopsis>&&); /// Add a new partition synopsis. void merge(const uuid& partition, partition_synopsis&&); /// Returns the partition synopsis for a specific partition. /// Note that most callers will prefer to use `lookup()` instead. /// @pre `partition` must be a valid key for this meta index. partition_synopsis& at(const uuid& partition); /// Erase this partition from the meta index. void erase(const uuid& partition); /// Retrieves the list of candidate partition IDs for a given expression. /// @param expr The expression to lookup. /// @returns A vector of UUIDs representing candidate partitions. [[nodiscard]] std::vector<uuid> lookup(const expression& expr) const; [[nodiscard]] std::vector<uuid> lookup_impl(const expression& expr) const; /// @returns A best-effort estimate of the amount of memory used for this meta /// index (in bytes). [[nodiscard]] size_t memusage() const; // -- data members ----------------------------------------------------------- /// A pointer to the parent actor. meta_index_actor::pointer self = {}; /// Maps a partition ID to the synopses for that partition. // We mainly iterate over the whole map and return a sorted set, for which // the `flat_map` proves to be much faster than `std::{unordered_,}set`. // See also ae9dbed. detail::flat_map<uuid, partition_synopsis> synopses = {}; }; /// The META INDEX is the first index actor that queries hit. The result /// represents a list of candidate partition IDs that may contain the desired /// data. The META INDEX may return false positives but never false negatives. /// @param self The actor handle. meta_index_actor::behavior_type meta_index(meta_index_actor::stateful_pointer<meta_index_state> self); } // namespace vast::system
c++
code
3,142
699
/* * event_server.cpp * PHD Guiding * * Created by Andy Galasso. * Copyright (c) 2013 Andy Galasso. * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs 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. * */ #include "phd.h" #include <wx/sstream.h> #include <wx/sckstrm.h> #include <sstream> EventServer EvtServer; BEGIN_EVENT_TABLE(EventServer, wxEvtHandler) EVT_SOCKET(EVENT_SERVER_ID, EventServer::OnEventServerEvent) EVT_SOCKET(EVENT_SERVER_CLIENT_ID, EventServer::OnEventServerClientEvent) END_EVENT_TABLE() enum { MSG_PROTOCOL_VERSION = 1, }; static const wxString literal_null("null"); static const wxString literal_true("true"); static const wxString literal_false("false"); static wxString state_name(EXPOSED_STATE st) { switch (st) { case EXPOSED_STATE_NONE: return "Stopped"; case EXPOSED_STATE_SELECTED: return "Selected"; case EXPOSED_STATE_CALIBRATING: return "Calibrating"; case EXPOSED_STATE_GUIDING_LOCKED: return "Guiding"; case EXPOSED_STATE_GUIDING_LOST: return "LostLock"; case EXPOSED_STATE_PAUSED: return "Paused"; case EXPOSED_STATE_LOOPING: return "Looping"; default: return "Unknown"; } } static wxString json_escape(const wxString& s) { wxString t(s); static const wxString BACKSLASH("\\"); static const wxString BACKSLASHBACKSLASH("\\\\"); static const wxString DQUOT("\""); static const wxString BACKSLASHDQUOT("\\\""); t.Replace(BACKSLASH, BACKSLASHBACKSLASH); t.Replace(DQUOT, BACKSLASHDQUOT); return t; } template<char LDELIM, char RDELIM> struct JSeq { wxString m_s; bool m_first; bool m_closed; JSeq() : m_first(true), m_closed(false) { m_s << LDELIM; } void close() { m_s << RDELIM; m_closed = true; } wxString str() { if (!m_closed) close(); return m_s; } }; typedef JSeq<'[', ']'> JAry; typedef JSeq<'{', '}'> JObj; static JAry& operator<<(JAry& a, const wxString& str) { if (a.m_first) a.m_first = false; else a.m_s << ','; a.m_s << json_escape(str); return a; } static JAry& operator<<(JAry& a, double d) { return a << wxString::Format("%.2f", d); } static JAry& operator<<(JAry& a, int i) { return a << wxString::Format("%d", i); } static wxString json_format(const json_value *j) { if (!j) return literal_null; switch (j->type) { default: case JSON_NULL: return literal_null; case JSON_OBJECT: { wxString ret("{"); bool first = true; json_for_each (jj, j) { if (first) first = false; else ret << ","; ret << '"' << jj->name << "\":" << json_format(jj); } ret << "}"; return ret; } case JSON_ARRAY: { wxString ret("["); bool first = true; json_for_each (jj, j) { if (first) first = false; else ret << ","; ret << json_format(jj); } ret << "]"; return ret; } case JSON_STRING: return '"' + json_escape(j->string_value) + '"'; case JSON_INT: return wxString::Format("%d", j->int_value); case JSON_FLOAT: return wxString::Format("%g", (double) j->float_value); case JSON_BOOL: return j->int_value ? literal_true : literal_false; } } struct NULL_TYPE { } NULL_VALUE; // name-value pair struct NV { wxString n; wxString v; NV(const wxString& n_, const wxString& v_) : n(n_), v('"' + json_escape(v_) + '"') { } NV(const wxString& n_, const char *v_) : n(n_), v('"' + json_escape(v_) + '"') { } NV(const wxString& n_, const wchar_t *v_) : n(n_), v('"' + json_escape(v_) + '"') { } NV(const wxString& n_, int v_) : n(n_), v(wxString::Format("%d", v_)) { } NV(const wxString& n_, double v_) : n(n_), v(wxString::Format("%g", v_)) { } NV(const wxString& n_, double v_, int prec) : n(n_), v(wxString::Format("%.*f", prec, v_)) { } NV(const wxString& n_, bool v_) : n(n_), v(v_ ? literal_true : literal_false) { } template<typename T> NV(const wxString& n_, const std::vector<T>& vec); NV(const wxString& n_, JAry& ary) : n(n_), v(ary.str()) { } NV(const wxString& n_, JObj& obj) : n(n_), v(obj.str()) { } NV(const wxString& n_, const json_value *v_) : n(n_), v(json_format(v_)) { } NV(const wxString& n_, const PHD_Point& p) : n(n_) { JAry ary; ary << p.X << p.Y; v = ary.str(); } NV(const wxString& n_, const wxPoint& p) : n(n_) { JAry ary; ary << p.x << p.y; v = ary.str(); } NV(const wxString& n_, const NULL_TYPE& nul) : n(n_), v(literal_null) { } }; template<typename T> NV::NV(const wxString& n_, const std::vector<T>& vec) : n(n_) { std::ostringstream os; os << '['; for (unsigned int i = 0; i < vec.size(); i++) { if (i != 0) os << ','; os << vec[i]; } os << ']'; v = os.str(); } static JObj& operator<<(JObj& j, const NV& nv) { if (j.m_first) j.m_first = false; else j.m_s << ','; j.m_s << '"' << nv.n << "\":" << nv.v; return j; } static NV NVMount(const Mount *mount) { return NV("Mount", mount->Name()); } static JObj& operator<<(JObj& j, const PHD_Point& pt) { return j << NV("X", pt.X, 3) << NV("Y", pt.Y, 3); } static JAry& operator<<(JAry& a, JObj& j) { return a << j.str(); } struct Ev : public JObj { Ev(const wxString& event) { double const now = ::wxGetUTCTimeMillis().ToDouble() / 1000.0; *this << NV("Event", event) << NV("Timestamp", now, 3) << NV("Host", wxGetHostName()) << NV("Inst", pFrame->GetInstanceNumber()); } }; static Ev ev_message_version() { Ev ev("Version"); ev << NV("PHDVersion", PHDVERSION) << NV("PHDSubver", PHDSUBVER) << NV("MsgVersion", MSG_PROTOCOL_VERSION); return ev; } static Ev ev_set_lock_position(const PHD_Point& xy) { Ev ev("LockPositionSet"); ev << xy; return ev; } static Ev ev_calibration_complete(Mount *mount) { Ev ev("CalibrationComplete"); ev << NVMount(mount); if (mount->IsStepGuider()) { ev << NV("Limit", mount->GetAoMaxPos()); } return ev; } static Ev ev_star_selected(const PHD_Point& pos) { Ev ev("StarSelected"); ev << pos; return ev; } static Ev ev_start_guiding() { return Ev("StartGuiding"); } static Ev ev_paused() { return Ev("Paused"); } static Ev ev_start_calibration(Mount *mount) { Ev ev("StartCalibration"); ev << NVMount(mount); return ev; } static Ev ev_app_state(EXPOSED_STATE st = Guider::GetExposedState()) { Ev ev("AppState"); ev << NV("State", state_name(st)); return ev; } static Ev ev_settling(double distance, double time, double settleTime) { Ev ev("Settling"); ev << NV("Distance", distance, 2) << NV("Time", time, 1) << NV("SettleTime", settleTime, 1); return ev; } static Ev ev_settle_done(const wxString& errorMsg) { Ev ev("SettleDone"); int status = errorMsg.IsEmpty() ? 0 : 1; ev << NV("Status", status); if (status != 0) { ev << NV("Error", errorMsg); } return ev; } static void send_buf(wxSocketClient *client, const wxCharBuffer& buf) { client->Write(buf.data(), buf.length()); client->Write("\r\n", 2); } static void do_notify1(wxSocketClient *client, const JAry& ary) { send_buf(client, JAry(ary).str().ToUTF8()); } static void do_notify1(wxSocketClient *client, const JObj& j) { send_buf(client, JObj(j).str().ToUTF8()); } static void do_notify(const EventServer::CliSockSet& cli, const JObj& jj) { wxCharBuffer buf = JObj(jj).str().ToUTF8(); for (EventServer::CliSockSet::const_iterator it = cli.begin(); it != cli.end(); ++it) { send_buf(*it, buf); } } inline static void simple_notify(const EventServer::CliSockSet& cli, const wxString& ev) { if (!cli.empty()) do_notify(cli, Ev(ev)); } inline static void simple_notify_ev(const EventServer::CliSockSet& cli, const Ev& ev) { if (!cli.empty()) do_notify(cli, ev); } #define SIMPLE_NOTIFY(s) simple_notify(m_eventServerClients, s) #define SIMPLE_NOTIFY_EV(ev) simple_notify_ev(m_eventServerClients, ev) static void send_catchup_events(wxSocketClient *cli) { EXPOSED_STATE st = Guider::GetExposedState(); do_notify1(cli, ev_message_version()); if (pFrame->pGuider) { if (pFrame->pGuider->LockPosition().IsValid()) do_notify1(cli, ev_set_lock_position(pFrame->pGuider->LockPosition())); if (pFrame->pGuider->CurrentPosition().IsValid()) do_notify1(cli, ev_star_selected(pFrame->pGuider->CurrentPosition())); } if (pMount && pMount->IsCalibrated()) do_notify1(cli, ev_calibration_complete(pMount)); if (pSecondaryMount && pSecondaryMount->IsCalibrated()) do_notify1(cli, ev_calibration_complete(pSecondaryMount)); if (st == EXPOSED_STATE_GUIDING_LOCKED) { do_notify1(cli, ev_start_guiding()); } else if (st == EXPOSED_STATE_CALIBRATING) { Mount *mount = pMount; if (pFrame->pGuider->GetState() == STATE_CALIBRATING_SECONDARY) mount = pSecondaryMount; do_notify1(cli, ev_start_calibration(mount)); } else if (st == EXPOSED_STATE_PAUSED) { do_notify1(cli, ev_paused()); } do_notify1(cli, ev_app_state()); } struct ClientReadBuf { enum { SIZE = 1024 }; char buf[SIZE]; char *dest; ClientReadBuf() { reset(); } size_t avail() const { return &buf[SIZE] - dest; } void reset() { dest = &buf[0]; } }; inline static ClientReadBuf *client_rdbuf(wxSocketClient *cli) { return (ClientReadBuf *) cli->GetClientData(); } static void destroy_client(wxSocketClient *cli) { ClientReadBuf *buf = client_rdbuf(cli); cli->Destroy(); delete buf; } static void drain_input(wxSocketInputStream& sis) { while (sis.CanRead()) { char buf[1024]; if (sis.Read(buf, sizeof(buf)).LastRead() == 0) break; } } static bool find_eol(char *p, size_t len) { const char *end = p + len; for (; p < end; p++) { if (*p == '\r' || *p == '\n') { *p = 0; return true; } } return false; } enum { JSONRPC_PARSE_ERROR = -32700, JSONRPC_INVALID_REQUEST = -32600, JSONRPC_METHOD_NOT_FOUND = -32601, JSONRPC_INVALID_PARAMS = -32602, JSONRPC_INTERNAL_ERROR = -32603, }; static NV jrpc_error(int code, const wxString& msg) { JObj err; err << NV("code", code) << NV("message", msg); return NV("error", err); } template<typename T> static NV jrpc_result(const T& t) { return NV("result", t); } template<typename T> static NV jrpc_result(T& t) { return NV("result", t); } static NV jrpc_id(const json_value *id) { return NV("id", id); } struct JRpcResponse : public JObj { JRpcResponse() { *this << NV("jsonrpc", "2.0"); } }; static wxString parser_error(const JsonParser& parser) { return wxString::Format("invalid JSON request: %s on line %d at \"%.12s...\"", parser.ErrorDesc(), parser.ErrorLine(), parser.ErrorPos()); } static void parse_request(const json_value *req, const json_value **pmethod, const json_value **pparams, const json_value **pid) { *pmethod = *pparams = *pid = 0; if (req) { json_for_each (t, req) { if (t->name) { if (t->type == JSON_STRING && strcmp(t->name, "method") == 0) *pmethod = t; else if (strcmp(t->name, "params") == 0) *pparams = t; else if (strcmp(t->name, "id") == 0) *pid = t; } } } } static const json_value *at(const json_value *ary, unsigned int idx) { unsigned int i = 0; json_for_each (j, ary) { if (i == idx) return j; ++i; } return 0; } static void deselect_star(JObj& response, const json_value *params) { pFrame->pGuider->Reset(true); response << jrpc_result(0); } static void get_exposure(JObj& response, const json_value *params) { response << jrpc_result(pFrame->RequestedExposureDuration()); } static void get_exposure_durations(JObj& response, const json_value *params) { std::vector<int> exposure_durations; pFrame->GetExposureDurations(&exposure_durations); response << jrpc_result(exposure_durations); } static void get_profiles(JObj& response, const json_value *params) { JAry ary; wxArrayString names = pConfig->ProfileNames(); for (unsigned int i = 0; i < names.size(); i++) { wxString name = names[i]; int id = pConfig->GetProfileId(name); if (id) { JObj t; t << NV("id", id) << NV("name", name); if (id == pConfig->GetCurrentProfileId()) t << NV("selected", true); ary << t; } } response << jrpc_result(ary); } static void set_exposure(JObj& response, const json_value *params) { const json_value *exp; if (!params || (exp = at(params, 0)) == 0 || exp->type != JSON_INT) { response << jrpc_error(JSONRPC_INVALID_PARAMS, "expected exposure param"); return; } bool ok = pFrame->SetExposureDuration(exp->int_value); if (ok) { response << jrpc_result(1); } else { response << jrpc_error(1, "could not set exposure duration"); } } static void get_profile(JObj& response, const json_value *params) { int id = pConfig->GetCurrentProfileId(); wxString name = pConfig->GetCurrentProfile(); JObj t; t << NV("id", id) << NV("name", name); response << jrpc_result(t); } static bool all_equipment_connected() { return pCamera && pCamera->Connected && (!pMount || pMount->IsConnected()) && (!pSecondaryMount || pSecondaryMount->IsConnected()); } static void set_profile(JObj& response, const json_value *params) { const json_value *id; if (!params || (id = at(params, 0)) == 0 || id->type != JSON_INT) { response << jrpc_error(JSONRPC_INVALID_PARAMS, "expected profile id param"); return; } if (!pFrame || !pFrame->pGearDialog) // paranoia { response << jrpc_error(1, "internal error"); return; } wxString errMsg; bool error = pFrame->pGearDialog->SetProfile(id->int_value, &errMsg); if (error) { response << jrpc_error(1, errMsg); } else { response << jrpc_result(0); } } static void get_connected(JObj& response, const json_value *params) { response << jrpc_result(all_equipment_connected()); } static void set_connected(JObj& response, const json_value *params) { const json_value *val; if (!params || (val = at(params, 0)) == 0 || val->type != JSON_BOOL) { response << jrpc_error(JSONRPC_INVALID_PARAMS, "expected connected boolean param"); return; } if (!pFrame || !pFrame->pGearDialog) // paranoia { response << jrpc_error(1, "internal error"); return; } wxString errMsg; bool error = val->int_value ? pFrame->pGearDialog->ConnectAll(&errMsg) : pFrame->pGearDialog->DisconnectAll(&errMsg); if (error) { response << jrpc_error(1, errMsg); } else { response << jrpc_result(0); } } static void get_calibrated(JObj& response, const json_value *params) { bool calibrated = pMount && pMount->IsCalibrated() && (!pSecondaryMount || pSecondaryMount->IsCalibrated()); response << jrpc_result(calibrated); } static bool float_param(const json_value *v, double *p) { if (v->type == JSON_INT) { *p = (double) v->int_value; return true; } else if (v->type == JSON_FLOAT) { *p = v->float_value; return true; } return false; } static bool float_param(const char *name, const json_value *v, double *p) { if (strcmp(name, v->name) != 0) return false; return float_param(v, p); } static void get_paused(JObj& response, const json_value *params) { response << jrpc_result(pFrame->pGuider->IsPaused()); } static void set_paused(JObj& response, const json_value *params) { const json_value *p; bool val; if (!params || (p = at(params, 0)) == 0 || p->type != JSON_BOOL) { response << jrpc_error(JSONRPC_INVALID_PARAMS, "expected bool param at index 0"); return; } val = p->int_value ? true : false; PauseType pause = PAUSE_NONE; if (val) { pause = PAUSE_GUIDING; p = at(params, 1); if (p) { if (p->type == JSON_STRING) { if (strcmp(p->string_value, "full") == 0) pause = PAUSE_FULL; } else { response << jrpc_error(JSONRPC_INVALID_PARAMS, "expected string param at index 1"); return; } } } pFrame->SetPaused(pause); response << jrpc_result(0); } static void loop(JObj& response, const json_value *params) { bool error = pFrame->StartLooping(); if (error) response << jrpc_error(1, "could not start looping"); else response << jrpc_result(0); } static void stop_capture(JObj& response, const json_value *params) { pFrame->StopCapturing(); response << jrpc_result(0); } static void find_star(JObj& r
c++
code
20,000
4,705
#include <Kernel/FileSystem/FileDescription.h> #include <Kernel/Process.h> #include <Kernel/Scheduler.h> #include <Kernel/Thread.h> #include <Kernel/VM/MemoryManager.h> #include <LibC/signal_numbers.h> //#define SIGNAL_DEBUG HashTable<Thread*>& thread_table() { ASSERT_INTERRUPTS_DISABLED(); static HashTable<Thread*>* table; if (!table) table = new HashTable<Thread*>; return *table; } InlineLinkedList<Thread>* g_runnable_threads; InlineLinkedList<Thread>* g_nonrunnable_threads; static const dword default_kernel_stack_size = 65536; static const dword default_userspace_stack_size = 65536; Thread::Thread(Process& process) : m_process(process) , m_tid(process.m_next_tid++) { dbgprintf("Thread{%p}: New thread TID=%u in %s(%u)\n", this, m_tid, process.name().characters(), process.pid()); set_default_signal_dispositions(); m_fpu_state = (FPUState*)kmalloc_aligned(sizeof(FPUState), 16); memset(&m_tss, 0, sizeof(m_tss)); // Only IF is set when a process boots. m_tss.eflags = 0x0202; word cs, ds, ss; if (m_process.is_ring0()) { cs = 0x08; ds = 0x10; ss = 0x10; } else { cs = 0x1b; ds = 0x23; ss = 0x23; } m_tss.ds = ds; m_tss.es = ds; m_tss.fs = ds; m_tss.gs = ds; m_tss.ss = ss; m_tss.cs = cs; m_tss.cr3 = m_process.page_directory().cr3(); if (m_process.is_ring0()) { // FIXME: This memory is leaked. // But uh, there's also no kernel process termination, so I guess it's not technically leaked... m_kernel_stack_base = (dword)kmalloc_eternal(default_kernel_stack_size); m_tss.esp = (m_kernel_stack_base + default_kernel_stack_size) & 0xfffffff8u; } else { // Ring3 processes need a separate stack for Ring0. m_kernel_stack_region = MM.allocate_kernel_region(default_kernel_stack_size, String::format("Kernel Stack (Thread %d)", m_tid)); m_kernel_stack_base = m_kernel_stack_region->vaddr().get(); m_tss.ss0 = 0x10; m_tss.esp0 = m_kernel_stack_region->vaddr().offset(default_kernel_stack_size).get() & 0xfffffff8u; } // HACK: Ring2 SS in the TSS is the current PID. m_tss.ss2 = m_process.pid(); m_far_ptr.offset = 0x98765432; if (m_process.pid() != 0) { InterruptDisabler disabler; thread_table().set(this); set_thread_list(g_nonrunnable_threads); } } Thread::~Thread() { dbgprintf("~Thread{%p}\n", this); kfree_aligned(m_fpu_state); { InterruptDisabler disabler; if (m_thread_list) m_thread_list->remove(this); thread_table().remove(this); } if (g_last_fpu_thread == this) g_last_fpu_thread = nullptr; if (selector()) gdt_free_entry(selector()); } void Thread::unblock() { m_blocked_descriptor = nullptr; if (current == this) { set_state(Thread::Running); return; } ASSERT(m_state != Thread::Runnable && m_state != Thread::Running); set_state(Thread::Runnable); } void Thread::snooze_until(Alarm& alarm) { m_snoozing_alarm = &alarm; block(Thread::BlockedSnoozing); Scheduler::yield(); } void Thread::block(Thread::State new_state) { bool did_unlock = process().big_lock().unlock_if_locked(); if (state() != Thread::Running) { kprintf("Thread::block: %s(%u) block(%u/%s) with state=%u/%s\n", process().name().characters(), process().pid(), new_state, to_string(new_state), state(), to_string(state())); } ASSERT(state() == Thread::Running); m_was_interrupted_while_blocked = false; set_state(new_state); Scheduler::yield(); if (did_unlock) process().big_lock().lock(); } void Thread::block(Thread::State new_state, FileDescription& descriptor) { m_blocked_descriptor = &descriptor; block(new_state); } void Thread::sleep(dword ticks) { ASSERT(state() == Thread::Running); current->set_wakeup_time(g_uptime + ticks); current->block(Thread::BlockedSleep); } const char* to_string(Thread::State state) { switch (state) { case Thread::Invalid: return "Invalid"; case Thread::Runnable: return "Runnable"; case Thread::Running: return "Running"; case Thread::Dying: return "Dying"; case Thread::Dead: return "Dead"; case Thread::Stopped: return "Stopped"; case Thread::Skip1SchedulerPass: return "Skip1"; case Thread::Skip0SchedulerPasses: return "Skip0"; case Thread::BlockedSleep: return "Sleep"; case Thread::BlockedWait: return "Wait"; case Thread::BlockedRead: return "Read"; case Thread::BlockedWrite: return "Write"; case Thread::BlockedSignal: return "Signal"; case Thread::BlockedSelect: return "Select"; case Thread::BlockedLurking: return "Lurking"; case Thread::BlockedConnect: return "Connect"; case Thread::BlockedReceive: return "Receive"; case Thread::BlockedSnoozing: return "Snoozing"; } kprintf("to_string(Thread::State): Invalid state: %u\n", state); ASSERT_NOT_REACHED(); return nullptr; } void Thread::finalize() { dbgprintf("Finalizing Thread %u in %s(%u)\n", tid(), m_process.name().characters(), pid()); set_state(Thread::State::Dead); m_blocked_descriptor = nullptr; if (this == &m_process.main_thread()) m_process.finalize(); } void Thread::finalize_dying_threads() { Vector<Thread*, 32> dying_threads; { InterruptDisabler disabler; for_each_in_state(Thread::State::Dying, [&](Thread& thread) { dying_threads.append(&thread); }); } for (auto* thread : dying_threads) thread->finalize(); } bool Thread::tick() { ++m_ticks; if (tss().cs & 3) ++m_process.m_ticks_in_user; else ++m_process.m_ticks_in_kernel; return --m_ticks_left; } void Thread::send_signal(byte signal, Process* sender) { ASSERT(signal < 32); if (sender) dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, process().name().characters(), pid()); else dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, process().name().characters(), pid()); InterruptDisabler disabler; m_pending_signals |= 1 << signal; } bool Thread::has_unmasked_pending_signals() const { return m_pending_signals & ~m_signal_mask; } ShouldUnblockThread Thread::dispatch_one_pending_signal() { ASSERT_INTERRUPTS_DISABLED(); dword signal_candidates = m_pending_signals & ~m_signal_mask; ASSERT(signal_candidates); byte signal = 0; for (; signal < 32; ++signal) { if (signal_candidates & (1 << signal)) { break; } } return dispatch_signal(signal); } enum class DefaultSignalAction { Terminate, Ignore, DumpCore, Stop, Continue, }; DefaultSignalAction default_signal_action(byte signal) { ASSERT(signal && signal < NSIG); switch (signal) { case SIGHUP: case SIGINT: case SIGKILL: case SIGPIPE: case SIGALRM: case SIGUSR1: case SIGUSR2: case SIGVTALRM: case SIGSTKFLT: case SIGIO: case SIGPROF: case SIGTERM: case SIGPWR: return DefaultSignalAction::Terminate; case SIGCHLD: case SIGURG: case SIGWINCH: return DefaultSignalAction::Ignore; case SIGQUIT: case SIGILL: case SIGTRAP: case SIGABRT: case SIGBUS: case SIGFPE: case SIGSEGV: case SIGXCPU: case SIGXFSZ: case SIGSYS: return DefaultSignalAction::DumpCore; case SIGCONT: return DefaultSignalAction::Continue; case SIGSTOP: case SIGTSTP: case SIGTTIN: case SIGTTOU: return DefaultSignalAction::Stop; } ASSERT_NOT_REACHED(); } ShouldUnblockThread Thread::dispatch_signal(byte signal) { ASSERT_INTERRUPTS_DISABLED(); ASSERT(signal < 32); #ifdef SIGNAL_DEBUG kprintf("dispatch_signal %s(%u) <- %u\n", process().name().characters(), pid(), signal); #endif auto& action = m_signal_action_data[signal]; // FIXME: Implement SA_SIGINFO signal handlers. ASSERT(!(action.flags & SA_SIGINFO)); // Mark this signal as handled. m_pending_signals &= ~(1 << signal); if (signal == SIGSTOP) { set_state(Stopped); return ShouldUnblockThread::No; } if (signal == SIGCONT && state() == Stopped) set_state(Runnable); auto handler_vaddr = action.handler_or_sigaction; if (handler_vaddr.is_null()) { switch (default_signal_action(signal)) { case DefaultSignalAction::Stop: set_state(Stopped); return ShouldUnblockThread::No; case DefaultSignalAction::DumpCore: case DefaultSignalAction::Terminate: m_process.terminate_due_to_signal(signal); return ShouldUnblockThread::No; case DefaultSignalAction::Ignore: if (state() == BlockedSignal) set_state(Runnable); return ShouldUnblockThread::No; case DefaultSignalAction::Continue: return ShouldUnblockThread::Yes; } ASSERT_NOT_REACHED(); } if (handler_vaddr.as_ptr() == SIG_IGN) { #ifdef SIGNAL_DEBUG kprintf("%s(%u) ignored signal %u\n", process().name().characters(), pid(), signal); #endif return ShouldUnblockThread::Yes; } dword old_signal_mask = m_signal_mask; dword new_signal_mask = action.mask; if (action.flags & SA_NODEFER) new_signal_mask &= ~(1 << signal); else new_signal_mask |= 1 << signal; m_signal_mask |= new_signal_mask; Scheduler::prepare_to_modify_tss(*this); word ret_cs = m_tss.cs; dword ret_eip = m_tss.eip; dword ret_eflags = m_tss.eflags; bool interrupting_in_kernel = (ret_cs & 3) == 0; ProcessPagingScope paging_scope(m_process); m_process.create_signal_trampolines_if_needed(); if (interrupting_in_kernel) { #ifdef SIGNAL_DEBUG kprintf("dispatch_signal to %s(%u) in state=%s with return to %w:%x\n", process().name().characters(), pid(), to_string(state()), ret_cs, ret_eip); #endif ASSERT(is_blocked()); m_tss_to_resume_kernel = make<TSS32>(m_tss); #ifdef SIGNAL_DEBUG kprintf("resume tss pc: %w:%x stack: %w:%x flags: %x cr3: %x\n", m_tss_to_resume_kernel->cs, m_tss_to_resume_kernel->eip, m_tss_to_resume_kernel->ss, m_tss_to_resume_kernel->esp, m_tss_to_resume_kernel->eflags, m_tss_to_resume_kernel->cr3); #endif if (!m_signal_stack_user_region) { m_signal_stack_user_region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, String::format("User Signal Stack (Thread %d)", m_tid)); ASSERT(m_signal_stack_user_region); } if (!m_kernel_stack_for_signal_handler_region) m_kernel_stack_for_signal_handler_region = MM.allocate_kernel_region(default_kernel_stack_size, String::format("Kernel Signal Stack (Thread %d)", m_tid)); m_tss.ss = 0x23; m_tss.esp = m_signal_stack_user_region->vaddr().offset(default_userspace_stack_size).get(); m_tss.ss0 = 0x10; m_tss.esp0 = m_kernel_stack_for_signal_handler_region->vaddr().offset(default_kernel_stack_size).get(); push_value_on_stack(0); } else { push_value_on_stack(ret_eip); push_value_on_stack(ret_eflags); // PUSHA dword old_esp = m_tss.esp; push_value_on_stack(m_tss.eax); push_value_on_stack(m_tss.ecx); push_value_on_stack(m_tss.edx); push_value_on_stack(m_tss.ebx); push_value_on_stack(old_esp); push_value_on_stack(m_tss.ebp); push_value_on_stack(m_tss.esi); push_value_on_stack(m_tss.edi); // Align the stack. m_tss.esp -= 12; } // PUSH old_signal_mask push_value_on_stack(old_signal_mask); m_tss.cs = 0x1b; m_tss.ds = 0x23; m_tss.es = 0x23; m_tss.fs = 0x23; m_tss.gs = 0x23; m_tss.eip = handler_vaddr.get(); // FIXME: Should we worry about the stack being 16 byte aligned when entering a signal handler? push_value_on_stack(signal); if (interrupting_in_kernel) push_value_on_stack(m_process.m_return_to_ring0_from_signal_trampoline.get()); else push_value_on_stack(m_process.m_return_to_ring3_from_signal_trampoline.get()); ASSERT((m_tss.esp % 16) == 0); // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal. set_state(Skip1SchedulerPass); #ifdef SIGNAL_DEBUG kprintf("signal: Okay, %s(%u) {%s} has been primed with signal handler %w:%x\n", process().name().characters(), pid(), to_string(state()), m_tss.cs, m_tss.eip); #endif return ShouldUnblockThread::Yes; } void Thread::set_default_signal_dispositions() { // FIXME: Set up all the right default actions. See signal(7). memset(&m_signal_action_data, 0, sizeof(m_signal_action_data)); m_signal_action_data[SIGCHLD].handler_or_sigaction = VirtualAddress((dword)SIG_IGN); m_signal_action_data[SIGWINCH].handler_or_sigaction = VirtualAddress((dword)SIG_IGN); } void Thread::push_value_on_stack(dword value) { m_tss.esp -= 4; dword* stack_ptr = (dword*)m_tss.esp; *stack_ptr = value; } void Thread::make_userspace_stack_for_main_thread(Vector<String> arguments, Vector<String> environment) { auto* region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, "Stack (Main thread)"); ASSERT(region); m_tss.esp = region->vaddr().offset(default_userspace_stack_size).get(); char* stack_base = (char*)region->vaddr().get(); int argc = arguments.size(); char** argv = (char**)stack_base; char** env = argv + arguments.size() + 1; char* bufptr = stack_base + (sizeof(char*) * (arguments.size() + 1)) + (sizeof(char*) * (environment.size() + 1)); size_t total_blob_size = 0; for (auto& a : arguments) total_blob_size += a.length() + 1; for (auto& e : environment) total_blob_size += e.length() + 1; size_t total_meta_size = sizeof(char*) * (arguments.size() + 1) + sizeof(char*) * (environment.size() + 1); // FIXME: It would be better if this didn't make us panic. ASSERT((total_blob_size + total_meta_size) < default_userspace_stack_size); for (int i = 0; i < arguments.size(); ++i) { argv[i] = bufptr; memcpy(bufptr, arguments[i].characters(), arguments[i].length()); bufptr += arguments[i].length(); *(bufptr++) = '\0'; } argv[arguments.size()] = nullptr; for (int i = 0; i < environment.size(); ++i) { env[i] = bufptr; memcpy(bufptr, environment[i].characters(), environment[i].length()); bufptr += environment[i].length(); *(bufptr++) = '\0'; } env[environment.size()] = nullptr; // NOTE: The stack needs to be 16-byte aligned. push_value_on_stack((dword)env); push_value_on_stack((dword)argv); push_value_on_stack((dword)argc); push_value_on_stack(0); } void Thread::make_userspace_stack_for_secondary_thread(void* argument) { auto* region = m_process.allocate_region(VirtualAddress(), default_userspace_stack_size, String::format("Stack (Thread %d)", tid())); ASSERT(region); m_tss.esp = region->vaddr().offset(default_userspace_stack_size).get(); // NOTE: The stack needs to be 16-byte aligned. push_value_on_stack((dword)argument); push_value_on_stack(0); } Thread* Thread::clone(Process& process) { auto* clone = new Thread(process); memcpy(clone->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data)); clone->m_signal_mask = m_signal_mask; clone->m_fpu_state = (FPUState*)kmalloc_aligned(sizeof(FPUState), 16); memcpy(clone->m_fpu_state, m_fpu_state, sizeof(FPUState)); clone->m_has_used_fpu = m_has_used_fpu; return clone; } KResult Thread::wait_for_connect(FileDescription& descriptor) { ASSERT(descriptor.is_socket()); auto& socket = *descriptor.socket(); if (socket.is_connected()) return KSuccess; block(Thread::State::BlockedConnect, descriptor); Scheduler::yield(); if (!socket.is_connected()) return KResult(-ECONNREFUSED); return KSuccess; } void Thread::initialize() { g_runnable_threads = new InlineLinkedList<Thread>; g_nonrunnable_threads = new InlineLinkedList<Thread>; Scheduler::initialize(); } Vector<Thread*> Thread::all_threads() { Vector<Thread*> threads; InterruptDisabler disabler; threads.ensure_capacity(thread_table().size()); for (auto* thread : thread_table()) threads.unchecked_append(thread); return threads; } bool Thread::is_thread(void* ptr) { ASSERT_INTERRUPTS_DISABLED(); return thread_table().contains((Thread*)ptr); } void Thread::set_thread_list(InlineLinkedList<Thread>* thread_list) { ASSERT(pid() != 0); if (m_thread_list == thread_list) return; if (m_thread_list) m_thread_list->remove(this); if (thread_list) thread_list->append(this); m_thread_list = thread_list; } void Thread::set_state(State new_state) { m_state = new_state; if (m_process.pid() != 0) set_thread_list(thread_list_for_state(new_state)); }
c++
code
17,474
3,776
#include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <QClipboard> #include <string> #include <vector> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a Mpaycoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a Mpaycoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)")); ui->signatureIn_VM->setPlaceholderText(tr("Enter Mpaycoin signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(const QString &address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(const QString &address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CPubKey pubkey; if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(pubkey.GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
c++
code
8,790
2,164
/* * 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 "Method.h" #include "PacketParser.h" #include "ExceptionManager.h" using namespace jdwp; using namespace Method; int Method::LineTableHandler::Execute(JNIEnv *jni) { jvmtiError err; jclass refType = m_cmdParser->command.ReadReferenceTypeID(jni); jmethodID methodID = m_cmdParser->command.ReadMethodID(jni); #ifndef NDEBUG if (JDWP_TRACE_ENABLED(LOG_KIND_DATA)) { jvmtiError err; char* classSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetClassSignature(refType, &classSignature, 0)); JvmtiAutoFree afs(classSignature); char* methodName = 0; char* methodSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetMethodName(methodID, &methodName, &methodSignature, 0)); JvmtiAutoFree afmn(methodName); JvmtiAutoFree afms(methodSignature); JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "LineTable: received: methodName=%s, methodSignature=%s, classSignature=%s", methodName, JDWP_CHECK_NULL(methodSignature), JDWP_CHECK_NULL(classSignature))); } #endif jboolean isNative; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->IsMethodNative(methodID, &isNative)); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } if (isNative == JNI_TRUE) { JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "LineTable: native method")); AgentException e(JDWP_ERROR_NATIVE_METHOD); JDWP_SET_EXCEPTION(e); return JDWP_ERROR_NATIVE_METHOD; } jlocation start_location; jlocation end_location; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetMethodLocation(methodID, &start_location, &end_location)); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } jint entry_count = 0; jvmtiLineNumberEntry* table = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLineNumberTable(methodID, &entry_count, &table)); JvmtiAutoFree afv(table); if (err == JVMTI_ERROR_MUST_POSSESS_CAPABILITY || err == JVMTI_ERROR_ABSENT_INFORMATION) { JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "LineTable: send: tableStart=%lld, tableEnd=%lld, entry_count=0 (no info)", start_location, end_location)); m_cmdParser->reply.WriteLong(start_location); m_cmdParser->reply.WriteLong(end_location); m_cmdParser->reply.WriteInt(0); } else if (err == JVMTI_ERROR_NONE) { JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "LineTable: send: tableStart=%lld, tableEnd=%lld, entry_count=%d", start_location, end_location, entry_count)); m_cmdParser->reply.WriteLong(start_location); m_cmdParser->reply.WriteLong(end_location); m_cmdParser->reply.WriteInt(entry_count); for (int i = 0; i < entry_count; i++) { JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "LineTable: send: entry#=%d, lineCodeIndex=%lld, lineCodeNumber=%d", i, table[i].start_location, table[i].line_number)); m_cmdParser->reply.WriteLong(table[i].start_location); m_cmdParser->reply.WriteInt(table[i].line_number); } } else { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } return JDWP_ERROR_NONE; } int Method::VariableTableHandler::Execute(JNIEnv *jni) { jclass refType = m_cmdParser->command.ReadReferenceTypeID(jni); jmethodID methodID = m_cmdParser->command.ReadMethodID(jni); #ifndef NDEBUG if (JDWP_TRACE_ENABLED(LOG_KIND_DATA)) { jvmtiError err; char* classSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetClassSignature(refType, &classSignature, 0)); JvmtiAutoFree afcs(classSignature); char* methodName = 0; char* methodSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetMethodName(methodID, &methodName, &methodSignature, 0)); JvmtiAutoFree afmn(methodName); JvmtiAutoFree afms(methodSignature); JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTable: received: methodName=%s, methodSignature=%s, classSignature=%s", methodName, JDWP_CHECK_NULL(methodSignature), JDWP_CHECK_NULL(classSignature))); } #endif jboolean isNative; jvmtiError err; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->IsMethodNative(methodID, &isNative)); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } if (isNative == JNI_TRUE) { JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTable: native method")); AgentException e(JDWP_ERROR_NATIVE_METHOD); JDWP_SET_EXCEPTION(e); return JDWP_ERROR_NATIVE_METHOD; } jint size; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetArgumentsSize(methodID, &size)); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } m_cmdParser->reply.WriteInt(size); jint entry_count; jvmtiLocalVariableEntry* table = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLocalVariableTable(methodID, &entry_count, &table)); JvmtiAutoFree afv(table); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } #ifndef NDEBUG if (JDWP_TRACE_ENABLED(LOG_KIND_DATA)) { jlocation start_location; jlocation end_location; GetJvmtiEnv()->GetMethodLocation(methodID, &start_location, &end_location); JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTable: methodStart=%lld, methodEnd=%lld, entry_count=%d", start_location, end_location, entry_count)); } #endif JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTable: send: argSize=%d, entry_count=%d", size, entry_count)); m_cmdParser->reply.WriteInt(entry_count); for (int i = 0; i < entry_count; i++) { JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTable: send: entry#=%d, codeIndex=%lld, name=%s, signature=%s, length=%d, slot=%d", i, table[i].start_location, table[i].name, table[i].signature, table[i].length, table[i].slot)); m_cmdParser->reply.WriteLong(table[i].start_location); m_cmdParser->reply.WriteString(table[i].name); m_cmdParser->reply.WriteString(table[i].signature); m_cmdParser->reply.WriteInt(table[i].length); m_cmdParser->reply.WriteInt(table[i].slot); JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->Deallocate( reinterpret_cast<unsigned char*>(table[i].name))); JDWP_ASSERT(err==JVMTI_ERROR_NONE); JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->Deallocate( reinterpret_cast<unsigned char*>(table[i].signature))); JDWP_ASSERT(err==JVMTI_ERROR_NONE); JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->Deallocate( reinterpret_cast<unsigned char*>(table[i].generic_signature))); JDWP_ASSERT(err==JVMTI_ERROR_NONE); } return JDWP_ERROR_NONE; } int Method::BytecodesHandler::Execute(JNIEnv *jni) { jclass refType = m_cmdParser->command.ReadReferenceTypeID(jni); jmethodID methodID = m_cmdParser->command.ReadMethodID(jni); #ifndef NDEBUG if (JDWP_TRACE_ENABLED(LOG_KIND_DATA)) { jvmtiError err; char* classSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetClassSignature(refType, &classSignature, 0)); JvmtiAutoFree afcs(classSignature); char* methodName = 0; char* methodSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetMethodName(methodID, &methodName, &methodSignature, 0)); JvmtiAutoFree afmn(methodName); JvmtiAutoFree afms(methodSignature); JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "Bytecodes: received: methodName=%s, methodSignature=%s, classSignature=%s", methodName, JDWP_CHECK_NULL(methodSignature), JDWP_CHECK_NULL(classSignature))); } #endif jint bytecode_count; unsigned char* bytecodes = 0; jvmtiError err; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetBytecodes(methodID, &bytecode_count, &bytecodes)); JvmtiAutoFree afv(bytecodes); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "Bytecodes: send: bytecode_count=%d", bytecode_count)); m_cmdParser->reply.WriteByteArray(reinterpret_cast<jbyte*>(bytecodes), bytecode_count); return JDWP_ERROR_NONE; } int Method::IsObsoleteHandler::Execute(JNIEnv *jni) { jclass refType = m_cmdParser->command.ReadReferenceTypeID(jni); jmethodID methodID = m_cmdParser->command.ReadMethodID(jni); // when the methodID is 0, it means the method is obsolete. if (0 == methodID) { JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "IsObsolete: send: is_obsolete=TRUE")); m_cmdParser->reply.WriteBoolean(JNI_TRUE); return JDWP_ERROR_NONE; } #ifndef NDEBUG if (JDWP_TRACE_ENABLED(LOG_KIND_DATA)) { jvmtiError err; char* classSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetClassSignature(refType, &classSignature, 0)); JvmtiAutoFree afcs(classSignature); char* methodName = 0; char* methodSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetMethodName(methodID, &methodName, &methodSignature, 0)); JvmtiAutoFree afmn(methodName); JvmtiAutoFree afms(methodSignature); JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "IsObsolete: received: methodName=%s, methodSignature=%s, classSignature=%s", methodName, JDWP_CHECK_NULL(methodSignature), JDWP_CHECK_NULL(classSignature))); } #endif jboolean is_obsolete = JNI_FALSE; jvmtiError err; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->IsMethodObsolete(methodID, &is_obsolete)); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "IsObsolete: send: is_obsolete=%s", (is_obsolete ? "TRUE" : "FALSE"))); m_cmdParser->reply.WriteBoolean(is_obsolete); return JDWP_ERROR_NONE; } int Method::VariableTableWithGenericHandler::Execute(JNIEnv *jni) { jclass refType = m_cmdParser->command.ReadReferenceTypeID(jni); jmethodID methodID = m_cmdParser->command.ReadMethodID(jni); #ifndef NDEBUG if (JDWP_TRACE_ENABLED(LOG_KIND_DATA)) { jvmtiError err; char* classSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetClassSignature(refType, &classSignature, 0)); JvmtiAutoFree afcs(classSignature); char* methodName = 0; char* methodSignature = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetMethodName(methodID, &methodName, &methodSignature, 0)); JvmtiAutoFree afmn(methodName); JvmtiAutoFree afms(methodSignature); JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTableWithGeneric: received: methodName=%s, methodSignature=%s, classSignature=%s", methodName, JDWP_CHECK_NULL(methodSignature), JDWP_CHECK_NULL(classSignature))); } #endif jint size; jvmtiError err; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetArgumentsSize(methodID, &size)); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } m_cmdParser->reply.WriteInt(size); jint entry_count; jvmtiLocalVariableEntry* table = 0; JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->GetLocalVariableTable(methodID, &entry_count, &table)); JvmtiAutoFree afv(table); if (err != JVMTI_ERROR_NONE) { AgentException e(err); JDWP_SET_EXCEPTION(e); return err; } #ifndef NDEBUG if (JDWP_TRACE_ENABLED(LOG_KIND_DATA)) { jlocation start_location; jlocation end_location; GetJvmtiEnv()->GetMethodLocation(methodID, &start_location, &end_location); JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTableWithGeneric: methodStart=%lld, methodEnd=%lld, entry_count=%d", start_location, end_location, entry_count)); } #endif JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTableWithGeneric: send: argSize=%d, entry_count=%d", size, entry_count)); m_cmdParser->reply.WriteInt(entry_count); for (int i = 0; i < entry_count; i++) { JDWP_TRACE(LOG_RELEASE, (LOG_DATA_FL, "VariableTableWithGeneric: send: entry#=%d, codeIndex=%lld, name=%s, signature=%s, length=%d, slot=%d", i, table[i].start_location, table[i].name, table[i].signature, table[i].length, table[i].slot)); m_cmdParser->reply.WriteLong(table[i].start_location); m_cmdParser->reply.WriteString(table[i].name); m_cmdParser->reply.WriteString(table[i].signature); m_cmdParser->reply.WriteString(table[i].generic_signature); m_cmdParser->reply.WriteInt(table[i].length); m_cmdParser->reply.WriteInt(table[i].slot); JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->Deallocate( reinterpret_cast<unsigned char*>(table[i].name))); JDWP_ASSERT(err==JVMTI_ERROR_NONE); JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->Deallocate( reinterpret_cast<unsigned char*>(table[i].signature))); JDWP_ASSERT(err==JVMTI_ERROR_NONE); JVMTI_TRACE(LOG_DEBUG, err, GetJvmtiEnv()->Deallocate( reinterpret_cast<unsigned char*>(table[i].generic_signature))); JDWP_ASSERT(err==JVMTI_ERROR_NONE); } return JDWP_ERROR_NONE; }
c++
code
14,564
2,865
// Copyright (c) Terence Parr, Sam Harwell. Licensed under the BSD license. See LICENSE in the project root for license information. #include "stdafx.h" #include <cassert> #include <algorithm> #include <iterator> #include <stdexcept> #include <unordered_set> #include <unordered_map> #include <antlr/v4/runtime/atn/semantic_context.hpp> #include <antlr/v4/runtime/misc/murmur_hash.hpp> #include <antlr/v4/runtime/misc/unordered_ptr_set.hpp> #if defined(_MSC_VER) && (_MSC_VER == 1800) #undef assert #define assert(_Expression) (void)( (!!(_Expression)) || (_wassert(_CRT_WIDE(#_Expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0) ) #endif namespace antlr4 { namespace atn { using namespace antlr4::misc; namespace { typedef std::shared_ptr<semantic_context> semantic_context_ptr; template<typename Container> std::vector<std::shared_ptr<semantic_context::precedence_predicate>> filter_precedence_predicates(Container& container) { std::vector<std::shared_ptr<semantic_context::precedence_predicate>> result; for (auto it = container.begin(); it != container.end(); /*empty*/) { if ((*it)->type() == semantic_context::context_type::precedence_predicate) { result.push_back(std::static_pointer_cast<semantic_context::precedence_predicate>(*it)); container.erase(it++); } else { ++it; } } return std::move(result); } } const std::shared_ptr<semantic_context> semantic_context::none = std::make_shared<semantic_context::predicate>(-1, -1, false); std::shared_ptr<semantic_context> semantic_context::combine_and(std::shared_ptr<semantic_context> const& x, std::shared_ptr<semantic_context> const& y) { if (!x || x == none) { return y; } if (!y || y == none) { return x; } auto result = std::make_shared<and_operator>(x, y); if (result->operands().size() == 1) { return result->operands()[0]; } return std::move(result); } std::shared_ptr<semantic_context> semantic_context::combine_or(std::shared_ptr<semantic_context> const& x, std::shared_ptr<semantic_context> const& y) { if (!x) { return y; } if (!y) { return x; } if (x == none || y == none) { return none; } auto result = std::make_shared<or_operator>(x, y); if (result->operands().size() == 1) { return result->operands()[0]; } return std::move(result); } semantic_context::and_operator::and_operator(std::shared_ptr<semantic_context> const& x, std::shared_ptr<semantic_context> const& y) : semantic_context(context_type::and_operator) { unordered_ptr_set<semantic_context_ptr> operands; if (x->type() == context_type::and_operator) { and_operator* x_and = static_cast<and_operator*>(x.get()); operands.insert(x_and->operands().begin(), x_and->operands().end()); } else { operands.insert(x); } if (y->type() == context_type::and_operator) { and_operator* y_and = static_cast<and_operator*>(y.get()); operands.insert(y_and->operands().begin(), y_and->operands().end()); } else { operands.insert(y); } std::vector<std::shared_ptr<precedence_predicate>> precedence_predicates(filter_precedence_predicates(operands)); if (!precedence_predicates.empty()) { // interested in the transition with the lowest precedence auto reduced = std::min_element( precedence_predicates.begin(), precedence_predicates.end(), [](std::shared_ptr<precedence_predicate> const& x, std::shared_ptr<precedence_predicate> const& y) { return x->precedence() < y->precedence(); }); operands.insert(*reduced); } std::copy(operands.begin(), operands.end(), std::back_inserter(_operands)); } semantic_context::or_operator::or_operator(std::shared_ptr<semantic_context> const& x, std::shared_ptr<semantic_context> const& y) : semantic_context(context_type::or_operator) { unordered_ptr_set<semantic_context_ptr> operands; if (x->type() == context_type::or_operator) { or_operator* x_or = static_cast<or_operator*>(x.get()); operands.insert(x_or->operands().begin(), x_or->operands().end()); } else { operands.insert(x); } if (y->type() == context_type::or_operator) { or_operator* y_or = static_cast<or_operator*>(y.get()); operands.insert(y_or->operands().begin(), y_or->operands().end()); } else { operands.insert(y); } std::vector<std::shared_ptr<precedence_predicate>> precedence_predicates(filter_precedence_predicates(operands)); if (!precedence_predicates.empty()) { // interested in the transition with the highest precedence auto reduced = std::max_element( precedence_predicates.begin(), precedence_predicates.end(), [](std::shared_ptr<precedence_predicate> const& x, std::shared_ptr<precedence_predicate> const& y) { return x->precedence() < y->precedence(); }); operands.insert(*reduced); } std::copy(operands.begin(), operands.end(), std::back_inserter(_operands)); } bool operator== (semantic_context const& x, semantic_context const& y) { if (&x == &y) { return true; } if (x.type() != y.type()) { return false; } switch (x.type()) { case semantic_context::context_type::predicate: { semantic_context::predicate const& left = static_cast<semantic_context::predicate const&>(x); semantic_context::predicate const& right = static_cast<semantic_context::predicate const&>(y); return left.rule_index() == right.rule_index() && left.predicate_index() == right.predicate_index() && left.context_dependent() == right.context_dependent(); } case semantic_context::context_type::precedence_predicate: { semantic_context::precedence_predicate const& left = static_cast<semantic_context::precedence_predicate const&>(x); semantic_context::precedence_predicate const& right = static_cast<semantic_context::precedence_predicate const&>(y); return left.precedence() == right.precedence(); } case semantic_context::context_type::and_operator: { //semantic_context::and_operator const& left = static_cast<semantic_context::and_operator const&>(x); //semantic_context::and_operator const& right = static_cast<semantic_context::and_operator const&>(y); throw std::runtime_error("not implemented"); } case semantic_context::context_type::or_operator: { //semantic_context::or_operator const& left = static_cast<semantic_context::or_operator const&>(x); //semantic_context::or_operator const& right = static_cast<semantic_context::or_operator const&>(y); throw std::runtime_error("not implemented"); } default: assert(!"Invalid context type."); return false; } } } } namespace std { using namespace antlr4::atn; using namespace antlr4::misc; size_t hash<semantic_context>::operator() (semantic_context const& x) const { switch (x.type()) { case semantic_context::context_type::predicate: { semantic_context::predicate const& left = static_cast<semantic_context::predicate const&>(x); int32_t hash = murmur_hash::initialize(); hash = murmur_hash::update(hash, left.rule_index()); hash = murmur_hash::update(hash, left.predicate_index()); hash = murmur_hash::update(hash, left.context_dependent() ? 1 : 0); hash = murmur_hash::finish(hash, 3); return static_cast<size_t>(hash); } case semantic_context::context_type::precedence_predicate: { semantic_context::precedence_predicate const& left = static_cast<semantic_context::precedence_predicate const&>(x); int32_t hash = 1; hash = 31 * hash + left.precedence(); return static_cast<size_t>(hash); } case semantic_context::context_type::and_operator: { //semantic_context::and_operator const& left = static_cast<semantic_context::and_operator const&>(x); throw std::runtime_error("not implemented"); } case semantic_context::context_type::or_operator: { //semantic_context::or_operator const& left = static_cast<semantic_context::or_operator const&>(x); throw std::runtime_error("not implemented"); } default: assert(!"Invalid context type."); return false; } } }
c++
code
8,093
1,925
#ifndef INCLUDE_ROBOT_GIMBAL_HPP_ #define INCLUDE_ROBOT_GIMBAL_HPP_ #include <algorithm> #include "../utils.hpp" #include "servo.hpp" struct Gimbal { static constexpr float max_speed = deg2rad(540); enum Mode { attitude_mode, velocity_mode }; enum Frame { chassis, fixed, gimbal }; Servo yaw_servo; Servo pitch_servo; Mode mode; IMU chassis_imu; Attitude chassis_attitude; // The target angular speed in the frame `gimbal_fixed`: gravity aligned, // orientation fixed when the robot starts. Vector3 target_angular_velocity_in_gimbal_fixed; Attitude target_attitude; bool performing_action; bool following_chassis; GimbalValues<float> control_speed; void update_control(float time_step, Attitude attitude, IMU imu); Gimbal() : yaw_servo(true, deg2rad(-250), deg2rad(250), max_speed) , pitch_servo(true, deg2rad(-30), deg2rad(25), max_speed) , mode(Mode::attitude_mode) , chassis_imu() , chassis_attitude() , target_angular_velocity_in_gimbal_fixed() , target_attitude() , performing_action(false) , following_chassis(false) {} // float distance() const { return std::max(yaw_servo.distance(), pitch_servo.distance()); } float distance() const { if (mode == Mode::attitude_mode) { Attitude current; if (!performing_action && following_chassis) { current = attitude(Frame::chassis); } else { current = attitude(Frame::fixed); } return std::max(std::abs(current.yaw - target_attitude.yaw), std::abs(current.pitch - target_attitude.pitch)); } return 0.0; } // Angles in fixed frame only!!! void set_target_angles(GimbalValues<float> angle) { set_mode(Mode::attitude_mode); target_attitude = {.yaw = angle.yaw, .pitch = angle.pitch}; // if (mode == Mode::attitude_mode) { // target_attitude = target_attitude + chassis_attitude; // } } void set_target_speeds(GimbalValues<float> speed) { set_mode(Mode::velocity_mode); target_angular_velocity_in_gimbal_fixed = {.y = std::clamp(speed.pitch, -max_speed, max_speed), .z = std::clamp(speed.yaw, -max_speed, max_speed)}; } void reset_target_speeds() { target_angular_velocity_in_gimbal_fixed = {}; } void set_control_speeds(GimbalValues<float> speed) { control_speed.pitch = std::clamp(speed.pitch, -max_speed, max_speed); control_speed.yaw = std::clamp(speed.yaw, -max_speed, max_speed); } Attitude attitude(Frame frame) const { Attitude value = {.yaw = yaw_servo.angle.current, .pitch = pitch_servo.angle.current}; if (frame == Frame::fixed) value = value + chassis_attitude; return value; } GimbalValues<float> current_angles() const { return {.yaw = yaw_servo.angle.current, .pitch = pitch_servo.angle.current}; } GimbalValues<float> target_angles() const { return {.yaw = yaw_servo.angle.target, .pitch = pitch_servo.angle.target}; } Vector3 angular_velocity(Frame frame) const { Vector3 value = {.y = pitch_servo.speed.current, .z = yaw_servo.speed.current}; if (frame == Frame::fixed) value = value + chassis_imu.angular_velocity; return value; } GimbalValues<float> current_speeds() const { return {.yaw = yaw_servo.speed.current, .pitch = pitch_servo.speed.current}; } GimbalValues<float> target_speeds() const { return {.yaw = yaw_servo.speed.target, .pitch = pitch_servo.speed.target}; } void enable(bool value) { yaw_servo.enabled.desired = pitch_servo.enabled.desired = value; } void follow_chassis(bool value) { spdlog::info("[Chassis] follow_chassis -> {}", value); if (value != following_chassis) { following_chassis = value; reset_target_attitude(); } } void reset_target_attitude() { spdlog::info("[Chassis] reset_target_attitude [{}]", following_chassis); if (following_chassis) { target_attitude = attitude(Frame::chassis); } else { target_attitude = attitude(Frame::fixed); } } void set_mode(Mode _mode) { if (mode != _mode) { mode = _mode; if (mode == Mode::attitude_mode) { reset_target_attitude(); } } } GimbalValues<float> fixed_angles(GimbalValues<float> value, GimbalValues<Frame> frame) const { GimbalValues<float> chassis_angles = chassis_attitude; GimbalValues<float> servo_angles = current_angles(); for (size_t i = 0; i < value.size; i++) { if (frame[i] == Frame::chassis) { value[i] = value[i] + chassis_angles[i]; } else if (frame.yaw == Frame::gimbal) { value[i] = value[i] + chassis_angles[i] + servo_angles[i]; } else { float delta = normalize(value[i] - chassis_angles[i] - servo_angles[i]); const Servo *servo; if (i == 0) { servo = &yaw_servo; } else { servo = &pitch_servo; } if (servo_angles[i] + delta < servo->min_angle) { delta += 2 * M_PI; } else if (servo_angles[i] + delta > servo->max_angle) { delta -= 2 * M_PI; } value[i] = delta + chassis_angles[i] + servo_angles[i]; } } return value; } }; #endif // INCLUDE_ROBOT_GIMBAL_HPP_ */
c++
code
5,276
1,128
#ifndef STAN_MATH_PRIM_PROB_GUMBEL_LPDF_HPP #define STAN_MATH_PRIM_PROB_GUMBEL_LPDF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/log.hpp> #include <stan/math/prim/fun/max_size.hpp> #include <stan/math/prim/fun/size.hpp> #include <stan/math/prim/fun/size_zero.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <cmath> namespace stan { namespace math { /** \ingroup prob_dists * Returns the Gumbel log probability density for the given * location and scale. Given containers of matching sizes, returns the * log sum of densities. * * @tparam T_y type of real parameter * @tparam T_loc type of location parameter * @tparam T_scale type of scale parameter * @param y real parameter * @param mu location parameter * @param beta scale parameter * @return log probability density or log sum of probability densities * @throw std::domain_error if y is nan, mu is infinite, or beta is nonpositive * @throw std::invalid_argument if container sizes mismatch */ template <bool propto, typename T_y, typename T_loc, typename T_scale> return_type_t<T_y, T_loc, T_scale> gumbel_lpdf(const T_y& y, const T_loc& mu, const T_scale& beta) { using T_partials_return = partials_return_t<T_y, T_loc, T_scale>; using std::exp; using std::log; static const char* function = "gumbel_lpdf"; check_not_nan(function, "Random variable", y); check_finite(function, "Location parameter", mu); check_positive(function, "Scale parameter", beta); check_consistent_sizes(function, "Random variable", y, "Location parameter", mu, "Scale parameter", beta); if (size_zero(y, mu, beta)) { return 0.0; } if (!include_summand<propto, T_y, T_loc, T_scale>::value) { return 0.0; } T_partials_return logp(0.0); operands_and_partials<T_y, T_loc, T_scale> ops_partials(y, mu, beta); scalar_seq_view<T_y> y_vec(y); scalar_seq_view<T_loc> mu_vec(mu); scalar_seq_view<T_scale> beta_vec(beta); size_t N = max_size(y, mu, beta); VectorBuilder<true, T_partials_return, T_scale> inv_beta(size(beta)); VectorBuilder<include_summand<propto, T_scale>::value, T_partials_return, T_scale> log_beta(size(beta)); for (size_t i = 0; i < stan::math::size(beta); i++) { inv_beta[i] = 1.0 / value_of(beta_vec[i]); if (include_summand<propto, T_scale>::value) { log_beta[i] = log(value_of(beta_vec[i])); } } for (size_t n = 0; n < N; n++) { const T_partials_return y_dbl = value_of(y_vec[n]); const T_partials_return mu_dbl = value_of(mu_vec[n]); const T_partials_return y_minus_mu_over_beta = (y_dbl - mu_dbl) * inv_beta[n]; if (include_summand<propto, T_scale>::value) { logp -= log_beta[n]; } logp += -y_minus_mu_over_beta - exp(-y_minus_mu_over_beta); T_partials_return scaled_diff = inv_beta[n] * exp(-y_minus_mu_over_beta); if (!is_constant_all<T_y>::value) { ops_partials.edge1_.partials_[n] -= inv_beta[n] - scaled_diff; } if (!is_constant_all<T_loc>::value) { ops_partials.edge2_.partials_[n] += inv_beta[n] - scaled_diff; } if (!is_constant_all<T_scale>::value) { ops_partials.edge3_.partials_[n] += -inv_beta[n] + y_minus_mu_over_beta * inv_beta[n] - scaled_diff * y_minus_mu_over_beta; } } return ops_partials.build(logp); } template <typename T_y, typename T_loc, typename T_scale> inline return_type_t<T_y, T_loc, T_scale> gumbel_lpdf(const T_y& y, const T_loc& mu, const T_scale& beta) { return gumbel_lpdf<false>(y, mu, beta); } } // namespace math } // namespace stan #endif
c++
code
3,905
799
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <gmock/gmock-spec-builders.h> #include "mkldnn_plugin/mkldnn_graph.h" #include "test_graph.hpp" #include "single_layer_common.hpp" #include <mkldnn_plugin/mkldnn_extension_utils.h> #include "tests_common.hpp" using namespace ::testing; using namespace std; using namespace mkldnn; struct broadcast_test_params { std::string shape_precision; std::string precision; InferenceEngine::SizeVector in_shape; InferenceEngine::SizeVector out_shape; std::vector<std::function<void(MKLDNNPlugin::PrimitiveDescInfo)>> comp; }; template <typename data_t> void ref_broadcast(InferenceEngine::TBlob<data_t> &src, InferenceEngine::TBlob<data_t> &dst) { size_t i; const data_t *src_data = src.data(); InferenceEngine::SizeVector src_dims = src.getTensorDesc().getDims(); InferenceEngine::SizeVector srcStrides = src.getTensorDesc().getBlockingDesc().getStrides(); if (!src_dims.size()) src_dims = InferenceEngine::SizeVector(1, 1); if (!srcStrides.size()) srcStrides = InferenceEngine::SizeVector(1, 1); data_t* dst_data = dst.data(); InferenceEngine::SizeVector dst_dims = dst.getTensorDesc().getDims(); InferenceEngine::SizeVector dstStrides = dst.getTensorDesc().getBlockingDesc().getStrides(); if (src_dims.size() > dst_dims.size()) FAIL() << "Output tensor dimension is smaller then input tensor dimension"; size_t prefix_size = dst_dims.size() - src_dims.size(); for (i = 0; i < src_dims.size(); i++) { if (src_dims[i] != 1 && src_dims[i] != dst_dims[i + prefix_size]) FAIL() << "In/Output corresponding dimension must have the same value, or Input dimension is equal to 1"; } InferenceEngine::SizeVector src_aligned(dst_dims.size()); InferenceEngine::SizeVector srcStrides_aligned(dst_dims.size()); for (i = 0; i < dst_dims.size(); i++) { if (i < prefix_size) { src_aligned[i] = 1; srcStrides_aligned[i] = srcStrides[0]; } else { src_aligned[i] = src_dims[i - prefix_size]; srcStrides_aligned[i] = srcStrides[i - prefix_size]; } } size_t src_idx, work_amount_dst = dstStrides[0] * dst_dims[0]; InferenceEngine::SizeVector counters(dst_dims.size(), 0); for (size_t iwork = 0; iwork < work_amount_dst; ++iwork) { for (i = 0, src_idx = 0; i < dst_dims.size(); ++i) src_idx += counters[i] ? ((counters[i] % src_aligned[i]) * srcStrides_aligned[i]) : 0; dst_data[iwork] = src_data[src_idx]; for (int j = dst_dims.size() - 1; j >= 0; j--) { counters[j] = (counters[j] + 1) % dst_dims[j]; if (counters[j] != 0) break; } } } class MKLDNNCPUExtBroadcastTests : public TestsCommon, public WithParamInterface<broadcast_test_params> { std::string model_t = R"V0G0N( <net Name="Broadcast_net" version="2" precision="_IIDXP_" batch="1"> <layers> <layer name="input" type="Input" precision="_IIDXP_" id="1"> <output> <port id="1"> _IN_ </port> </output> </layer> <layer name="shape" type="Input" precision="_ISDXP_" id="2"> <output> <port id="2"> <dim>_DIM_SIZE_</dim> </port> </output> </layer> <layer name="output" id="2" type="Broadcast" precision="_IIDXP_"> <data/> <input> <port id="1"> _IN_ </port> <port id="2"> <dim>_DIM_SIZE_</dim> </port> </input> <output> <port id="3"> _OUT_ </port> </output> </layer> </layers> <edges> <edge from-layer="1" from-port="1" to-layer="2" to-port="1"/> <edge from-layer="2" from-port="2" to-layer="2" to-port="2"/> </edges> </net> )V0G0N"; std::string getModel(broadcast_test_params p) { std::string model = model_t; std::string in_shape = ""; std::string out_shape; REPLACE_WITH_STR(model, "_IIDXP_", p.precision); REPLACE_WITH_STR(model, "_ISDXP_", p.shape_precision); for (size_t i = 0; i < p.in_shape.size(); i++) { in_shape += "<dim>"; in_shape += std::to_string(p.in_shape[i]) + "</dim>\n"; } REPLACE_WITH_STR(model, "_IN_", in_shape); for (size_t i = 0; i < p.out_shape.size(); i++) { out_shape += "<dim>"; out_shape += std::to_string(p.out_shape[i]) + "</dim>\n"; } REPLACE_WITH_STR(model, "_OUT_", out_shape); REPLACE_WITH_NUM(model, "_DIM_SIZE_", p.out_shape.size()); return model; } protected: virtual void TearDown() { } virtual void SetUp() { try { TestsCommon::SetUp(); broadcast_test_params p = ::testing::WithParamInterface<broadcast_test_params>::GetParam(); std::string model = getModel(p); InferenceEngine::CNNNetReader net_reader; ASSERT_NO_THROW(net_reader.ReadNetwork(model.data(), model.length())); MKLDNNGraphTestClass graph; graph.CreateGraph(net_reader.getNetwork()); // Output Data InferenceEngine::OutputsDataMap out; out = net_reader.getNetwork().getOutputsInfo(); InferenceEngine::BlobMap outputBlobs; // Input Data InferenceEngine::Blob::Ptr dims; InferenceEngine::SizeVector vector_dim(1, p.out_shape.size()); if (p.shape_precision == "I32") { dims = InferenceEngine::make_shared_blob<int32_t>({ InferenceEngine::Precision::I32, vector_dim, InferenceEngine::TensorDesc::getLayoutByDims(vector_dim) }); dims->allocate(); for (size_t i = 0; i < p.out_shape.size(); i++) { static_cast<int32_t*>(dims->buffer())[i] = static_cast<int32_t>(p.out_shape[i]); } auto * dimsPtr = dynamic_cast<InferenceEngine::TBlob<int32_t>*>(dims.get()); if (dimsPtr == nullptr) FAIL() << "Cannot cast blob to TBlob<int32_t>."; } else if (p.shape_precision == "FP32") { dims = InferenceEngine::make_shared_blob<float>({ InferenceEngine::Precision::FP32, vector_dim, InferenceEngine::TensorDesc::getLayoutByDims(vector_dim) }); dims->allocate(); for (size_t i = 0; i < p.out_shape.size(); i++) { static_cast<float*>(dims->buffer())[i] = static_cast<float>(p.out_shape[i]); } auto * dimsPtr = dynamic_cast<InferenceEngine::TBlob<float>*>(dims.get()); if (dimsPtr == nullptr) FAIL() << "Cannot cast blob to TBlob<float>."; } InferenceEngine::BlobMap srcs; InferenceEngine::Blob::Ptr src; std::pair<std::string, InferenceEngine::DataPtr> item = *out.begin(); if (p.precision == "I32") { src = InferenceEngine::make_shared_blob<int32_t>({InferenceEngine::Precision::I32, p.in_shape, InferenceEngine::TensorDesc::getLayoutByDims(p.in_shape)}); src->allocate(); for (size_t i = 0; i < src->size(); i++) static_cast<int32_t*>(src->buffer())[i] = static_cast<int32_t>(i); auto * srcPtr = dynamic_cast<InferenceEngine::TBlob<int32_t>*>(src.get()); if (srcPtr == nullptr) FAIL() << "Cannot cast blob to TBlob<int32_t>."; srcs.insert(std::pair<std::string, InferenceEngine::Blob::Ptr>("input", src)); srcs.insert(std::pair<std::string, InferenceEngine::Blob::Ptr>("shape", dims)); // Output Blob InferenceEngine::TBlob<int32_t>::Ptr output; output = InferenceEngine::make_shared_blob<int32_t>(item.second->getTensorDesc()); output->allocate(); outputBlobs[item.first] = output; // Output Reference InferenceEngine::TBlob<int32_t> dst_ref(item.second->getTensorDesc()); dst_ref.allocate(); ref_broadcast(*srcPtr, dst_ref); // Infer graph.Infer(srcs, outputBlobs); for (int i = 0; i < dst_ref.size(); i++) { if (dst_ref.data()[i] != (*output).data()[i]) FAIL() << "The difference between res_ptr[i] and ref_ptr[i]"; } } else if (p.precision == "FP32") { src = InferenceEngine::make_shared_blob<float>({InferenceEngine::Precision::FP32, p.in_shape, InferenceEngine::TensorDesc::getLayoutByDims(p.in_shape)}); src->allocate(); fill_data_dbgval(src->buffer(), src->size()); auto * srcPtr = dynamic_cast<InferenceEngine::TBlob<float>*>(src.get()); if (srcPtr == nullptr) FAIL() << "Cannot cast blob to TBlob<float>."; srcs.insert(std::pair<std::string, InferenceEngine::Blob::Ptr>("input", src)); srcs.insert(std::pair<std::string, InferenceEngine::Blob::Ptr>("shape", dims)); // Output Blob InferenceEngine::TBlob<float>::Ptr output; output = InferenceEngine::make_shared_blob<float>(item.second->getTensorDesc()); output->allocate(); outputBlobs[item.first] = output; // Output Reference InferenceEngine::TBlob<float> dst_ref(item.second->getTensorDesc()); dst_ref.allocate(); ref_broadcast(*srcPtr, dst_ref); // Infer graph.Infer(srcs, outputBlobs); compare(*output, dst_ref); } else { return; } } catch (const InferenceEngine::details::InferenceEngineException &e) { FAIL() << e.what(); } } }; TEST_P(MKLDNNCPUExtBroadcastTests, TestsBroadcast) {} INSTANTIATE_TEST_CASE_P( TestsBroadcast, MKLDNNCPUExtBroadcastTests, ::testing::Values( // Params: shape_precision, precision, in_shape, out_shape broadcast_test_params{ "I32", "I32",{},{ 2, 3, 4 } }, broadcast_test_params{ "I32", "I32",{ 4, 1, 2 },{ 4, 2, 2 } }, broadcast_test_params{ "I32", "I32",{ 4, 2, 1 },{ 4, 2, 2 } }, broadcast_test_params{ "I32", "I32",{ 4, 2 },{ 2, 4, 2 } }, broadcast_test_params{ "I32", "I32",{ 4, 1, 1 },{ 4, 2, 1 } }, broadcast_test_params{ "I32", "I32",{ 2, 1, 3, 1 },{ 2, 2, 2, 3, 1 } }, broadcast_test_params{ "I32","FP32",{},{ 2, 3, 4 } }, broadcast_test_params{ "I32","FP32",{ 4, 1, 2 },{ 4, 2, 2 } }, broadcast_test_params{ "I32","FP32",{ 4, 2, 1 },{ 4, 2, 2 } }, broadcast_test_params{ "I32","FP32",{ 4, 2 },{ 2, 4, 2 } }, broadcast_test_params{ "I32","FP32",{ 4, 1, 1 },{ 4, 2, 1 } }, broadcast_test_params{ "I32","FP32", { 2, 1, 3, 1 },{ 2, 2, 2, 3, 1 } }, broadcast_test_params{"FP32","FP32",{ 2, 1, 3, 1 },{ 2, 2, 2, 3, 1 } } ));
c++
code
11,520
2,717