text
string
size
int64
token_count
int64
#include "testsetup.hpp" #include <py4dgeo/compute.hpp> #include <py4dgeo/epoch.hpp> #include <benchmark/benchmark.h> using namespace py4dgeo; static void distances_benchmark(benchmark::State& state) { auto [cloud, corepoints] = ahk_benchcloud(); Epoch epoch(*cloud); epoch.kdtree.build_tree(10); std::vector<double> scales{ 1.0 }; EigenNormalSet directions(corepoints->rows(), 3); EigenNormalSet orientation(1, 3); orientation << 0, 0, 1; // Precompute the multiscale directions compute_multiscale_directions( epoch, *corepoints, scales, orientation, directions); // We try to test all callback combinations auto wsfinder = radius_workingset_finder; auto uncertaintymeasure = standard_deviation_uncertainty; for (auto _ : state) { // Calculate the distances DistanceVector distances; UncertaintyVector uncertainties; compute_distances(*corepoints, 2.0, epoch, epoch, directions, 0.0, distances, uncertainties, wsfinder, uncertaintymeasure); } } BENCHMARK(distances_benchmark)->Unit(benchmark::kMillisecond); BENCHMARK_MAIN();
1,282
407
#pragma once #include "storage/downloader_queue_universal.hpp" #include "storage/downloading_policy.hpp" #include "storage/queued_country.hpp" #include "platform/downloader_defines.hpp" #include "platform/http_request.hpp" #include "platform/safe_callback.hpp" #include <cstdint> #include <functional> #include <memory> #include <string> #include <utility> #include <vector> namespace storage { // This interface encapsulates HTTP routines for receiving servers // URLs and downloading a single map file. class MapFilesDownloader { public: // Denotes bytes downloaded and total number of bytes. using ServersList = std::vector<std::string>; using ServersListCallback = platform::SafeCallback<void(ServersList const & serverList)>; virtual ~MapFilesDownloader() = default; /// Asynchronously downloads a map file, periodically invokes /// onProgress callback and finally invokes onDownloaded /// callback. Both callbacks will be invoked on the main thread. void DownloadMapFile(QueuedCountry && queuedCountry); // Removes item from m_quarantine queue when list of servers is not received. // Parent method must be called into override method. virtual void Remove(CountryId const & id); // Clears m_quarantine queue when list of servers is not received. // Parent method must be called into override method. virtual void Clear(); // Returns m_quarantine queue when list of servers is not received. // Parent method must be called into override method. virtual QueueInterface const & GetQueue() const; /** * @brief Async file download as string buffer (for small files only). * Request can be skipped if current servers list is empty. * Callback will be skipped on download error. * @param[in] url Final url part like "index.json" or "maps/210415/countries.txt". * @param[in] forceReset True - force reset current request, if any. */ void DownloadAsString(std::string url, std::function<bool (std::string const &)> && callback, bool forceReset = false); void SetServersList(ServersList const & serversList); void SetDownloadingPolicy(DownloadingPolicy * policy); void SetDataVersion(int64_t version) { m_dataVersion = version; } /// @name Legacy functions for Android resourses downloading routine. /// @{ void EnsureServersListReady(std::function<void ()> && callback); std::vector<std::string> MakeUrlListLegacy(std::string const & fileName) const; /// @} protected: bool IsDownloadingAllowed() const; std::vector<std::string> MakeUrlList(std::string const & relativeUrl) const; // Synchronously loads list of servers by http client. ServersList LoadServersList(); private: /** * @brief This method is blocking and should be called on network thread. * Default implementation receives a list of all servers that can be asked * for a map file and invokes callback on the main thread (@see ServersListCallback as SafeCallback). */ virtual void GetServersList(ServersListCallback const & callback); /// Asynchronously downloads the file and saves result to provided directory. virtual void Download(QueuedCountry && queuedCountry) = 0; /// @param[in] callback Called in main thread (@see GetServersList). void RunServersListAsync(std::function<void()> && callback); /// Current file downloading request for DownloadAsString. using RequestT = downloader::HttpRequest; std::unique_ptr<RequestT> m_fileRequest; ServersList m_serversList; int64_t m_dataVersion = 0; /// Used as guard for m_serversList assign. std::atomic_bool m_isServersListRequested = false; DownloadingPolicy * m_downloadingPolicy = nullptr; // This queue accumulates download requests before // the servers list is received on the network thread. Queue m_pendingRequests; }; } // namespace storage
3,820
1,082
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // ============================================================ // // BindingLog.inl // // // Implements inlined methods of BindingLog // // ============================================================ #ifndef __BINDER__BINDING_LOG_INL__ #define __BINDER__BINDING_LOG_INL__ BOOL BindingLog::CanLog() { return (m_pCDebugLog != NULL); } CDebugLog *BindingLog::GetDebugLog() { _ASSERTE(m_pCDebugLog != NULL); return m_pCDebugLog; } HRESULT BindingLog::Log(LPCWSTR pwzInfo) { PathString info(pwzInfo); return BindingLog::Log(info); } HRESULT BindingLog::Log(LPCWSTR pwzPrefix, SString &info) { PathString message; message.Append(pwzPrefix); message.Append(info); return Log(message); } #endif
917
310
#ifndef PDMATH_UTIL_HPP #define PDMATH_UTIL_HPP #include <cstdint> #include <utility> namespace pdm { static constexpr uint8_t float_precision = 7; static constexpr float float_epsilon = 1.0e-6f; static float clamp(const float val, const float min, const float max) { if(val > max) { return max; } if(val < min) { return min; } return val; } static float clamp(const float val, const std::pair<float, float> &min_max) { if(val > min_max.second) { return min_max.second; } if(val < min_max.first) { return min_max.first; } return val; } static bool overlap(const std::pair<float, float> &a, const std::pair<float, float> &b) { return (a.second >= b.first) && (a.first <= b.second); } static bool overlap(const float a_min, const float a_max, const float b_min, const float b_max) { return (a_max >= b_min) && (a_min <= b_max); } } //namespace pdm #endif // PDMATH_UTIL_HPP
1,014
371
#include <iostream> #include "./../include/loadParams.hpp" int main(int argc, char* argv[]) { LoadParams *load; load = new LoadParams(); float test_num = 0; double test_double = 0; //char test_error = 0; std::string test_str; bool test_bool = true; load->get_param<float>("test3", test_num); load->get_param<double>("test4", test_double); //load->get_param<char>("test4", test_error); load->get_param<std::string>("set_string", test_str); load->get_param<bool>("set_bool", test_bool); load->get_param<bool>("error_bool", test_bool); std::cout << test_num << std::endl; std::cout << test_double << std::endl; std::cout << test_str << std::endl; std::cout << test_bool << std::endl; return 0; }
734
282
#include "gtest/gtest.h" #include "library.h" // #include "fff.h" // DEFINE_FFF_GLOBALS; // FAKE_VALUE_FUNC(int, library_func, int); // FAKE_VOID_FUNC(another_func, int); TEST(example, behaviour) { EXPECT_EQ(library_func(0),0); EXPECT_EQ(library_func(1),1); EXPECT_EQ(library_func(0),1); EXPECT_EQ(library_func(5),6); }
326
158
#include "SceneMenu.hpp" #include "SceneOptions.hpp" #include "SceneGame.hpp" #include "../Game.hpp" SceneMenu::SceneMenu(Scene*& currentScene) : currentScene(currentScene) { } SceneMenu::~SceneMenu() { } void SceneMenu::onUpdate(std::chrono::milliseconds deltaTime) { } void SceneMenu::onRender(Renderer* renderer) { renderer->clear(); renderer->clearColor(0.176470588F, 0.176470588F, 0.176470588F, 1.0F); } void SceneMenu::onGUIRender(GUIRenderer* guiRenderer) { guiRenderer->begin("Game", (float)Game::getInstance()->getWindow()->getWidth() / 2.0F - 100.0F, 100.0F, 200.0F, 300.0F); guiRenderer->row(15, 1); guiRenderer->row(70, 1); if (guiRenderer->button("Play")) { currentScene = new SceneGame(); } guiRenderer->row(15, 1); guiRenderer->row(70, 1); if (guiRenderer->button("Options")) { currentScene = new SceneOptions(); } guiRenderer->row(15, 1); guiRenderer->row(70, 1); if (guiRenderer->button("Exit")) { done = true; } guiRenderer->end(); } void SceneMenu::onMouseButton(int button, int action, int modifiers) { }
1,058
448
/* * TtbarHypothesis.cpp * * Created on: Dec 4, 2010 * Author: lkreczko */ #include "../interface/TtbarHypothesis.h" #include "../interface/ReconstructionModules/ReconstructionException.h" //#include "../interface/ReconstructionModules/BasicNeutrinoReconstruction.h" // #include <iostream> // using namespace std; namespace BAT { TtbarHypothesis::TtbarHypothesis() : totalChi2(99999.), // leptonicChi2(99999.), // hadronicChi2(99999.), // globalChi2(99999.), // neutrinoChi2(99999.),// discriminator(999999), // NuChi2Discriminator(99999), MassDiscriminator(99999), CSVDiscriminator(99999), hadronicTop(), // leptonicTop(), // leptonicW(), // hadronicW(), // resonance(), // neutrinoFromW(), // leptonicBjet(), // hadronicBJet(), // jet1FromW(), // jet2FromW(), // leptonFromW(), // met(), // decayChannel(Decay::unknown) { } TtbarHypothesis::TtbarHypothesis(const LeptonPointer& lepton, const ParticlePointer& neut, const JetPointer& lepBJet, const JetPointer& hadBJet, const JetPointer& hadWJet1, const JetPointer& hadWJet2) : totalChi2(99999.), // leptonicChi2(99999.), // hadronicChi2(99999.), // globalChi2(99999.), // neutrinoChi2(99999.),// discriminator(999999), // NuChi2Discriminator(99999), MassDiscriminator(99999), CSVDiscriminator(99999), hadronicTop(), // leptonicTop(), // leptonicW(new Particle(*lepton + *neut)), // hadronicW(new Particle(*hadWJet1 + *hadWJet2)), // resonance(), // neutrinoFromW(neut), // leptonicBjet(lepBJet), // hadronicBJet(hadBJet), // jet1FromW(hadWJet1), // jet2FromW(hadWJet2), // leptonFromW(lepton), // met(new MET(neut->px(), neut->py())), // decayChannel(Decay::unknown) { } TtbarHypothesis::~TtbarHypothesis() { } bool TtbarHypothesis::isCorrect() const { bool isCorrect = false; if (hadronicBJet->ttbar_decay_parton() == 6){ if (leptonicBjet->ttbar_decay_parton() == 5){ if ((jet1FromW->ttbar_decay_parton() == 3 && jet2FromW->ttbar_decay_parton() == 4 ) || (jet2FromW->ttbar_decay_parton() == 3 && jet1FromW->ttbar_decay_parton() == 4 )){ isCorrect = true; } } } // std::cout << "Event Reconstruction is : " << isCorrect << std::endl; return isCorrect; } bool TtbarHypothesis::isValid() const { bool hasObjects = leptonFromW && neutrinoFromW && jet1FromW && jet2FromW && hadronicBJet && leptonicBjet; return hasObjects; } bool TtbarHypothesis::isPhysical() const { bool hasPhysicalSolution = leptonicTop->mass() > 0 && leptonicW->mass() > 0 && hadronicW->mass() > 0 && hadronicTop->mass() > 0; return hasPhysicalSolution; } void TtbarHypothesis::combineReconstructedObjects() { if (isValid()) { leptonicW = ParticlePointer(new Particle(*neutrinoFromW + *leptonFromW)); if (jet1FromW != jet2FromW) hadronicW = ParticlePointer(new Particle(*jet1FromW + *jet2FromW)); else hadronicW = jet1FromW; leptonicTop = ParticlePointer(new Particle(*leptonicBjet + *leptonicW)); hadronicTop = ParticlePointer(new Particle(*hadronicBJet + *hadronicW)); resonance = ParticlePointer(new Particle(*leptonicTop + *hadronicTop)); // if(fabs(leptonicW->mass() - BasicNeutrinoReconstruction::W_mass) > 0.1) // cout << "Unexpected mass difference " << fabs(leptonicW->mass() - BasicNeutrinoReconstruction::W_mass) << endl; } else { throwDetailedException(); } } void TtbarHypothesis::throwDetailedException() const { std::string msg = "TTbar Hypothesis not filled properly: \n"; if (leptonFromW == 0) msg += "Lepton from W: not filled \n"; else msg += "Lepton from W: filled \n"; if (neutrinoFromW == 0) msg += "Neutrino from W: not filled \n"; else msg += "Neutrino from W: filled \n"; if (jet1FromW == 0) msg += "Jet 1 from W: not filled \n"; else msg += "Jet 1 from W: filled \n"; if (jet2FromW == 0) msg += "Jet 2 from W: not filled \n"; else msg += "Jet 2 from W: filled \n"; if (leptonicBjet == 0) msg += "Leptonic b-jet: not filled \n"; else msg += "Leptonic b-jet: filled \n"; if (hadronicBJet == 0) msg += "Hadronic b-jet: not filled \n"; else msg += "Hadronic b-jet: filled \n"; throw ReconstructionException(msg); } double TtbarHypothesis::M3() const { JetCollection jets; jets.clear(); jets.push_back(jet1FromW); jets.push_back(jet2FromW); jets.push_back(leptonicBjet); jets.push_back(hadronicBJet); return M3(jets); } double TtbarHypothesis::M3(const JetCollection jets) { double m3(0), max_pt(0); if (jets.size() >= 3) { for (unsigned int index1 = 0; index1 < jets.size() - 2; ++index1) { for (unsigned int index2 = index1 + 1; index2 < jets.size() - 1; ++index2) { for (unsigned int index3 = index2 + 1; index3 < jets.size(); ++index3) { FourVector m3Vector( jets.at(index1)->getFourVector() + jets.at(index2)->getFourVector() + jets.at(index3)->getFourVector()); double currentPt = m3Vector.Pt(); if (currentPt > max_pt) { max_pt = currentPt; m3 = m3Vector.M(); } } } } } return m3; } double TtbarHypothesis::sumPt() const { return leptonicBjet->pt() + hadronicBJet->pt() + jet1FromW->pt() + jet2FromW->pt(); } double TtbarHypothesis::PtTtbarSystem() const { return resonance->pt(); } } // namespace BAT
5,258
2,387
#include <iostream> void bitwise(int a, int b) { std::cout << "a and b: " << (a & b) << '\n'; // Note: parentheses are needed because & has lower precedence than << std::cout << "a or b: " << (a | b) << '\n'; std::cout << "a xor b: " << (a ^ b) << '\n'; std::cout << "not a: " << ~a << '\n'; std::cout << "a shl b: " << (a << b) << '\n'; // Note: "<<" is used both for output and for left shift std::cout << "a shr b: " << (a >> b) << '\n'; // typically arithmetic right shift, but not guaranteed unsigned int c = a; std::cout << "c sra b: " << (c >> b) << '\n'; // logical right shift (guaranteed) // there are no rotation operators in C++ }
674
248
/* Copyright 2014 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. */ #include "appsensorapi/handlermanager.h" #include <gtest/gunit.h> #include "appsensorapi/handler.h" #include "appsensorapi/versionreader.h" using ime_goopy::HandlerManager; using ime_goopy::VersionInfo; using ime_goopy::Handler; namespace { const int kNumHandlers = 20; // Customize the handler with special rules to validate if the rules are // invoked. class CustomHandler : public Handler { public: explicit CustomHandler(size_t size) : Handler() { version_info_.file_size = size; } // Validate if the method is invoked by whether data is null. BOOL HandleCommand(uint32 command, void *data) const { return data != NULL; } // Validate if the method is invoked by whether wparam is zero. LRESULT HandleMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) const { return wparam != 0; } private: DISALLOW_EVIL_CONSTRUCTORS(CustomHandler); }; class HandlerManagerTest : public testing::Test { protected: void SetUp() { handler_manager_.reset(new HandlerManager()); for (int i = 0; i < arraysize(handler_); i++) { handler_[i] = NULL; } } void TearDown() { for (int i = 0; i < arraysize(handler_); i++) { delete handler_[i]; handler_[i] = NULL; } } // Create an array of handlers with specified size. They are used to // validate the logic of HandlerManager. void PrepareData() { for (int i = 0; i < arraysize(handler_); i++) { handler_[i] = new CustomHandler(1000 * (i + 1)); ASSERT_TRUE(handler_manager_->AddHandler(handler_[i])); } ASSERT_EQ(arraysize(handler_), handler_manager_->GetCount()); } scoped_ptr<HandlerManager> handler_manager_; CustomHandler *handler_[kNumHandlers]; }; TEST_F(HandlerManagerTest, AddHandler) { // Prepare handler instances. for (int i = 0; i < arraysize(handler_); i++) { handler_[i] = new CustomHandler(1000 * (i + 1)); } // Add the handlers and validate its success. for (int i = 0; i < arraysize(handler_); i++) { EXPECT_TRUE(handler_manager_->AddHandler(handler_[i])); EXPECT_EQ(i + 1, handler_manager_->GetCount()); } // Add the same handlers, should be failed and the number of handlers // should not be changed. for (int i = 0; i < arraysize(handler_); i++) { EXPECT_FALSE(handler_manager_->AddHandler(handler_[i])); EXPECT_EQ(arraysize(handler_), handler_manager_->GetCount()); } } TEST_F(HandlerManagerTest, RemoveHandler) { // Prepare the handlers array. PrepareData(); // Remove each handler and validate the number of handlers is // decreasing. for (int i = 0; i < arraysize(handler_); i++) { EXPECT_TRUE(handler_manager_->RemoveHandler(handler_[i])); EXPECT_EQ(arraysize(handler_) - i - 1, handler_manager_->GetCount()); } // Try to remove again, should not be able to removed. for (int i = 0; i < arraysize(handler_); i++) { EXPECT_FALSE(handler_manager_->RemoveHandler(handler_[i])); } EXPECT_EQ(0, handler_manager_->GetCount()); } TEST_F(HandlerManagerTest, GetHandlerBySize) { // Prepare the handlers array. PrepareData(); // Validate all handlers are obtained by their sizes. for (int i = 0; i < arraysize(handler_); i++) { const Handler *handler = handler_manager_->GetHandlerBySize( handler_[i]->version_info()->file_size); ASSERT_TRUE(handler != NULL); EXPECT_EQ(handler_[i]->version_info()->file_size, handler->version_info()->file_size); } // Try to remove each handler, then validate the failure of the method. for (int i = 0; i < arraysize(handler_); i++) { ASSERT_TRUE(handler_manager_->RemoveHandler(handler_[i])); EXPECT_TRUE(handler_manager_->GetHandlerBySize( handler_[i]->version_info()->file_size) == NULL); } } TEST_F(HandlerManagerTest, GetHandlerByInfo) { // Prepare the handlers array. PrepareData(); // Validate all handlers are obtained by their info. for (int i = 0; i < arraysize(handler_); i++) { const Handler *handler = handler_manager_->GetHandlerByInfo( *handler_[i]->version_info()); ASSERT_TRUE(handler != NULL); EXPECT_EQ(handler_[i]->version_info()->file_size, handler->version_info()->file_size); } // Try to remove each handler, then validate the failure of the method. for (int i = 0; i < arraysize(handler_); i++) { ASSERT_TRUE(handler_manager_->RemoveHandler(handler_[i])); EXPECT_TRUE(handler_manager_->GetHandlerByInfo( *handler_[i]->version_info()) == NULL); } } TEST_F(HandlerManagerTest, HandleCommand) { PrepareData(); // Validate the customized rule is invoked. // The rule is based on the assume: // data = non-null -> return true // null -> return false EXPECT_TRUE(handler_manager_->HandleCommand( *handler_[0]->version_info(), 1, "Not Null")); EXPECT_FALSE(handler_manager_->HandleCommand( *handler_[0]->version_info(), 1, NULL)); } TEST_F(HandlerManagerTest, HandleMessage) { PrepareData(); // Validate the customized rule is invoked. // The rule is based on the assume: // wparam = non-zero -> return true // zero -> return false EXPECT_TRUE(handler_manager_->HandleMessage( *handler_[0]->version_info(), NULL, WM_USER, 1, 0)); EXPECT_FALSE(handler_manager_->HandleMessage( *handler_[0]->version_info(), NULL, WM_USER, 0, 0)); } } // namespace int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
6,145
2,034
#include "depthai/pipeline/node/EdgeDetector.hpp" #include "spdlog/fmt/fmt.h" namespace dai { namespace node { EdgeDetector::EdgeDetector(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId) : Node(par, nodeId), rawConfig(std::make_shared<RawEdgeDetectorConfig>()), initialConfig(rawConfig) { inputs = {&inputConfig, &inputImage}; outputs = {&outputImage, &passthroughInputImage}; } std::string EdgeDetector::getName() const { return "EdgeDetector"; } nlohmann::json EdgeDetector::getProperties() { nlohmann::json j; properties.initialConfig = *rawConfig; nlohmann::to_json(j, properties); return j; } // Node properties configuration void EdgeDetector::setWaitForConfigInput(bool wait) { properties.inputConfigSync = wait; } void EdgeDetector::setNumFramesPool(int numFramesPool) { properties.numFramesPool = numFramesPool; } void EdgeDetector::setMaxOutputFrameSize(int maxFrameSize) { properties.outputFrameSize = maxFrameSize; } std::shared_ptr<Node> EdgeDetector::clone() { return std::make_shared<std::decay<decltype(*this)>::type>(*this); } } // namespace node } // namespace dai
1,152
381
//------------------------------------------------------------- // Based on Variant.cc in the Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - // Licensed under a LGPL-2 or later license - //------------------------------------------------------------- #include "crpropa/Variant.h" #include <algorithm> namespace crpropa { Variant::Variant() : type(TYPE_NONE) { } Variant::~Variant() { clear(); } Variant::Variant(const Variant& a) : type(TYPE_NONE) { copy(a); } Variant::Variant(const char *s) { data._String = new std::string(s); type = TYPE_STRING; } void Variant::clear() { if (type == TYPE_STRING) { if(data._String) { delete data._String; data._String = NULL; } } type = TYPE_NONE; } void Variant::check(const Type t) const { if (type != t) throw bad_conversion(type, t); } void Variant::check(const Type t) { if (type == TYPE_NONE) { std::memset(&data, 0, sizeof(data)); switch (t) { case TYPE_STRING: data._String = new std::string; break; default: break; } type = t; } else if (type != t) { throw bad_conversion(type, t); } } const std::type_info& Variant::getTypeInfo() const { if (type == TYPE_BOOL) { const std::type_info &ti = typeid(data._Bool); return ti; } else if (type == TYPE_CHAR) { const std::type_info &ti = typeid(data._Char); return ti; } else if (type == TYPE_UCHAR) { const std::type_info &ti = typeid(data._UChar); return ti; } else if (type == TYPE_INT16) { const std::type_info &ti = typeid(data._Int16); return ti; } else if (type == TYPE_UINT16) { const std::type_info &ti = typeid(data._UInt16); return ti; } else if (type == TYPE_INT32) { const std::type_info &ti = typeid(data._Int32); return ti; } else if (type == TYPE_UINT32) { const std::type_info &ti = typeid(data._UInt32); return ti; } else if (type == TYPE_INT64) { const std::type_info &ti = typeid(data._Int64); return ti; } else if (type == TYPE_UINT64) { const std::type_info &ti = typeid(data._UInt64); return ti; } else if (type == TYPE_FLOAT) { const std::type_info &ti = typeid(data._Float); return ti; } else if (type == TYPE_DOUBLE) { const std::type_info &ti = typeid(data._Double); return ti; } else if (type == TYPE_STRING) { const std::type_info &ti = typeid(*data._String); return ti; } else { const std::type_info &ti = typeid(0); return ti; } } const char *Variant::getTypeName(Type type) { if (type == TYPE_NONE) { return "none"; } else if (type == TYPE_BOOL) { return "bool"; } else if (type == TYPE_CHAR) { return "char"; } else if (type == TYPE_UCHAR) { return "uchar"; } else if (type == TYPE_INT16) { return "int16"; } else if (type == TYPE_UINT16) { return "uint16"; } else if (type == TYPE_INT32) { return "int32"; } else if (type == TYPE_UINT32) { return "uint32"; } else if (type == TYPE_INT64) { return "int64"; } else if (type == TYPE_UINT64) { return "uint64"; } else if (type == TYPE_FLOAT) { return "float"; } else if (type == TYPE_DOUBLE) { return "double"; } else if (type == TYPE_STRING) { return "string"; } else { return "unknown"; } } Variant::Type Variant::toType(const std::string &name) { if (name == "none") { return TYPE_NONE; } else if (name == "bool") { return TYPE_BOOL; } else if (name == "char") { return TYPE_CHAR; } else if (name == "uchar") { return TYPE_UCHAR; } else if (name == "int16") { return TYPE_INT16; } else if (name == "uint16") { return TYPE_UINT16; } else if (name == "int32") { return TYPE_INT32; } else if (name == "uint32") { return TYPE_UINT32; } else if (name == "int64") { return TYPE_INT64; } else if (name == "uint64") { return TYPE_UINT64; } else if (name == "float") { return TYPE_FLOAT; } else if (name == "double") { return TYPE_DOUBLE; } else if (name == "string") { return TYPE_STRING; } else { return TYPE_NONE; } } bool Variant::operator ==(const Variant &a) const { if (type != a.type) return false; if (type == TYPE_BOOL) { return (data._Bool == a.data._Bool); } else if (type == TYPE_CHAR) { return (data._Char == a.data._Char); } else if (type == TYPE_UCHAR) { return (data._UChar == a.data._UChar); } else if (type == TYPE_INT16) { return (data._Int16 == a.data._Int16); } else if (type == TYPE_UINT16) { return (data._UInt16 == a.data._UInt16); } else if (type == TYPE_INT32) { return (data._Int32 == a.data._Int32); } else if (type == TYPE_UINT32) { return (data._UInt32 == a.data._UInt32); } else if (type == TYPE_INT64) { return (data._Int64 == a.data._Int64); } else if (type == TYPE_UINT64) { return (data._UInt64 == a.data._UInt64); } else if (type == TYPE_FLOAT) { return (data._Float == a.data._Float); } else if (type == TYPE_DOUBLE) { return (data._Double == a.data._Double); } else if (type == TYPE_STRING) { return (*data._String == *a.data._String); } else { throw std::runtime_error("compare operator not implemented"); } } std::string Variant::toString() const { if (type == TYPE_STRING) return *data._String; std::stringstream sstr; if (type == TYPE_BOOL) { sstr << data._Bool; } else if (type == TYPE_CHAR) { sstr << data._Char; } else if (type == TYPE_UCHAR) { sstr << data._UChar; } else if (type == TYPE_INT16) { sstr << data._Int16; } else if (type == TYPE_UINT16) { sstr << data._UInt16; } else if (type == TYPE_INT32) { sstr << data._Int32; } else if (type == TYPE_UINT32) { sstr << data._UInt32; } else if (type == TYPE_INT64) { sstr << data._Int64; } else if (type == TYPE_UINT64) { sstr << data._UInt64; } else if (type == TYPE_FLOAT) { sstr << std::scientific << data._Float; } else if (type == TYPE_DOUBLE) { sstr << std::scientific << data._Double; } return sstr.str(); } Variant Variant::fromString(const std::string &str, Type type) { std::stringstream sstr(str); switch (type) { case TYPE_BOOL: { std::string upperstr(str); std::transform(upperstr.begin(), upperstr.end(), upperstr.begin(), (int(*)(int))toupper);if ( upperstr == "YES") return Variant(true); else if (upperstr == "NO") return Variant(false); if (upperstr == "TRUE") return Variant(true); else if (upperstr == "FALSE") return Variant(false); if (upperstr == "1") return Variant(true); else if (upperstr == "0") return Variant(false); throw bad_conversion(type, TYPE_BOOL); } case TYPE_CHAR: { char c; sstr >> c; return Variant(c); } case TYPE_UCHAR: { unsigned char c; sstr >> c; return Variant(c); } case TYPE_INT16: { int16_t c; sstr >> c; return Variant(c); } case TYPE_UINT16: { uint16_t c; sstr >> c; return Variant(c); } case TYPE_INT32: { int32_t c; sstr >> c; return Variant(c); } case TYPE_UINT32: { uint32_t c; sstr >> c; return Variant(c); } case TYPE_INT64: { int64_t c; sstr >> c; return Variant(c); } case TYPE_UINT64: { uint64_t c; sstr >> c; return Variant(c); } case TYPE_FLOAT: { float c; sstr >> c; return Variant(c); } case TYPE_DOUBLE: { double c; sstr >> c; return Variant(c); } case TYPE_STRING: { return Variant(str); } default: throw std::runtime_error("pxl::Variant::fromString: unknown type"); } } bool Variant::operator !=(const Variant &a) const { if (type != a.type) return true; switch (type) { case TYPE_BOOL: return (data._Bool != a.data._Bool); case TYPE_CHAR: return (data._Char != a.data._Char); case TYPE_UCHAR: return (data._UChar != a.data._UChar); case TYPE_INT16: return (data._Int16 != a.data._Int16); case TYPE_UINT16: return (data._UInt16 == a.data._UInt16); case TYPE_INT32: return (data._Int32 == a.data._Int32); case TYPE_UINT32: return (data._UInt32 == a.data._UInt32); case TYPE_INT64: return (data._Int64 == a.data._Int64); case TYPE_UINT64: return (data._UInt64 == a.data._UInt64); case TYPE_FLOAT: return (data._Float == a.data._Float); case TYPE_DOUBLE: return (data._Double == a.data._Double); case TYPE_STRING: return (*data._String == *a.data._String); default: throw std::runtime_error("compare operator not implemented"); } } void Variant::copy(const Variant &a) { Type t = a.type; if (t == TYPE_BOOL) { operator =(a.data._Bool); } else if (t == TYPE_CHAR) { operator =(a.data._Char); } else if (t == TYPE_UCHAR) { operator =(a.data._UChar); } else if (t == TYPE_INT16) { operator =(a.data._Int16); } else if (t == TYPE_UINT16) { operator =(a.data._UInt16); } else if (t == TYPE_INT32) { operator =(a.data._Int32); } else if (t == TYPE_UINT32) { operator =(a.data._UInt32); } else if (t == TYPE_INT64) { operator =(a.data._Int64); } else if (t == TYPE_UINT64) { operator =(a.data._UInt64); } else if (t == TYPE_FLOAT) { operator =(a.data._Float); } else if (t == TYPE_DOUBLE) { operator =(a.data._Double); } else if (t == TYPE_STRING) { operator =(*a.data._String); } else { type = TYPE_NONE; } } bool Variant::toBool() const { switch (type) { case TYPE_BOOL: return data._Bool; break; case TYPE_CHAR: return data._Char != 0; break; case TYPE_UCHAR: return data._UChar != 0; break; case TYPE_INT16: return data._Int16 != 0; break; case TYPE_UINT16: return data._UInt16 != 0; break; case TYPE_INT32: return data._Int32 != 0; break; case TYPE_UINT32: return data._UInt32 != 0; break; case TYPE_INT64: return data._Int64 != 0; break; case TYPE_UINT64: return data._UInt64 != 0; break; case TYPE_STRING: { std::string upperstr(*data._String); std::transform(upperstr.begin(), upperstr.end(), upperstr.begin(), (int(*)(int))toupper);if ( upperstr == "YES") return true; else if (upperstr == "NO") return false; if (upperstr == "TRUE") return true; else if (upperstr == "FALSE") return false; if (upperstr == "1") return true; else if (upperstr == "0") return false; else throw bad_conversion(type, TYPE_BOOL); } break; case TYPE_FLOAT: case TYPE_DOUBLE: case TYPE_NONE: throw bad_conversion(type, TYPE_BOOL); break; } return false; } #define INT_CASE(from_var, from_type, to_type, to) \ case Variant::from_type:\ if (data._##from_var < std::numeric_limits<to>::min() || data._##from_var > std::numeric_limits<to>::max())\ throw bad_conversion(type, to_type);\ else\ return static_cast<to>(data._##from_var);\ break;\ #define INT_FUNCTION(to_type, fun, to) \ to Variant::fun() const { \ switch (type) { \ case Variant::TYPE_BOOL: \ return data._Bool ? 1 : 0; \ break; \ INT_CASE(Char, TYPE_CHAR, to_type, to) \ INT_CASE(UChar, TYPE_UCHAR, to_type, to) \ INT_CASE(Int16, TYPE_INT16, to_type, to) \ INT_CASE(UInt16, TYPE_UINT16, to_type, to) \ INT_CASE(Int32, TYPE_INT32, to_type, to) \ INT_CASE(UInt32, TYPE_UINT32, to_type, to) \ INT_CASE(Int64, TYPE_INT64, to_type, to) \ INT_CASE(UInt64, TYPE_UINT64, to_type, to) \ INT_CASE(Float, TYPE_FLOAT, to_type, to) \ INT_CASE(Double, TYPE_DOUBLE, to_type, to) \ case Variant::TYPE_STRING: \ { \ long l = atol(data._String->c_str()); \ if (l < std::numeric_limits<to>::min() || l > std::numeric_limits<to>::max()) \ throw bad_conversion(type, to_type); \ else \ return l; \ } \ break; \ case Variant::TYPE_NONE: \ throw bad_conversion(type, TYPE_INT16); \ break;\ }\ return 0;\ } INT_FUNCTION( TYPE_CHAR, toChar, char) INT_FUNCTION( TYPE_UCHAR, toUChar, unsigned char) INT_FUNCTION( TYPE_INT16, toInt16, int16_t) INT_FUNCTION( TYPE_UINT16, toUInt16, uint16_t) INT_FUNCTION( TYPE_INT32, toInt32, int32_t) INT_FUNCTION( TYPE_UINT32, toUInt32, uint32_t) INT_FUNCTION( TYPE_INT64, toInt64, int64_t) INT_FUNCTION( TYPE_UINT64, toUInt64, uint64_t) std::ostream& operator <<(std::ostream& os, const Variant &v) { switch (v.getType()) { case Variant::TYPE_BOOL: os << v.asBool(); break; case Variant::TYPE_CHAR: os << v.asChar(); break; case Variant::TYPE_UCHAR: os << v.asUChar(); break; case Variant::TYPE_INT16: os << v.asInt16(); break; case Variant::TYPE_UINT16: os << v.asUInt16(); break; case Variant::TYPE_INT32: os << v.asInt32(); break; case Variant::TYPE_UINT32: os << v.asUInt32(); break; case Variant::TYPE_INT64: os << v.asInt64(); break; case Variant::TYPE_UINT64: os << v.asUInt64(); break; case Variant::TYPE_FLOAT: os << v.asFloat(); break; case Variant::TYPE_DOUBLE: os << v.asDouble(); break; case Variant::TYPE_STRING: os << v.asString(); break; default: break; } return os; } float Variant::toFloat() const { if (type == TYPE_CHAR) { return static_cast<float>(data._Char); } else if (type == TYPE_UCHAR) { return static_cast<float>(data._UChar); } else if (type == TYPE_INT16) { return static_cast<float>(data._Int16); } else if (type == TYPE_UINT16) { return static_cast<float>(data._UInt16); } else if (type == TYPE_INT32) { return static_cast<float>(data._Int32); } else if (type == TYPE_UINT32) { return static_cast<float>(data._UInt32); } else if (type == TYPE_INT64) { return static_cast<float>(data._Int64); } else if (type == TYPE_UINT64) { return static_cast<float>(data._UInt64); } else if (type == TYPE_FLOAT) { return static_cast<float>(data._Float); } else if (type == TYPE_DOUBLE) { return static_cast<float>(data._Double); } else if (type == TYPE_STRING) { return static_cast<float>(std::atof(data._String->c_str())); } else if (type == TYPE_BOOL) { return data._Bool ? 1.0f : 0.0f; } else { return 0.0; } } double Variant::toDouble() const { if (type == TYPE_CHAR) { return static_cast<double>(data._Char); } else if (type == TYPE_UCHAR) { return static_cast<double>(data._UChar); } else if (type == TYPE_INT16) { return static_cast<double>(data._Int16); } else if (type == TYPE_UINT16) { return static_cast<double>(data._UInt16); } else if (type == TYPE_INT32) { return static_cast<double>(data._Int32); } else if (type == TYPE_UINT32) { return static_cast<double>(data._UInt32); } else if (type == TYPE_INT64) { return static_cast<double>(data._Int64); } else if (type == TYPE_UINT64) { return static_cast<double>(data._UInt64); } else if (type == TYPE_FLOAT) { return static_cast<double>(data._Float); } else if (type == TYPE_DOUBLE) { return static_cast<double>(data._Double); } else if (type == TYPE_STRING) { return std::atof(data._String->c_str()); } else if (type == TYPE_BOOL) { return data._Bool ? 1.0 : 0.0; } else { return 0.0; } } #define MEMCPYRET(VAR) \ memcpy(buffer, &VAR, sizeof( VAR) );\ return sizeof( VAR ); size_t Variant::copyToBuffer(void* buffer) { if (type == TYPE_CHAR) { MEMCPYRET( data._Char ) } else if (type == TYPE_UCHAR) { MEMCPYRET( data._UChar ) } else if (type == TYPE_INT16) { MEMCPYRET(data._Int16); } else if (type == TYPE_UINT16) { MEMCPYRET(data._UInt16); } else if (type == TYPE_INT32) { MEMCPYRET(data._Int32); } else if (type == TYPE_UINT32) { MEMCPYRET(data._UInt32); } else if (type == TYPE_INT64) { MEMCPYRET(data._Int64); } else if (type == TYPE_UINT64) { MEMCPYRET(data._UInt64); } else if (type == TYPE_FLOAT) { MEMCPYRET(data._Float); } else if (type == TYPE_DOUBLE) { MEMCPYRET(data._Double); } else if (type == TYPE_STRING) { size_t len = data._String->size(); memcpy(buffer, data._String->c_str(), len); return len; } else if (type == TYPE_BOOL) { MEMCPYRET(data._Bool); } else if (type == TYPE_NONE) { return 0; } throw std::runtime_error("This is serious: Type not handled in copyToBuffer()!"); }; size_t Variant::getSize() const { if (type == TYPE_CHAR) { return sizeof(data._Char); } else if (type == TYPE_UCHAR) { return sizeof(data._UChar); } else if (type == TYPE_INT16) { return sizeof(data._Int16); } else if (type == TYPE_UINT16) { return sizeof(data._UInt16); } else if (type == TYPE_INT32) { return sizeof(data._Int32); } else if (type == TYPE_UINT32) { return sizeof(data._UInt32); } else if (type == TYPE_INT64) { return sizeof(data._Int64); } else if (type == TYPE_UINT64) { return sizeof(data._UInt64); } else if (type == TYPE_FLOAT) { return sizeof(data._Float); } else if (type == TYPE_DOUBLE) { return sizeof(data._Double); } else if (type == TYPE_STRING) { size_t len = strlen(data._String->c_str()+1); return len; } else if (type == TYPE_BOOL) { return sizeof(data._Bool); } else if (type == TYPE_NONE) { return 0; } throw std::runtime_error("This is serious: Type not handled in getSize()!"); }; } // namespace pxl
16,867
7,959
#include <stdio.h> #include <stdlib.h> #include <iostream> #include "FibHeap_sp.h" using namespace fib_heap; using namespace std; #define NotAVertex -1 #define MaxVertexNum 10 /* maximum number of vertices */ #define INFI 10000 typedef int Vertex; /* vertices are numbered from 0 to MaxVertexNum-1 */ typedef int WeightType; typedef struct GNode *PtrToGNode; struct GNode{ int Nv; int Ne; WeightType G[MaxVertexNum][MaxVertexNum]; }; typedef PtrToGNode MGraph; typedef struct Vnode *PtrToVNode; struct Vnode{ Vertex V; PtrToVNode Next; }; MGraph ReadG(); void ShortestDist(MGraph Graph, int dist[], Vertex S); MGraph ReadG() { int numOfVertex, numOfEdge; cin >> numOfVertex; cin >> numOfEdge; MGraph MG = (MGraph)malloc(sizeof(struct GNode)); MG->Nv = numOfVertex; MG->Ne = numOfEdge; int i, j; /* initial the matrix*/ for (i = 0; i < numOfVertex; i++) // traversal rows { for (j = 0; j < numOfVertex; j++) // traversal cols { if (i == j) MG->G[i][j] = 0; else MG->G[i][j] = INFI; } } int tempVertex1, tempVertex2, tempDist; for (i = 0; i < numOfEdge; i++) // store the info according to input { cin >> tempVertex1; cin >> tempVertex2; cin >> tempDist; MG->G[tempVertex1][tempVertex2] = tempDist; } return MG; } void ShortestDist(MGraph Graph, int dist[], Vertex S) { int i; Vertex V, W; FibHeap H; // create the Fibonacci heap FibHeapNode** nodes = new FibHeapNode*[Graph->Nv]; dist[S] = 0; for (i = 0; i < Graph->Nv; i++) // insert all information about distance into the heap { if (i != S) dist[i] = INFI; nodes[i] = H.insert(dist[i]); nodes[i]->V = i; } for (;;) { FibHeapNode* min = H._extract_min_node(); if (min == nullptr || min->key == INFI ) break; V = min->V; for (W = 0; W < Graph->Nv; W++) { if ( W != V && Graph->G[V][W] != INFI ) { if (dist[V] + Graph->G[V][W] < dist[W]) { dist[W] = dist[V] + Graph->G[V][W]; H.decrease_key(nodes[W], dist[W]); } } } } for (W = 0; W < Graph->Nv; W++) if ( dist[W] == INFI ) dist[W] = -1; } int main() { int dist[MaxVertexNum]; Vertex S, V; cout << "Please input the information of the DAG, firstly the number of vertex and edges" << " then the information of edges, finally the start point" << endl; MGraph G = ReadG(); cin >> S; ShortestDist(G, dist, S); for (V = 0; V<G->Nv; V++) printf("%d ", dist[V]); printf("\n"); return 0; }
2,449
1,102
/*! ****************************************************************************** * * \file * * \brief Header file containing SIMT distrubuted register abstractions for * CUDA * ****************************************************************************** */ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2016-22, Lawrence Livermore National Security, LLC // and RAJA project contributors. See the RAJA/LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #include "RAJA/config.hpp" #include "RAJA/util/macros.hpp" #include "RAJA/pattern/tensor/internal/RegisterBase.hpp" #include "RAJA/util/macros.hpp" #include "RAJA/util/Operators.hpp" #ifdef RAJA_ENABLE_CUDA #include "RAJA/policy/cuda/reduce.hpp" #ifndef RAJA_policy_tensor_arch_cuda_cuda_warp_register_HPP #define RAJA_policy_tensor_arch_cuda_cuda_warp_register_HPP namespace RAJA { namespace expt { template<typename ELEMENT_TYPE> class Register<ELEMENT_TYPE, cuda_warp_register> : public internal::expt::RegisterBase<Register<ELEMENT_TYPE, cuda_warp_register>> { public: using base_type = internal::expt::RegisterBase<Register<ELEMENT_TYPE, cuda_warp_register>>; using register_policy = cuda_warp_register; using self_type = Register<ELEMENT_TYPE, cuda_warp_register>; using element_type = ELEMENT_TYPE; using register_type = ELEMENT_TYPE; using int_vector_type = Register<int64_t, cuda_warp_register>; private: element_type m_value; public: static constexpr int s_num_elem = 32; /*! * @brief Default constructor, zeros register contents */ RAJA_INLINE RAJA_DEVICE constexpr Register() : base_type(), m_value(0) { } /*! * @brief Copy constructor from raw value */ RAJA_INLINE RAJA_DEVICE constexpr Register(element_type c) : base_type(), m_value(c) {} /*! * @brief Copy constructor */ RAJA_INLINE RAJA_DEVICE constexpr Register(self_type const &c) : base_type(), m_value(c.m_value) {} /*! * @brief Copy assignment operator */ RAJA_INLINE RAJA_DEVICE self_type &operator=(self_type const &c){ m_value = c.m_value; return *this; } RAJA_INLINE RAJA_DEVICE self_type &operator=(element_type c){ m_value = c; return *this; } /*! * @brief Gets our warp lane */ RAJA_INLINE RAJA_DEVICE constexpr static int get_lane() { return threadIdx.x; } RAJA_DEVICE RAJA_INLINE constexpr element_type const &get_raw_value() const { return m_value; } RAJA_DEVICE RAJA_INLINE element_type &get_raw_value() { return m_value; } RAJA_DEVICE RAJA_INLINE static constexpr bool is_root() { return get_lane() == 0; } /*! * @brief Load a full register from a stride-one memory location * */ RAJA_INLINE RAJA_DEVICE self_type &load_packed(element_type const *ptr){ auto lane = get_lane(); m_value = ptr[lane]; return *this; } /*! * @brief Partially load a register from a stride-one memory location given * a run-time number of elements. * */ RAJA_INLINE RAJA_DEVICE self_type &load_packed_n(element_type const *ptr, int N){ auto lane = get_lane(); if(lane < N){ m_value = ptr[lane]; } else{ m_value = element_type(0); } return *this; } /*! * @brief Gather a full register from a strided memory location * */ RAJA_INLINE RAJA_DEVICE self_type &load_strided(element_type const *ptr, int stride){ auto lane = get_lane(); m_value = ptr[stride*lane]; return *this; } /*! * @brief Partially load a register from a stride-one memory location given * a run-time number of elements. * */ RAJA_INLINE RAJA_DEVICE self_type &load_strided_n(element_type const *ptr, int stride, int N){ auto lane = get_lane(); if(lane < N){ m_value = ptr[stride*lane]; } else{ m_value = element_type(0); } return *this; } /*! * @brief Generic gather operation for full vector. * * Must provide another register containing offsets of all values * to be loaded relative to supplied pointer. * * Offsets are element-wise, not byte-wise. * */ RAJA_INLINE RAJA_DEVICE self_type &gather(element_type const *ptr, int_vector_type offsets){ m_value = ptr[offsets.get_raw_value()]; return *this; } /*! * @brief Generic gather operation for n-length subvector. * * Must provide another register containing offsets of all values * to be loaded relative to supplied pointer. * * Offsets are element-wise, not byte-wise. * */ RAJA_INLINE RAJA_DEVICE self_type &gather_n(element_type const *ptr, int_vector_type offsets, camp::idx_t N){ if(get_lane() < N){ m_value = ptr[offsets.get_raw_value()]; } else{ m_value = element_type(0); } return *this; } /*! * @brief Generic segmented load operation used for loading sub-matrices * from larger arrays. * * The default operation combines the s_segmented_offsets and gather * operations. * * */ RAJA_DEVICE RAJA_INLINE self_type &segmented_load(element_type const *ptr, camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer){ auto lane = get_lane(); // compute segment and segment_size auto seg = lane >> segbits; auto i = lane & ((1<<segbits)-1); m_value = ptr[seg*stride_outer + i*stride_inner]; return *this; } /*! * @brief Generic segmented load operation used for loading sub-matrices * from larger arrays where we load partial segments. * * * */ RAJA_DEVICE RAJA_INLINE self_type &segmented_load_nm(element_type const *ptr, camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer, camp::idx_t num_inner, camp::idx_t num_outer) { auto lane = get_lane(); // compute segment and segment_size auto seg = lane >> segbits; auto i = lane & ((1<<segbits)-1); if(seg >= num_outer || i >= num_inner){ m_value = element_type(0); } else{ m_value = ptr[seg*stride_outer + i*stride_inner]; } return *this; } /*! * @brief Store entire register to consecutive memory locations * */ RAJA_INLINE RAJA_DEVICE self_type const &store_packed(element_type *ptr) const{ auto lane = get_lane(); ptr[lane] = m_value; return *this; } /*! * @brief Store entire register to consecutive memory locations * */ RAJA_INLINE RAJA_DEVICE self_type const &store_packed_n(element_type *ptr, int N) const{ auto lane = get_lane(); if(lane < N){ ptr[lane] = m_value; } return *this; } /*! * @brief Store entire register to consecutive memory locations * */ RAJA_INLINE RAJA_DEVICE self_type const &store_strided(element_type *ptr, int stride) const{ auto lane = get_lane(); ptr[lane*stride] = m_value; return *this; } /*! * @brief Store partial register to consecutive memory locations * */ RAJA_INLINE RAJA_DEVICE self_type const &store_strided_n(element_type *ptr, int stride, int N) const{ auto lane = get_lane(); if(lane < N){ ptr[lane*stride] = m_value; } return *this; } /*! * @brief Generic scatter operation for full vector. * * Must provide another register containing offsets of all values * to be stored relative to supplied pointer. * * Offsets are element-wise, not byte-wise. * */ template<typename T2> RAJA_DEVICE RAJA_INLINE self_type const &scatter(element_type *ptr, T2 const &offsets) const { ptr[offsets.get_raw_value()] = m_value; return *this; } /*! * @brief Generic scatter operation for n-length subvector. * * Must provide another register containing offsets of all values * to be stored relative to supplied pointer. * * Offsets are element-wise, not byte-wise. * */ template<typename T2> RAJA_DEVICE RAJA_INLINE self_type const &scatter_n(element_type *ptr, T2 const &offsets, camp::idx_t N) const { if(get_lane() < N){ ptr[offsets.get_raw_value()] = m_value; } return *this; } /*! * @brief Generic segmented store operation used for storing sub-matrices * to larger arrays. * */ RAJA_DEVICE RAJA_INLINE self_type const &segmented_store(element_type *ptr, camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer) const { auto lane = get_lane(); // compute segment and segment_size auto seg = lane >> segbits; auto i = lane & ((1<<segbits)-1); ptr[seg*stride_outer + i*stride_inner] = m_value; return *this; } /*! * @brief Generic segmented store operation used for storing sub-matrices * to larger arrays where we store partial segments. * */ RAJA_DEVICE RAJA_INLINE self_type const &segmented_store_nm(element_type *ptr, camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer, camp::idx_t num_inner, camp::idx_t num_outer) const { auto lane = get_lane(); // compute segment and segment_size auto seg = lane >> segbits; auto i = lane & ((1<<segbits)-1); if(seg >= num_outer || i >= num_inner){ // nop } else{ ptr[seg*stride_outer + i*stride_inner] = m_value; } return *this; } /*! * @brief Get scalar value from vector register * @param i Offset of scalar to get * @return Returns scalar value at i */ constexpr RAJA_INLINE RAJA_DEVICE element_type get(int i) const { return __shfl_sync(0xffffffff, m_value, i, 32); } /*! * @brief Set scalar value in vector register * @param i Offset of scalar to set * @param value Value of scalar to set */ RAJA_INLINE RAJA_DEVICE self_type &set(element_type value, int i) { auto lane = get_lane(); if(lane == i){ m_value = value; } return *this; } RAJA_DEVICE RAJA_INLINE self_type &broadcast(element_type const &a){ m_value = a; return *this; } /*! * @brief Extracts a scalar value and broadcasts to a new register */ RAJA_DEVICE RAJA_INLINE self_type get_and_broadcast(int i) const { self_type x; x.m_value = __shfl_sync(0xffffffff, m_value, i, 32); return x; } RAJA_DEVICE RAJA_INLINE self_type &copy(self_type const &src){ m_value = src.m_value; return *this; } RAJA_DEVICE RAJA_INLINE self_type add(self_type const &b) const { return self_type(m_value + b.m_value); } RAJA_DEVICE RAJA_INLINE self_type subtract(self_type const &b) const { return self_type(m_value - b.m_value); } RAJA_DEVICE RAJA_INLINE self_type multiply(self_type const &b) const { return self_type(m_value * b.m_value); } RAJA_DEVICE RAJA_INLINE self_type divide(self_type const &b) const { return self_type(m_value / b.m_value); } RAJA_DEVICE RAJA_INLINE self_type divide_n(self_type const &b, int N) const { return get_lane() < N ? self_type(m_value / b.m_value) : self_type(element_type(0)); } /** * floats and doubles use the CUDA instrinsic FMA */ template<typename RETURN_TYPE = self_type> RAJA_DEVICE RAJA_INLINE typename std::enable_if<!std::numeric_limits<element_type>::is_integer, RETURN_TYPE>::type multiply_add(self_type const &b, self_type const &c) const { return self_type(fma(m_value, b.m_value, c.m_value)); } /** * int32 and int64 don't have a CUDA intrinsic FMA, do unfused ops */ template<typename RETURN_TYPE = self_type> RAJA_DEVICE RAJA_INLINE typename std::enable_if<std::numeric_limits<element_type>::is_integer, RETURN_TYPE>::type multiply_add(self_type const &b, self_type const &c) const { return self_type(m_value * b.m_value + c.m_value); } /** * floats and doubles use the CUDA instrinsic FMS */ template<typename RETURN_TYPE = self_type> RAJA_DEVICE RAJA_INLINE typename std::enable_if<!std::numeric_limits<element_type>::is_integer, RETURN_TYPE>::type multiply_subtract(self_type const &b, self_type const &c) const { return self_type(fma(m_value, b.m_value, -c.m_value)); } /** * int32 and int64 don't have a CUDA intrinsic FMS, do unfused ops */ template<typename RETURN_TYPE = self_type> RAJA_DEVICE RAJA_INLINE typename std::enable_if<std::numeric_limits<element_type>::is_integer, RETURN_TYPE>::type multiply_subtract(self_type const &b, self_type const &c) const { return self_type(m_value * b.m_value - c.m_value); } /*! * @brief Sum the elements of this vector * @return Sum of the values of the vectors scalar elements */ RAJA_INLINE RAJA_DEVICE element_type sum() const { // Allreduce sum using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::plus>; return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value); } /*! * @brief Returns the largest element * @return The largest scalar element in the register */ RAJA_INLINE RAJA_DEVICE element_type max() const { // Allreduce maximum using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::maximum>; return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value); } /*! * @brief Returns the largest element * @return The largest scalar element in the register */ RAJA_INLINE RAJA_DEVICE element_type max_n(int N) const { // Allreduce maximum using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::maximum>; auto ident = RAJA::operators::limits<element_type>::min(); auto lane = get_lane(); auto value = lane < N ? m_value : ident; return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(value); } /*! * @brief Returns element-wise largest values * @return Vector of the element-wise max values */ RAJA_INLINE RAJA_DEVICE self_type vmax(self_type a) const { return self_type{RAJA::max<element_type>(m_value, a.m_value)}; } /*! * @brief Returns the largest element * @return The largest scalar element in the register */ RAJA_INLINE RAJA_DEVICE element_type min() const { // Allreduce minimum using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::minimum>; return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value); } /*! * @brief Returns the largest element from first N lanes * @return The largest scalar element in the register */ RAJA_INLINE RAJA_DEVICE element_type min_n(int N) const { // Allreduce minimum using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::minimum>; auto ident = RAJA::operators::limits<element_type>::max(); auto lane = get_lane(); auto value = lane < N ? m_value : ident; return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(value); } /*! * @brief Returns element-wise largest values * @return Vector of the element-wise max values */ RAJA_INLINE RAJA_DEVICE self_type vmin(self_type a) const { return self_type{RAJA::min<element_type>(m_value, a.m_value)}; } /*! * Provides gather/scatter indices for segmented loads and stores * * THe number of segment bits (segbits) is specified, as well as the * stride between elements in a segment (stride_inner), * and the stride between segments (stride_outer) */ RAJA_INLINE RAJA_DEVICE static int_vector_type s_segmented_offsets(camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer) { int_vector_type result; auto lane = get_lane(); // compute segment and segment_size auto seg = lane >> segbits; auto i = lane & ((1<<segbits)-1); result.get_raw_value() = seg*stride_outer + i*stride_inner; return result; } /*! * Sum elements within each segment, with segment size defined by segbits. * Stores each segments sum consecutively, but shifed to the * corresponding output_segment slot. * * Note: segment size is 1<<segbits elements * number of segments is s_num_elem>>seg_bits * * * * * Example: * * Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7 * * segbits=0 is equivalent to the input vector, since there are 8 * outputs, there is only 1 output segment * * Result= x0, x1, x2, x3, x4, x5, x6, x7 * * segbits=1 sums neighboring pairs of values. There are 4 output, * so there are possible output segments. * * output_segment=0: * Result= x0+x1, x2+x3, x4+x5, x6+x7, 0, 0, 0, 0 * * output_segment=1: * Result= 0, 0, 0, 0, x0+x1, x2+x3, x4+x5, x6+x7 * * and so on up to segbits=3, which is a full sum of x0..x7, and the * output_segment denotes the vector position of the sum * */ RAJA_INLINE RAJA_DEVICE self_type segmented_sum_inner(camp::idx_t segbits, camp::idx_t output_segment) const { // First: tree reduce values within each segment element_type x = m_value; RAJA_UNROLL for(int delta = 1;delta < 1<<segbits;delta = delta<<1){ // tree shuffle element_type y = __shfl_sync(0xffffffff, x, get_lane()+delta); // reduce x += y; } // Second: send result to output segment lanes self_type result; result.get_raw_value() = __shfl_sync(0xffffffff, x, get_lane()<<segbits); // Third: mask off everything but output_segment // this is because all output segments are valid at this point // (5-segbits), the 5 is since the warp-width is 32 == 1<<5 int our_output_segment = get_lane()>>(5-segbits); bool in_output_segment = our_output_segment == output_segment; if(!in_output_segment){ result.get_raw_value() = 0; } return result; } /*! * Sum across segments, with segment size defined by segbits * * Note: segment size is 1<<segbits elements * number of segments is s_num_elem>>seg_bits * * * * * Example: * * Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7 * * segbits=0 is equivalent to the input vector, since there are 8 * outputs, there is only 1 output segment * * Result= x0, x1, x2, x3, x4, x5, x6, x7 * * segbits=1 sums strided pairs of values. There are 4 output, * so there are possible output segments. * * output_segment=0: * Result= x0+x4, x1+x5, x2+x6, x3+x7, 0, 0, 0, 0 * * output_segment=1: * Result= 0, 0, 0, 0, x0+x4, x1+x5, x2+x6, x3+x7 * * and so on up to segbits=3, which is a full sum of x0..x7, and the * output_segment denotes the vector position of the sum * */ RAJA_INLINE RAJA_DEVICE self_type segmented_sum_outer(camp::idx_t segbits, camp::idx_t output_segment) const { // First: tree reduce values within each segment element_type x = m_value; RAJA_UNROLL for(int i = 0;i < 5-segbits; ++ i){ // tree shuffle int delta = s_num_elem >> (i+1); element_type y = __shfl_sync(0xffffffff, x, get_lane()+delta); // reduce x += y; } // Second: send result to output segment lanes self_type result; int get_from = get_lane()&( (1<<segbits)-1); result.get_raw_value() = __shfl_sync(0xffffffff, x, get_from); int mask = (get_lane()>>segbits) == output_segment; // Third: mask off everything but output_segment if(!mask){ result.get_raw_value() = 0; } return result; } RAJA_INLINE RAJA_DEVICE self_type segmented_divide_nm(self_type den, camp::idx_t segbits, camp::idx_t num_inner, camp::idx_t num_outer) const { self_type result; auto lane = get_lane(); // compute segment and segment_size auto seg = lane >> segbits; auto i = lane & ((1<<segbits)-1); if(seg >= num_outer || i >= num_inner){ // nop } else{ result.get_raw_value() = m_value / den.get_raw_value(); } return result; } /*! * Segmented broadcast copies a segment to all output segments of a vector * * Note: segment size is 1<<segbits elements * number of segments is s_num_elem>>seg_bits * * * Example: * * Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7 * * segbits=0 means the input segment size is 1, so this selects the * value at x[input_segmnet] and broadcasts it to the rest of the * vector * * input segments allowed are from 0 to 7, inclusive * * input_segment=0 * Result= x0, x0, x0, x0, x0, x0, x0, x0 * * input_segment=5 * Result= x5, x5, x5, x5, x5, x5, x5, x5 * * segbits=1 means that the input segments are each pair of x values: * * input segments allowed are from 0 to 3, inclusive * * output_segment=0: * Result= x0, x1, x0, x1, x0, x1, x0, x1 * * output_segment=1: * Result= x2, x3, x2, x3, x2, x3, x2, x3 * * output_segment=3: * Result= x6, x7, x6, x7, x6, x7, x6, x7 * * and so on up to segbits=2, the input segments are 4 wide: * * input segments allowed are from 0 or 1 * * output_segment=0: * Result= x0, x1, x2, x3, x0, x1, x2, x3 * * output_segment=1: * Result= x4, x5, x6, x7, x4, x5, x6, x7 * */ RAJA_INLINE RAJA_DEVICE self_type segmented_broadcast_inner(camp::idx_t segbits, camp::idx_t input_segment) const { self_type result; camp::idx_t mask = (1<<segbits)-1; camp::idx_t offset = input_segment << segbits; camp::idx_t i = (get_lane()&mask) + offset; result.get_raw_value() = __shfl_sync(0xffffffff, m_value, i); return result; } /*! * Segmented broadcast spreads a segment to all output segments of a vector * * Note: segment size is 1<<segbits elements * number of segments is s_num_elem>>seg_bits * * * Example: * * Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7 * * segbits=0 means the input segment size is 1, so this selects the * value at x[input_segmnet] and broadcasts it to the rest of the * vector * * input segments allowed are from 0 to 7, inclusive * * input_segment=0 * Result= x0, x0, x0, x0, x0, x0, x0, x0 * * input_segment=5 * Result= x5, x5, x5, x5, x5, x5, x5, x5 * * segbits=1 means that the input segments are each pair of x values: * * input segments allowed are from 0 to 3, inclusive * * output_segment=0: * Result= x0, x0, x0, x0, x1, x1, x1, x1 * * output_segment=1: * Result= x2, x2, x2, x2, x3, x3, x3, x3 * * output_segment=3: * Result= x6, x6, x6, x6, x7, x7, x7, x7 */ RAJA_INLINE RAJA_DEVICE self_type segmented_broadcast_outer(camp::idx_t segbits, camp::idx_t input_segment) const { self_type result; camp::idx_t offset = input_segment * (self_type::s_num_elem >> segbits); camp::idx_t i = (get_lane() >> segbits) + offset; result.get_raw_value() = __shfl_sync(0xffffffff, m_value, i); return result; } }; } // namespace expt } // namespace RAJA #endif // Guard #endif // CUDA
26,711
8,973
// SPDX-License-Identifier: BSD-3-Clause /* Copyright 2018-2020, Intel Corporation */ /** * @file * Array container with std::array compatible interface. */ #ifndef LIBPMEMOBJ_CPP_ARRAY_HPP #define LIBPMEMOBJ_CPP_ARRAY_HPP #include <algorithm> #include <functional> #include <libpmemobj++/container/detail/contiguous_iterator.hpp> #include <libpmemobj++/detail/common.hpp> #include <libpmemobj++/persistent_ptr.hpp> #include <libpmemobj++/pext.hpp> #include <libpmemobj++/slice.hpp> #include <libpmemobj++/transaction.hpp> #include <libpmemobj++/utils.hpp> #include <libpmemobj/base.h> namespace pmem { namespace obj { /** * pmem::obj::array - persistent container with std::array compatible interface. * * pmem::obj::array can only be stored on pmem. Creating array on * stack will result with "pool_error" exception. * * All methods which allow write access to specific element will add it to an * active transaction. * * All methods which return non-const pointer to raw data add entire array * to a transaction. * * When a non-const iterator is returned it adds part of the array * to a transaction while traversing. */ template <typename T, std::size_t N> struct array { template <typename Y, std::size_t M> struct standard_array_traits { using type = Y[N]; }; /* zero-sized array support */ template <typename Y> struct standard_array_traits<Y, 0> { struct _alignment_struct { Y _data[1]; }; struct alignas(_alignment_struct) type { char _data[sizeof(_alignment_struct)]; }; }; /* Member types */ using value_type = T; using pointer = value_type *; using const_pointer = const value_type *; using reference = value_type &; using const_reference = const value_type &; using iterator = pmem::detail::basic_contiguous_iterator<T>; using const_iterator = const_pointer; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; using range_snapshotting_iterator = pmem::detail::range_snapshotting_iterator<T>; /* Underlying array */ typename standard_array_traits<T, N>::type _data; /** * Defaulted constructor. */ array() = default; /** * Defaulted copy constructor. */ array(const array &) = default; /** * Defaulted move constructor. * * Performs member-wise move but do NOT add moved-from array to the * transaction. */ array(array &&) = default; /** * Copy assignment operator - perform assignment from other * pmem::obj::array. * * This function creates a transaction internally. * * @throw transaction_error when adding the object to the * transaction failed. * @throw pmem::pool_error if an object is not in persistent memory. */ array & operator=(const array &other) { /* * _get_pool should be called before self assignment check to * maintain the same behaviour for all arguments. */ auto pop = _get_pool(); if (this == &other) return *this; transaction::run(pop, [&] { detail::conditional_add_to_tx( this, 1, POBJ_XADD_ASSUME_INITIALIZED); std::copy(other.cbegin(), other.cend(), _get_data()); }); return *this; } /** * Move assignment operator - perform move assignment from other * pmem::obj::array. * * This function creates a transaction internally. * * @throw transaction_error when adding the object to the * transaction failed. * @throw pmem::pool_error if an object is not in persistent memory. */ array & operator=(array &&other) { /* * _get_pool should be called before self assignment check to * maintain the same behaviour for all arguments. */ auto pop = _get_pool(); if (this == &other) return *this; transaction::run(pop, [&] { detail::conditional_add_to_tx( this, 1, POBJ_XADD_ASSUME_INITIALIZED); detail::conditional_add_to_tx( &other, 1, POBJ_XADD_ASSUME_INITIALIZED); std::move(other._get_data(), other._get_data() + size(), _get_data()); }); return *this; } /** * Access element at specific index and add it to a transaction. * * @throw std::out_of_range if index is out of bound. * @throw transaction_error when adding the object to the * transaction failed. */ reference at(size_type n) { if (n >= N) throw std::out_of_range("array::at"); detail::conditional_add_to_tx(_get_data() + n, 1, POBJ_XADD_ASSUME_INITIALIZED); return _get_data()[n]; } /** * Access element at specific index. * * @throw std::out_of_range if index is out of bound. */ const_reference at(size_type n) const { if (n >= N) throw std::out_of_range("array::at"); return _get_data()[n]; } /** * Access element at specific index. * * @throw std::out_of_range if index is out of bound. */ const_reference const_at(size_type n) const { if (n >= N) throw std::out_of_range("array::const_at"); return _get_data()[n]; } /** * Access element at specific index and add it to a transaction. * No bounds checking is performed. * * @throw transaction_error when adding the object to the * transaction failed. */ reference operator[](size_type n) { detail::conditional_add_to_tx(_get_data() + n, 1, POBJ_XADD_ASSUME_INITIALIZED); return _get_data()[n]; } /** * Access element at specific index. * No bounds checking is performed. */ const_reference operator[](size_type n) const { return _get_data()[n]; } /** * Returns raw pointer to the underlying data * and adds entire array to a transaction. * * @throw transaction_error when adding the object to the * transaction failed. */ T * data() { detail::conditional_add_to_tx(this, 1, POBJ_XADD_ASSUME_INITIALIZED); return _get_data(); } /** * Returns const raw pointer to the underlying data. */ const T * data() const noexcept { return _get_data(); } /** * Returns const raw pointer to the underlying data. */ const T * cdata() const noexcept { return _get_data(); } /** * Returns an iterator to the beginning. * * @throw transaction_error when adding the object to the * transaction failed. */ iterator begin() { return iterator(_get_data()); } /** * Returns an iterator to the end. * * @throw transaction_error when adding the object to the * transaction failed. */ iterator end() { return iterator(_get_data() + size()); } /** * Returns const iterator to the beginning. */ const_iterator begin() const noexcept { return const_iterator(_get_data()); } /** * Returns const iterator to the beginning. */ const_iterator cbegin() const noexcept { return const_iterator(_get_data()); } /** * Returns a const iterator to the end. */ const_iterator end() const noexcept { return const_iterator(_get_data() + size()); } /** * Returns a const iterator to the end. */ const_iterator cend() const noexcept { return const_iterator(_get_data() + size()); } /** * Returns a reverse iterator to the beginning. * * @throw transaction_error when adding the object to the * transaction failed. */ reverse_iterator rbegin() { return reverse_iterator(iterator(_get_data() + size())); } /** * Returns a reverse iterator to the end. * * @throw transaction_error when adding the object to the * transaction failed. */ reverse_iterator rend() { return reverse_iterator(iterator(_get_data())); } /** * Returns a const reverse iterator to the beginning. */ const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(cend()); } /** * Returns a const reverse iterator to the beginning. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /** * Returns a const reverse iterator to the end. */ const_reverse_iterator rend() const noexcept { return const_reverse_iterator(cbegin()); } /** * Returns a const reverse iterator to the beginning. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } /** * Access the first element and add this element to a transaction. * * @throw transaction_error when adding the object to the * transaction failed. */ reference front() { detail::conditional_add_to_tx(_get_data(), 1, POBJ_XADD_ASSUME_INITIALIZED); return _get_data()[0]; } /** * Access the last element and add this element to a transaction. * * @throw transaction_error when adding the object to the * transaction failed. */ reference back() { detail::conditional_add_to_tx(&_get_data()[size() - 1], 1, POBJ_XADD_ASSUME_INITIALIZED); return _get_data()[size() - 1]; } /** * Access the first element. */ const_reference front() const { return _get_data()[0]; } /** * Access the first element. */ const_reference cfront() const { return _get_data()[0]; } /** * Access the last element. */ const_reference back() const { return _get_data()[size() - 1]; } /** * Access the last element. */ const_reference cback() const { return _get_data()[size() - 1]; } /** * Returns slice and snapshots requested range. * * @param[in] start start index of requested range. * @param[in] n number of elements in range. * * @return slice from start to start + n. * * @throw std::out_of_range if any element of the range would be * outside of the array. */ slice<pointer> range(size_type start, size_type n) { if (start + n > N) throw std::out_of_range("array::range"); detail::conditional_add_to_tx(_get_data() + start, n, POBJ_XADD_ASSUME_INITIALIZED); return {_get_data() + start, _get_data() + start + n}; } /** * Returns slice. * * @param[in] start start index of requested range. * @param[in] n number of elements in range. * @param[in] snapshot_size number of elements which should be * snapshotted in a bulk while traversing this slice. * If provided value is larger or equal to n, entire range is * added to a transaction. If value is equal to 0 no snapshotting * happens. * * @return slice from start to start + n. * * @throw std::out_of_range if any element of the range would be * outside of the array. */ slice<range_snapshotting_iterator> range(size_type start, size_type n, size_type snapshot_size) { if (start + n > N) throw std::out_of_range("array::range"); if (snapshot_size > n) snapshot_size = n; return {range_snapshotting_iterator(_get_data() + start, _get_data() + start, n, snapshot_size), range_snapshotting_iterator(_get_data() + start + n, _get_data() + start, n, snapshot_size)}; } /** * Returns const slice. * * @param[in] start start index of requested range. * @param[in] n number of elements in range. * * @return slice from start to start + n. * * @throw std::out_of_range if any element of the range would be * outside of the array. */ slice<const_iterator> range(size_type start, size_type n) const { if (start + n > N) throw std::out_of_range("array::range"); return {const_iterator(_get_data() + start), const_iterator(_get_data() + start + n)}; } /** * Returns const slice. * * @param[in] start start index of requested range. * @param[in] n number of elements in range. * * @return slice from start to start + n. * * @throw std::out_of_range if any element of the range would be * outside of the array. */ slice<const_iterator> crange(size_type start, size_type n) const { if (start + n > N) throw std::out_of_range("array::crange"); return {const_iterator(_get_data() + start), const_iterator(_get_data() + start + n)}; } /** * Returns size of the array. */ constexpr size_type size() const noexcept { return N; } /** * Returns the maximum size of the array. */ constexpr size_type max_size() const noexcept { return N; } /** * Checks whether array is empty. */ constexpr bool empty() const noexcept { return size() == 0; } /** * Fills array with specified value inside internal transaction. * * @throw transaction_error when adding the object to the * transaction failed. * @throw pmem::pool_error if an object is not in persistent memory. */ void fill(const_reference value) { auto pop = _get_pool(); transaction::run(pop, [&] { detail::conditional_add_to_tx( this, 1, POBJ_XADD_ASSUME_INITIALIZED); std::fill(_get_data(), _get_data() + size(), value); }); } /** * Swaps content with other array's content inside internal transaction. * * @throw transaction_error when adding the object to the * transaction failed. * @throw pmem::pool_error if an object is not in persistent memory. */ template <std::size_t Size = N> typename std::enable_if<Size != 0>::type swap(array &other) { /* * _get_pool should be called before self assignment check to * maintain the same behaviour for all arguments. */ auto pop = _get_pool(); if (this == &other) return; transaction::run(pop, [&] { detail::conditional_add_to_tx( this, 1, POBJ_XADD_ASSUME_INITIALIZED); detail::conditional_add_to_tx( &other, 1, POBJ_XADD_ASSUME_INITIALIZED); std::swap_ranges(_get_data(), _get_data() + size(), other._get_data()); }); } /** * Swap for zero-sized array. */ template <std::size_t Size = N> typename std::enable_if<Size == 0>::type swap(array &other) { static_assert(!std::is_const<T>::value, "cannot swap zero-sized array of type 'const T'"); } private: /** * Support for non-zero sized array. */ template <std::size_t Size = N> typename std::enable_if<Size != 0, T *>::type _get_data() { return this->_data; } /** * Support for non-zero sized array. */ template <std::size_t Size = N> typename std::enable_if<Size != 0, const T *>::type _get_data() const { return this->_data; } /** * Support for zero sized array. * Return value is a unique address (address of the array itself); */ template <std::size_t Size = N> typename std::enable_if<Size == 0, T *>::type _get_data() { return reinterpret_cast<T *>(&this->_data); } /** * Support for zero sized array. */ template <std::size_t Size = N> typename std::enable_if<Size == 0, const T *>::type _get_data() const { return reinterpret_cast<const T *>(&this->_data); } /** * Check whether object is on pmem and return pool_base instance. * * @throw pmem::pool_error if an object is not in persistent memory. */ pool_base _get_pool() const { return pmem::obj::pool_by_vptr(this); } }; /** * Non-member equal operator. */ template <typename T, std::size_t N> inline bool operator==(const array<T, N> &lhs, const array<T, N> &rhs) { return std::equal(lhs.cbegin(), lhs.cend(), rhs.cbegin()); } /** * Non-member not-equal operator. */ template <typename T, std::size_t N> inline bool operator!=(const array<T, N> &lhs, const array<T, N> &rhs) { return !(lhs == rhs); } /** * Non-member less than operator. */ template <typename T, std::size_t N> inline bool operator<(const array<T, N> &lhs, const array<T, N> &rhs) { return std::lexicographical_compare(lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()); } /** * Non-member greater than operator. */ template <typename T, std::size_t N> inline bool operator>(const array<T, N> &lhs, const array<T, N> &rhs) { return rhs < lhs; } /** * Non-member greater or equal operator. */ template <typename T, std::size_t N> inline bool operator>=(const array<T, N> &lhs, const array<T, N> &rhs) { return !(lhs < rhs); } /** * Non-member less or equal operator. */ template <typename T, std::size_t N> inline bool operator<=(const array<T, N> &lhs, const array<T, N> &rhs) { return !(lhs > rhs); } /** * Non-member cbegin. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::const_iterator cbegin(const pmem::obj::array<T, N> &a) { return a.cbegin(); } /** * Non-member cend. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::const_iterator cend(const pmem::obj::array<T, N> &a) { return a.cend(); } /** * Non-member crbegin. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::const_reverse_iterator crbegin(const pmem::obj::array<T, N> &a) { return a.crbegin(); } /** * Non-member crend. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::const_reverse_iterator crend(const pmem::obj::array<T, N> &a) { return a.crend(); } /** * Non-member begin. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::iterator begin(pmem::obj::array<T, N> &a) { return a.begin(); } /** * Non-member begin. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::const_iterator begin(const pmem::obj::array<T, N> &a) { return a.begin(); } /** * Non-member end. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::iterator end(pmem::obj::array<T, N> &a) { return a.end(); } /** * Non-member end. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::const_iterator end(const pmem::obj::array<T, N> &a) { return a.end(); } /** * Non-member rbegin. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::reverse_iterator rbegin(pmem::obj::array<T, N> &a) { return a.rbegin(); } /** * Non-member rbegin. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::const_reverse_iterator rbegin(const pmem::obj::array<T, N> &a) { return a.rbegin(); } /** * Non-member rend. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::reverse_iterator rend(pmem::obj::array<T, N> &a) { return a.rend(); } /** * Non-member rend. */ template <typename T, std::size_t N> typename pmem::obj::array<T, N>::const_reverse_iterator rend(const pmem::obj::array<T, N> &a) { return a.rend(); } /** * Non-member swap function. */ template <typename T, size_t N> inline void swap(pmem::obj::array<T, N> &lhs, pmem::obj::array<T, N> &rhs) { lhs.swap(rhs); } /** * Non-member get function. */ template <size_t I, typename T, size_t N> T & get(pmem::obj::array<T, N> &a) { static_assert(I < N, "Index out of bounds in std::get<> (pmem::obj::array)"); return a.at(I); } /** * Non-member get function. */ template <size_t I, typename T, size_t N> T && get(pmem::obj::array<T, N> &&a) { static_assert(I < N, "Index out of bounds in std::get<> (pmem::obj::array)"); return std::move(a.at(I)); } /** * Non-member get function. */ template <size_t I, typename T, size_t N> const T & get(const pmem::obj::array<T, N> &a) noexcept { static_assert(I < N, "Index out of bounds in std::get<> (pmem::obj::array)"); return a.at(I); } /** * Non-member get function. */ template <size_t I, typename T, size_t N> const T && get(const pmem::obj::array<T, N> &&a) noexcept { static_assert(I < N, "Index out of bounds in std::get<> (pmem::obj::array)"); return std::move(a.at(I)); } } /* namespace obj */ } /* namespace pmem */ #endif /* LIBPMEMOBJ_CPP_ARRAY_HPP */
19,250
7,236
// Two Sum II Input array is sorted #include <leetcode.h> class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> ans; for (int i = 0; i < numbers.size(); i++) { if (i != 0 && numbers[i] == numbers[i-1]) { continue; } if (numbers[i] > target) { break; } if (numbers.end() != find(numbers.begin() + i + 1, numbers.end(), target - numbers[i])) { for (int j = i + 1; j < numbers.size(); j++) { if (numbers[i] + numbers[j] == target) { ans.push_back(i + 1); ans.push_back(j + 1); return ans; } } } } return ans; } };
664
301
#include "dialog.h" #include "ui_dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(clicked(bool))); } void Dialog::displayMessage(const QString& message) { ui->textEdit->append(message); } Dialog::~Dialog() { delete ui; } void Dialog::clicked(bool key) { const QString text = ui->lineEdit->text(); if (text.isEmpty()) { ui->textEdit->append("[waring] send message is null!"); return; } emit sendText(text); displayMessage(tr("Sent message: %1").arg(text)); ui->lineEdit->clear(); }
664
238
#include <sltbench/impl/DoNotOptimize.h> namespace sltbench { namespace priv { void empty_function(volatile const char*) { } } // namespace priv } // namespace sltbench
174
64
#include <gmock/gmock.h> #include <azul/async/StaticThreadPool.hpp> #include <thread> class StaticThreadPoolTestFixture : public testing::Test { }; TEST_F(StaticThreadPoolTestFixture, Execute_EmptyTask_FutureReady) { azul::async::StaticThreadPool threadPool(1); auto result = threadPool.Execute([](){}); result.Wait(); ASSERT_TRUE(result.IsReady()); ASSERT_NO_THROW(result.Get()); } TEST_F(StaticThreadPoolTestFixture, Execute_TaskEnqueued_Success) { azul::async::StaticThreadPool executor(1); auto result = executor.Execute([](){ return 42; }); ASSERT_EQ(42, result.Get()); } TEST_F(StaticThreadPoolTestFixture, Execute_TaskThrowsException_ExceptionForwarded) { azul::async::StaticThreadPool executor(1); auto result = executor.Execute([](){ throw std::invalid_argument(""); }); ASSERT_THROW(result.Get(), std::invalid_argument); } TEST_F(StaticThreadPoolTestFixture, Execute_MultipleTasksAndThreads_Success) { azul::async::StaticThreadPool executor(4); std::vector<azul::async::Future<int>> results; const int tasksToExecute = 100; for (int i = 0; i < tasksToExecute; ++i) { auto result = executor.Execute([i](){ return i; }); results.emplace_back(std::move(result)); } for (int i = 0; i < tasksToExecute; ++i) { ASSERT_EQ(i, results[i].Get()); } } TEST_F(StaticThreadPoolTestFixture, Execute_OneDependency_ExecutedInOrder) { azul::async::StaticThreadPool executor(2); const auto firstTaskId = 1; const auto secondTaskId = 2; std::vector<int> ids; auto action1 = [&]() { std::this_thread::sleep_for(std::chrono::milliseconds(50)); ids.push_back(firstTaskId); }; auto action2 = [&]() { ids.push_back(secondTaskId); }; auto future1 = executor.Execute(action1); auto future2 = executor.Execute(action2, future1); ASSERT_NO_THROW(future1.Get()); ASSERT_NO_THROW(future2.Get()); ASSERT_EQ(firstTaskId, ids[0]); ASSERT_EQ(secondTaskId, ids[1]); } TEST_F(StaticThreadPoolTestFixture, Execute_DependencyThrowingException_FollowingTaskStillExecuted) { azul::async::StaticThreadPool executor(2); auto action1 = [&]() { throw std::runtime_error(""); }; auto action2 = [&]() { }; auto future1 = executor.Execute(action1); auto future2 = executor.Execute(action2, future1); ASSERT_THROW(future1.Get(), std::runtime_error); ASSERT_NO_THROW(future2.Get()); } TEST_F(StaticThreadPoolTestFixture, Execute_MultipleDependencies_ValidExecutionOrder) { std::vector<int> executedTasks; std::mutex mutex; auto log_task_id = [&mutex, &executedTasks](const int id) mutable { std::lock_guard<std::mutex> lock(mutex); executedTasks.push_back(id); }; azul::async::StaticThreadPool executor(2); // dependency graph: // task1 <---- task3 <------ task4 // task2 <-----------------| auto future1 = executor.Execute(std::bind(log_task_id, 1)); auto future2 = executor.Execute(std::bind(log_task_id, 2)); auto future3 = executor.Execute(std::bind(log_task_id, 3), future1); auto future4 = executor.Execute(std::bind(log_task_id, 4), future3, future2); ASSERT_NO_THROW(future4.Get()); ASSERT_EQ(3, executedTasks[2]); ASSERT_EQ(4, executedTasks[3]); } TEST_F(StaticThreadPoolTestFixture, Execute_MultipleTasksNoDependencies_AllThreadsOccupied) { std::vector<std::thread::id> utlizedThreadIds; std::mutex mutex; auto logThreadId = [&mutex, &utlizedThreadIds]() mutable { std::lock_guard<std::mutex> lock(mutex); utlizedThreadIds.push_back(std::this_thread::get_id()); }; azul::async::StaticThreadPool executor(4); auto action = [&logThreadId](){ logThreadId(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); }; std::vector<azul::async::Future<void>> futures; for (std::size_t i = 0; i < executor.ThreadCount(); ++i) { futures.emplace_back(executor.Execute(action)); } std::for_each(futures.begin(), futures.end(), [](auto f){ f.Wait(); }); ASSERT_EQ(utlizedThreadIds.size(), executor.ThreadCount()); }
4,172
1,478
#include <opencv2/opencv.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdlib.h> #include <unistd.h> #include "server.h" char mqtt_cmd[] = "mosquitto_pub -d -h 192.168.0.11 -t /sensor/data -m '{\"serialNumber\":\"SN-0002\",\"intrusion_count_v\": 1}'"; int data_send = 0; cv::Mat MoveDetect(cv::Mat temp, cv::Mat frame) { cv::Mat result = frame.clone(); cv::resize(result, result, cv::Size(640, 480)); //1.将background和frame转为灰度图 cv::Mat gray1, gray2; cv::cvtColor(temp, gray1, CV_BGR2GRAY); cv::cvtColor(frame, gray2, CV_BGR2GRAY); //2.将background和frame做差 cv::Mat diff; cv::absdiff(gray1, gray2, diff); //cv::imshow("diff", diff); //3.对差值图diff_thresh进行阈值化处理 cv::Mat diff_thresh; cv::threshold(diff, diff_thresh, 50, 255, CV_THRESH_BINARY); //cv::imshow("diff_thresh", diff_thresh); //4.腐蚀 cv::Mat kernel_erode = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); cv::Mat kernel_dilate = getStructuringElement(cv::MORPH_RECT, cv::Size(18, 18)); cv::erode(diff_thresh, diff_thresh, kernel_erode); //cv::imshow("erode", diff_thresh); //5.膨胀 cv::dilate(diff_thresh, diff_thresh, kernel_dilate); //cv::imshow("dilate", diff_thresh); //6.查找轮廓并绘制轮廓 std::vector < std::vector < cv::Point > >contours; cv::findContours(diff_thresh, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); cv::drawContours(result, contours, -1, cv::Scalar(0, 0, 255), 2); //在result上绘制轮廓 //7.查找正外接矩形 std::vector < cv::Rect > boundRect(contours.size()); for (unsigned i = 0; i < contours.size(); i++) { boundRect[i] = boundingRect(contours[i]); rectangle(result, boundRect[i], cv::Scalar(0, 255, 0), 2); } if (0 < contours.size()) { std::cout << "mqtt send success!" << std::endl; system(mqtt_cmd); } return result; } int main() { uint16_t port = 5555; /// Set the port http::Server s(port); cv::VideoCapture cap; if (!cap.open(0)) { std::cerr << "Cannot open the camera!" << std::endl; return -1; } std::mutex mtx; s.get("/img", [&] (auto, auto res) { res.headers.push_back("Connection: close"); res.headers.push_back("Max-Age: 0"); res.headers.push_back("Expires: 0"); res.headers.push_back("Cache-Control: no-cache, private"); res.headers.push_back("Pragma: no-cache"); res.headers.push_back("Content-Type: multipart/x-mixed-replace;boundary=--boundary"); if (!res.send_header()) return; std::vector<uchar> buf; cv::Mat frame; cv::Mat temp; cv::Mat result; int i = 0; while(true) { mtx.lock(); cap >> frame; if (frame.empty()) { std::cout << "frame is empty!" << std::endl; break; } if (i == 0) { result = MoveDetect(frame, frame); } else { result = MoveDetect(temp, frame); } mtx.unlock(); temp = frame.clone(); i++; cv::imencode(".jpg", result, buf); std::string image (buf.begin(), buf.end()); if (!res.send_msg("--boundary\r\n" "Content-Type: image/jpeg\r\n" "Content-Length: " + std::to_string(image.size()) + "\r\n\r\n" + image)) return; } cap.release(); cv::destroyAllWindows(); }).get("/", [](auto, auto res) { res >> "<html>" " <body>" " <h1>CAMERA STREAMING</h1>" /// Set the correct ip address " <img src='http://192.168.0.12:5555/img'/>" " </body>" "</html>"; }).listen(); return 0; }
3,949
1,544
//============================================================== // Copyright (C) 2004 Danny Chapman // danny@rowlhouse.freeserve.co.uk //-------------------------------------------------------------- // /// @file characterobject.hpp // //============================================================== #ifndef CHARACTEROBJECT_HPP #define CHARACTEROBJECT_HPP #include "object.hpp" #include "graphics.hpp" #include "jiglib.hpp" /// This is a game-object - i.e. a character that can be rendered. class tCharacterObject : public tObject { public: tCharacterObject(JigLib::tScalar radius, JigLib::tScalar height); ~tCharacterObject(); void SetProperties(JigLib::tScalar elasticity, JigLib::tScalar staticFriction, JigLib::tScalar dynamicFriction); void SetDensity(JigLib::tScalar density, JigLib::tPrimitive::tPrimitiveProperties::tMassDistribution massDistribution = JigLib::tPrimitive::tPrimitiveProperties::SOLID); void SetMass(JigLib::tScalar mass, JigLib::tPrimitive::tPrimitiveProperties::tMassDistribution massDistribution = JigLib::tPrimitive::tPrimitiveProperties::SOLID); // inherited from tObject JigLib::tBody * GetBody() {return &mBody;} // inherited from tObject - interpolated between the physics old and // current positions. void SetRenderPosition(JigLib::tScalar renderFraction); // inherited from tRenderObject void Render(tRenderType renderType); const JigLib::tSphere & GetRenderBoundingSphere() const; const JigLib::tVector3 & GetRenderPosition() const; const JigLib::tMatrix33 & GetRenderOrientation() const; /// If start, then set control to be forward, else stop going forward void ControlFwd(bool start); void ControlBack(bool start); void ControlLeft(bool start); void ControlRight(bool start); void ControlJump(); private: class tCharacterBody : public JigLib::tBody { public: virtual void PostPhysics(JigLib::tScalar dt); JigLib::tScalar mDesiredFwdSpeed; JigLib::tScalar mDesiredLeftSpeed; JigLib::tScalar mJumpSpeed; // used for smoothing JigLib::tScalar mFwdSpeed; JigLib::tScalar mLeftSpeed; JigLib::tScalar mFwdSpeedRate; JigLib::tScalar mLeftSpeedRate; JigLib::tScalar mTimescale; }; void UpdateControl(); tCharacterBody mBody; JigLib::tCollisionSkin mCollisionSkin; JigLib::tVector3 mLookDir; JigLib::tVector3 mRenderPosition; JigLib::tMatrix33 mRenderOrientation; GLuint mDisplayListNum; enum tMoveDir {MOVE_NONE = 1 << 0, MOVE_FWD = 1 << 1, MOVE_BACK = 1 << 2, MOVE_LEFT = 1 << 3, MOVE_RIGHT = 1 << 4}; /// bitmask from tMoveDir unsigned mMoveDir; JigLib::tScalar mBodyAngle; ///< in degrees - rotation around z JigLib::tScalar mLookUpAngle; ///< in Degrees JigLib::tScalar mMoveFwdSpeed; JigLib::tScalar mMoveBackSpeed; JigLib::tScalar mMoveSideSpeed; JigLib::tScalar mJumpSpeed; bool mDoJump; }; #endif
3,065
1,025
/* * (C) Copyright 2021 Met Office UK * * 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. */ #include "oops/util/FloatCompare.h" #include "oops/util/missingValues.h" #include "ufo/profile/ObsProfileAverageData.h" #include "ufo/profile/SlantPathLocations.h" #include "ufo/utils/OperatorUtils.h" // for getOperatorVariables namespace ufo { ObsProfileAverageData::ObsProfileAverageData(const ioda::ObsSpace & odb, const eckit::Configuration & config) : odb_(odb) { // Ensure observations have been grouped into profiles. if (odb_.obs_group_vars().empty()) throw eckit::UserError("Group variables configuration is empty", Here()); // Ensure observations have been sorted by air pressure in descending order. if (odb_.obs_sort_var() != "air_pressure") throw eckit::UserError("Sort variable must be air_pressure", Here()); if (odb_.obs_sort_order() != "descending") throw eckit::UserError("Profiles must be sorted in descending order", Here()); // Check the ObsSpace has been extended. If this is not the case // then it will not be possible to access profiles in the original and // extended sections of the ObsSpace. if (!odb_.has("MetaData", "extended_obs_space")) throw eckit::UserError("The extended obs space has not been produced", Here()); // Check the observed pressure is present. This is necessary in order to // determine the slant path locations. if (!odb_.has("MetaData", "air_pressure")) throw eckit::UserError("air_pressure@MetaData not present", Here()); // Set up configuration options. options_.validateAndDeserialize(config); // Add model air pressure to the list of variables used in this operator. // This GeoVaL is used to determine the slant path locations. modelVerticalCoord_ = options_.modelVerticalCoordinate; requiredVars_ += oops::Variables({modelVerticalCoord_}); // Add any simulated variables to the list of variables used in this operator. getOperatorVariables(config, odb_.obsvariables(), operatorVars_, operatorVarIndices_); requiredVars_ += operatorVars_; // If required, set up vectors for OPS comparison. if (options_.compareWithOPS.value()) this->setUpAuxiliaryReferenceVariables(); } const oops::Variables & ObsProfileAverageData::requiredVars() const { return requiredVars_; } const oops::Variables & ObsProfileAverageData::simulatedVars() const { return operatorVars_; } const std::vector<int> & ObsProfileAverageData::operatorVarIndices() const { return operatorVarIndices_; } void ObsProfileAverageData::cacheGeoVaLs(const GeoVaLs & gv) const { // Only perform the caching once. if (!cachedGeoVaLs_) cachedGeoVaLs_.reset(new GeoVaLs(gv)); } std::vector<std::size_t> ObsProfileAverageData::getSlantPathLocations (const std::vector<std::size_t> & locsOriginal, const std::vector<std::size_t> & locsExtended) const { const std::vector<std::size_t> slant_path_location = ufo::getSlantPathLocations(odb_, *cachedGeoVaLs_, locsOriginal, modelVerticalCoord_, options_.numIntersectionIterations.value() - 1); // If required, compare slant path locations and slant pressure with OPS output. if (options_.compareWithOPS.value()) { // Vector of slanted pressures, used for comparisons with OPS. std::vector<float> slant_pressure; // Number of levels for model pressure. const std::size_t nlevs_p = cachedGeoVaLs_->nlevs(modelVerticalCoord_); // Vector used to store different pressure GeoVaLs. std::vector <float> pressure_gv(nlevs_p); for (std::size_t mlev = 0; mlev < nlevs_p; ++mlev) { cachedGeoVaLs_->getAtLocation(pressure_gv, modelVerticalCoord_, slant_path_location[mlev]); slant_pressure.push_back(pressure_gv[mlev]); } this->compareAuxiliaryReferenceVariables(locsExtended, slant_path_location, slant_pressure); } return slant_path_location; } void ObsProfileAverageData::setUpAuxiliaryReferenceVariables() { if (!(odb_.has("MetOfficeHofX", "slant_path_location") && odb_.has("MetOfficeHofX", "slant_pressure"))) throw eckit::UserError("At least one reference variable is not present", Here()); // Get reference values of the slant path locations and pressures. slant_path_location_ref_.resize(odb_.nlocs()); slant_pressure_ref_.resize(odb_.nlocs()); odb_.get_db("MetOfficeHofX", "slant_path_location", slant_path_location_ref_); odb_.get_db("MetOfficeHofX", "slant_pressure", slant_pressure_ref_); } void ObsProfileAverageData::compareAuxiliaryReferenceVariables (const std::vector<std::size_t> & locsExtended, const std::vector<std::size_t> & slant_path_location, const std::vector<float> & slant_pressure) const { std::vector<int> slant_path_location_ref_profile; std::vector<float> slant_pressure_ref_profile; for (const std::size_t loc : locsExtended) { slant_path_location_ref_profile.push_back(slant_path_location_ref_[loc]); slant_pressure_ref_profile.push_back(slant_pressure_ref_[loc]); } std::stringstream errmsg; for (std::size_t mlev = 0; mlev < locsExtended.size(); ++mlev) { if (slant_path_location[mlev] != slant_path_location_ref_profile[mlev]) { errmsg << "Mismatch for slant_path_location, level = " << mlev << " (this code, OPS): " << slant_path_location[mlev] << ", " << slant_path_location_ref_profile[mlev]; throw eckit::BadValue(errmsg.str(), Here()); } if (!oops::is_close_relative(slant_pressure[mlev], slant_pressure_ref_profile[mlev], 1e-5f)) { errmsg << "Mismatch for slant_pressure, level = " << mlev << " (this code, OPS): " << slant_pressure[mlev] << ", " << slant_pressure_ref_profile[mlev]; throw eckit::BadValue(errmsg.str(), Here()); } } } void ObsProfileAverageData::print(std::ostream & os) const { os << "ObsProfileAverage operator" << std::endl; os << "config = " << options_ << std::endl; } } // namespace ufo
6,593
2,072
#include <CppUTest/TestHarness.h> extern "C" { #include "sharp.h" //#include "mem_map.h" } TEST_GROUP(Proj1Test) { void setup() { } void teardown() { } }; TEST(Proj1Test, sharp_read){ sharp_init(0, 1); // Configuring ADC to use 1 sample // With RE8 = 0, distance must be 0. PORTEbits.RE8 = 0; uint16_t distance = sharp_read(); CHECK_EQUAL(0, distance); // With RE8 = 1, distance must be calculated accordingly to ADC1BUF0. // Equation is d = 127048 / (V + 181) // Some values: d = 600mm V = 31 // d = 450mm V = 101 // d = 300mm V = 244 // d = 100mm V = 1090 PORTEbits.RE8 = 1; uint16_t v; for(v=0; v<1024; v++) { uint32_t distance_calc = 127048/(v+181); ADC1BUF0 = v; uint32_t distance = sharp_read(); CHECK_EQUAL(distance_calc, distance); } }
922
418
/* Copyright (c) 2005-2019, 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 _TESTCWD_HPP_ #define _TESTCWD_HPP_ #include <cxxtest/TestSuite.h> #include <cstdlib> #include <climits> #include "FakePetscSetup.hpp" #include "ChasteBuildRoot.hpp" #include "GetCurrentWorkingDirectory.hpp" #include "BoostFilesystem.hpp" #include "IsNan.hpp" /** * Test for a strange 'feature' of Debian sarge systems, where the * current working directory changes on PETSc initialisation. There * is now code in PetscSetupUtils::CommonSetup() to work around this. */ class TestCwd : public CxxTest::TestSuite { public: void TestShowCwd() { std::string chaste_source_root(ChasteSourceRootDir()); fs::path chaste_source_root_path(chaste_source_root); fs::path cwd(GetCurrentWorkingDirectory()+"/"); TS_ASSERT(fs::equivalent(cwd,chaste_source_root)); } void TestDivideOneByZero() { double one = 1.0; double zero = 0.0; double ans; #ifdef TEST_FOR_FPE // If we are testing for divide-by-zero, then this will throw an exception //TS_ASSERT_THROWS_ANYTHING(ans = one / zero); ans=zero*one;//otherwise compiler would complain ans=ans*zero;//otherwise compiler would complain #else // If we aren't testing for it, then there will be no exception TS_ASSERT_THROWS_NOTHING(ans = one / zero); double negative_infinity = std::numeric_limits<double>::infinity(); TS_ASSERT_EQUALS(ans, negative_infinity); #endif } void TestDivideZeroByZero() { double zero = 0.0; double ans; #ifdef TEST_FOR_FPE // If we are testing for divide-by-zero, then this will throw an exception //TS_ASSERT_THROWS_ANYTHING(ans = zero / zero); ans=zero;//otherwise compiler would complain ans=ans*zero;//otherwise compiler would complain #else // If we aren't testing for it, then there will be no exception TS_ASSERT_THROWS_NOTHING(ans = zero / zero); TS_ASSERT(std::isnan(ans)); #endif } }; #endif /*_TESTCWD_HPP_*/
3,717
1,254
#include "orderbook.h" #include "hawkes.h" #include "user.h" #include <cassert> #include <iostream> #define name_of_side \ std::string side = (_direction == OrderDirection::ask) ? "ask" : "bid" using namespace std::chrono_literals; OrderDirection opposite(OrderDirection d) { return (d == OrderDirection::ask) ? OrderDirection::bid : OrderDirection::ask; } MatchRes OrderBook::match_orders(std::shared_ptr<Order> &order_1, std::shared_ptr<Order> &order_2) { MatchRes res; res.transaction = false; if ((order_1) && (order_2)) { std::lock_guard<std::mutex> lock_1(*order_1->mtx()); std::lock_guard<std::mutex> lock_2(*order_2->mtx()); if ((order_1->status() == OrderStatus::queued) && (order_2->status() == OrderStatus::queued)) { if ((order_1->direction() != order_2->direction()) && (order_1->id() != order_2->id())) { std::shared_ptr<Order> &ask = (order_1->direction() == OrderDirection::ask) ? order_1 : order_2; std::shared_ptr<Order> &bid = (order_1->direction() == OrderDirection::bid) ? order_1 : order_2; // if((ask->id()==bid->id())||(ask->id()<0)||(bid->id()<0)) return res; if (ask->price() <= bid->price()) { res.transaction = true; res.transaction_size = std::min(ask->size(), bid->size()); res.transaction_price = (*ask < *bid) ? ask->price() : bid->price(); ask->size(ask->size() - res.transaction_size); bid->size(bid->size() - res.transaction_size); if (ask->size() <= 0) ask->mark_as(OrderStatus::executed); if (bid->size() <= 0) bid->mark_as(OrderStatus::executed); } } } } return res; } bool OrderBook::is_match(std::shared_ptr<Order> &order_1, std::shared_ptr<Order> &order_2) { if ((order_1) && (order_2)) { std::lock_guard<std::mutex> lock_1(*order_1->mtx()); std::lock_guard<std::mutex> lock_2(*order_2->mtx()); if ((order_1->status() == OrderStatus::queued) && (order_2->status() == OrderStatus::queued)) { if ((order_1->direction() != order_2->direction()) && (order_1->id() != order_2->id())) { std::shared_ptr<Order> &ask = (order_1->direction() == OrderDirection::ask) ? order_1 : order_2; std::shared_ptr<Order> &bid = (order_1->direction() == OrderDirection::bid) ? order_1 : order_2; if (ask->id() == bid->id()) return false; return ask->price() <= bid->price(); } } } return false; } OrderQueue::OrderQueue(OrderDirection d, int opening_price, std::mutex *bookmtx, std::condition_variable *bookcond) : _direction(d), _bestprice(BestPrice(d, opening_price)), _bookmtx(bookmtx), _bookcond(bookcond) {} OrderQueue::~OrderQueue() { /* std::string side = (_direction==OrderDirection::ask)? "ask" : "bid"; //printf("OrderQueue Destructor - side: %s\n", side.c_str()); */ _bookcond->notify_all(); _cond.notify_all(); } OrderQueue::OrderQueue(const OrderQueue &source) : std::deque<std::shared_ptr<Order>>{source}, Controller(), _direction(source.direction()), _bestprice(BestPrice(_direction, source.bestprice_value())), _bookmtx(source.bookmtx()), _bookcond(source.bookcond()) {} OrderQueue::OrderQueue(OrderQueue &&source) : std::deque<std::shared_ptr<Order>>{source}, Controller(), _direction(source.direction()), _bestprice(BestPrice(_direction, source.bestprice_value())), _bookmtx(source.bookmtx()), _bookcond(source.bookcond()) {} OrderQueue &OrderQueue::operator=(const OrderQueue &source) { std::lock_guard<std::mutex> lock(*_bookmtx); // std::cout << "OrderQueue Copy Assignment this: " << this << std::endl; _direction = source.direction(); _bestprice = BestPrice(_direction, source.bestprice_value()); _bookmtx = source.bookmtx(); _bookcond = source.bookcond(); _bestprice.new_(source.bestprice_order()); return *this; } OrderQueue &OrderQueue::operator=(OrderQueue &&source) { std::lock_guard<std::mutex> lock(*_bookmtx); // std::cout << "OrderQueue Move Assignment this: " << this << std::endl; _direction = source.direction(); _bestprice = BestPrice(_direction, source.bestprice_value()); _bookmtx = source.bookmtx(); _bookcond = source.bookcond(); _bestprice.new_(source.bestprice_order()); return *this; } void OrderQueue::add(std::shared_ptr<Order> &&order) { // write("OrderQueue:: add() direction=%d, order #%d \n", _direction, // order->id()); if (order) { if (order->direction() == _direction) { if (order->status() == OrderStatus::queued) { std::lock_guard<std::mutex> lock(_mtx); _volume += order->size(); auto pos = std::lower_bound( this->begin(), this->end(), order, [](std::shared_ptr<Order> order_1, std::shared_ptr<Order> order_2) { return *order_1 < *order_2; }); _bestprice.update(order); this->insert(pos, order); } } } } int OrderQueue::execute(std::shared_ptr<Order> order) { if (!order) return 0; int trade{0}; if (!is_empty()) { std::lock_guard<std::mutex> lock(_mtx); if (order->direction() != _direction) { int order_id = order->id(); std::string order_side = order->side(); for (auto it = this->begin(); (order->status() != OrderStatus::executed) && (it != this->end()) && (_direction * order->price() <= _direction * (*it)->price()) //_direction is either 1 (bid queue) or //-1 (ask queue) ;) { int id = (*it)->id(); std::string side = (*it)->side(); MatchRes mr = OrderBook::match_orders(*it, order); if (mr.transaction) { write("Limit orders #%d(%s) and #%d(%s) match: transaction " "price=%d, transaction size=%d\n", id, side.c_str(), order_id, order_side.c_str(), mr.transaction_price, mr.transaction_size); trade += mr.transaction_price * mr.transaction_size; _volume -= mr.transaction_size; } if ((*it)->status() != OrderStatus::queued) erase_order(it); else ++it; } if (this->empty()) { name_of_side; write("\n%s queue is now empty \n\n", side.c_str()); this->invalidate_bestprice(); this->cache_bestprice(order->price()); } } } else { this->invalidate_bestprice(); int p = (_direction == OrderDirection::ask) ? std::max(_bestprice.cached_price(), order->price()) : std::min(_bestprice.cached_price(), order->price()); this->cache_bestprice(p); } // write("OrderQueue::execute() direction=%d Now exiting\n", _direction); return trade; } void OrderQueue::simulate() { { std::lock_guard<std::mutex> booklock(*_bookmtx); _bookcond->notify_all(); } while (this->go()) { if (!is_empty()) { bool alterations = update(); if (alterations) { std::lock_guard<std::mutex> booklock(*_bookmtx); renew_bestprice(); _bookcond->notify_all(); // we notify OrderBook so that it can refresh // volumes } } } } void OrderQueue::stop() { _cond.notify_all(); for (auto it = this->begin(); it != this->end(); ++it) { (*it)->stop(); } std::lock_guard<std::mutex> lock(_gomtx); _go = false; } void OrderQueue::erase_order(iterator &it) { if ((this->begin() <= it) && (it < this->end())) { if (*it) { // int id = (*it)->id(); _volume -= (*it)->size(); it = this->erase(it); if (it != this->end()) { _bestprice.update(*it); } // write("OrderQueue::erase_order order #%d has been erased\n", id); } else it = this->erase(it); } } bool OrderQueue::update() { // write("OrderQueue::update() direction=%d\n", _direction); bool cancellations{false}; bool deletions{false}; std::lock_guard<std::mutex> lock(_mtx); for (iterator it = this->begin(); it != this->end();) { if (((*it)->status() != OrderStatus::queued) || ((*it)->size() <= 0)) { erase_order(it); deletions = true; } else { bool cancelling = (*it)->update(); /* if (it!=this->begin()){ int price = (*it)->price(); int prev_price = (*(it-1))->price(); if (price != prev_price){ _pricelevel[price] = it; } */ ++it; cancellations = cancellations || cancelling; } } return cancellations || deletions; } void OrderQueue::sort() { if (!is_empty()) { std::lock_guard<std::mutex> lock(_mtx); std::sort(this->begin(), this->end(), [](std::shared_ptr<Order> a, std::shared_ptr<Order> b) { return *a < *b; }); } } void OrderQueue::renew_bestprice() { std::lock_guard<std::mutex> lock(_mtx); // write("OrderQueue::renew_bestprice() _direction: %d\n", _direction); if (this->empty()) { _bestprice.invalidate(); } else { for (auto it = this->begin(); it != this->end(); ++it) { std::shared_ptr<Order> &order = *it; if (order) { if ((order->status() == OrderStatus::queued) && (order->size() > 0)) { _bestprice.new_(order); break; } } } } } void OrderQueue::erase_notqueued() { std::lock_guard<std::mutex> lock(_mtx); // write("OrderQueue::erase_notqueued() _direction: %d\n", _direction); int count{0}; if (!(this->empty())) { for (auto it = this->begin(); it != this->end();) { if ((*it)->status() != OrderStatus::queued) { erase_order(it); count++; } else { ++it; } } // write("%d orders have been erased from queue %d\n", count, _direction); } } bool OrderQueue::is_sorted() { // write("OrderQueue::is_sorted() _direction: %d\n", _direction); // std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::lock_guard<std::mutex> lock(_mtx); if (!(this->empty())) { auto it = this->begin(); while (it != this->end()) { Order &current = **it; ++it; if (it != this->end()) { Order &next = **it; if (!(current < next)) { write("OrderQueue %d is not sorted. \n", _direction); return false; } } } } return true; } bool OrderQueue::is_empty() { bool isempty = false; std::lock_guard<std::mutex> lock(_mtx); if (this->empty()) { isempty = true; invalidate_bestprice(); /* std::string side = (_direction==OrderDirection::bid)? "Bid" : "Ask"; write("%s queue is empty\n", side.c_str()); */ } return isempty; } OrderBook::OrderBook(int ticksize, int opening_bidprice, int opening_askprice) : _ticksize(ticksize) { opening_bidprice = std::max(10 * ticksize, opening_bidprice); opening_askprice = std::max(opening_bidprice, opening_askprice); _queue = std::map<OrderDirection, OrderQueue>{ {OrderDirection::bid, OrderQueue(OrderDirection::bid, opening_bidprice, &_mtx, &_cond)}, {OrderDirection::ask, OrderQueue(OrderDirection::ask, opening_askprice, &_mtx, &_cond)}, }; } OrderBook::OrderBook(int ticksize, int opening_bidprice, int opening_askprice, std::shared_ptr<SubWindow> subwin) : OrderBook(ticksize, opening_bidprice, opening_askprice) { set_subwindow(subwin); } OrderBook::~OrderBook() { // printf("OrderBook Destructor\n"); } void OrderBook::set_subwindow(std::shared_ptr<SubWindow> subwin) { _subwindow = subwin; for (auto d : all_directions) _queue.at(d).set_subwindow(subwin); } void OrderBook::add(std::shared_ptr<Order> &&order) { if (order) { std::lock_guard<std::mutex> lock(_mtx); write("Order #%d is being added on %s side; price=%d, size=%d\n", order->id(), order->side().c_str(), order->price(), order->active_size()); _queue.at(opposite(order->direction())).execute(order); _queue.at(order->direction()).add(std::move(order)); _cond.notify_all(); } } void OrderBook::add(std::shared_ptr<StandingOrder> &&order, double decayrate) { if (order) { order->set_decay(this, decayrate); add(std::move(order)); } } void OrderBook::add(OrderCommand &&cmd) { add(std::make_shared<Order>(cmd.price, cmd.size, cmd.d, _subwindow)); } void OrderBook::launch_simulation() { for (OrderDirection d : all_directions) { _threads.emplace_back(std::thread(&OrderQueue::simulate, &(_queue.at(d)))); } } void OrderBook::stop() { for (OrderDirection d : all_directions) { _queue.at(d).stop(); } _cond.notify_all(); } BestPrice::BestPrice(OrderDirection d, int initial_price) : _direction(d), _cached(initial_price) {} BestPrice::BestPrice(const BestPrice &source) : _direction(source.direction()), _price(source.price()), _cached(source.cached_price()) { _order = source.order(); } BestPrice::BestPrice(BestPrice &&source) : _direction(source.direction()), _price(source.price()), _cached(source.cached_price()) { _order = source.order(); } BestPrice::~BestPrice() { ////printf("BestPrice Destructor; _direction = %d\n", _direction); } BestPrice &BestPrice::operator=(const BestPrice &source) { _direction = source.direction(); _price = source.price(); _cached = source.cached_price(); _order = source.order(); return *this; } BestPrice &BestPrice::operator=(BestPrice &&source) { _direction = source.direction(); _price = source.price(); _cached = source.cached_price(); _order = source.order(); return *this; } int BestPrice::value() const { return (_order) ? _price : _cached; } void BestPrice::invalidate() { _order.reset(); _price = (_direction == OrderDirection::bid) ? 0 : 0; } bool BestPrice::is_better_than(std::shared_ptr<Order> other) { if (!(other)) return true; return (_order) ? (*_order < *other) : false; } void BestPrice::update(std::shared_ptr<Order> order) { if (order) { if ((order->status() == OrderStatus::queued) && (order->size() > 0)) { if (order->direction() == _direction) { if (!this->is_better_than(order)) { std::lock_guard<std::mutex> lock(*(order->mtx())); _price = order->price(); _cached = _price; _order = order; // write("BestPrice::update() direction=%d, price=%d\n", _direction, // _price); } } } } } void BestPrice::new_(std::shared_ptr<Order> order) { _order.reset(); update(order); } int OrderBook::askprice() { return _queue.at(OrderDirection::ask).bestprice()->value(); } int OrderBook::bidprice() { return _queue.at(OrderDirection::bid).bestprice()->value(); } long OrderBook::askvolume() { return _queue.at(OrderDirection::ask).volume(); } long OrderBook::bidvolume() { return _queue.at(OrderDirection::bid).volume(); } std::random_device rd; std::default_random_engine OrderSubmission::generator(rd()); std::discrete_distribution<int> OrderSubmission::distribution({0.05, 0.35, 0.40, 0.05, 0.05, 0.05, 0.05}); OrderSubmission::OrderSubmission(std::shared_ptr<OrderBook> ob, double decayrate) : hawkes(HawkesProcess(2)), _decayrate(decayrate) { // write("OrderSubmission Constructor\n"); _book = ob; init_user(); } OrderSubmission::~OrderSubmission() { // printf("OrderSubmission Destructor\n"); } void OrderSubmission::init_user() { _user = std::make_shared<User>(_book); _user->set_ordersubmission(this); } void OrderSubmission::set_subwindow(std::shared_ptr<SubWindow> sw) { hawkes.set_subwindow(sw); _subwindow = sw; } void OrderSubmission::set_userwindow(std::shared_ptr<UserWindow> uw) { _user->set_userwindow(uw); } OrderCommand OrderSubmission::generate_command(Event &&event) { OrderCommand cmd; cmd.d = (event.type == 0) ? OrderDirection::bid : OrderDirection::ask; int level = -2 + distribution(generator); int bestprice = (cmd.d == OrderDirection::bid) ? _book->bidprice() : _book->askprice(); cmd.price = std::max(0, bestprice - (cmd.d) * (_book->ticksize()) * level); cmd.size = std::max(0, 50 * (1 + distribution(generator))); // write("OrderSubmission::generate_command side=%d, level=%d, price=%d, // size=%d\n", cmd.d, level, cmd.price, cmd.size); return cmd; } void OrderSubmission::submit(int price, int size, OrderDirection d) { _book->add(std::make_shared<Order>(price, size, d, _subwindow)); } void OrderSubmission::submit(OrderCommand cmd) { submit(cmd.price, cmd.size, cmd.d); } void OrderSubmission::simulate() { // write("OrderSubmission::simulate()\n"); while (this->go()) { OrderCommand cmd = generate_command(hawkes.wait_for_event()); _book->add( std::make_shared<StandingOrder>(cmd.price, cmd.size, cmd.d, _subwindow), _decayrate); } } void OrderSubmission::launch_simulation() { _threads.emplace_back(std::thread(&HawkesProcess::simulate, &hawkes)); _threads.emplace_back(std::thread(&OrderSubmission::simulate, this)); _threads.emplace_back(std::thread(&User::simulate, _user.get())); } void OrderSubmission::stop() { hawkes.stop(); _book->stop(); _user->stop(); { std::lock_guard<std::mutex> lock(_gomtx); _go = false; } }
17,437
5,841
/*----------------------------------------------------------------------------* | This file is part of WinDEU, the port of DEU to Windows. | | WinDEU was created by the DEU team: | | Renaud Paquay, Raphael Quinet, Brendon Wyber and others... | | | | DEU is an open project: if you think that you can contribute, please join | | the DEU team. You will be credited for any code (or ideas) included in | | the next version of the program. | | | | If you want to make any modifications and re-distribute them on your own, | | you must follow the conditions of the WinDEU license. Read the file | | LICENSE or README.TXT in the top directory. If do not have a copy of | | these files, you can request them from any member of the DEU team, or by | | mail: Raphael Quinet, Rue des Martyrs 9, B-4550 Nandrin (Belgium). | | | | This program comes with absolutely no warranty. Use it at your own risks! | *----------------------------------------------------------------------------* Project WinDEU DEU team Jul-Dec 1994, Jan-Mar 1995 FILE: lprogdlg.cpp OVERVIEW ======== Source file for implementation of TLevelProgressDialog (TDialog). */ #include "common.h" #pragma hdrstop #ifndef __lprogdlg_h #include "lprogdlg.h" #endif #ifndef __levels_h #include "levels.h" #endif #ifndef __objects_h #include "objects.h" #endif // // Build a response table for all messages/commands handled // by the application. // DEFINE_RESPONSE_TABLE1(TLevelProgressDialog, TDialog) //{{TLevelProgressDialogRSP_TBL_BEGIN}} EV_WM_SIZE, EV_WM_PAINT, //{{TLevelProgressDialogRSP_TBL_END}} END_RESPONSE_TABLE; //{{TLevelProgressDialog Implementation}} /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // TLevelProgressDialog::TLevelProgressDialog (TWindow* parent, TResId resId, TModule* module) : TDialog(parent, resId, module) { Minimized = FALSE; // // Create interface object for NODES building // pNodesText = new TStatic (this, IDC_BUILD_NODES); pNodesGauge = new TGauge (this, "%d%%", 200, /*pNodesText->Attr.X, pNodesText->Attr.Y+10, pNodesText->Attr.W, pNodesText->Attr.H*/ 10, 20, 100, 10); pNodesGauge->SetRange (0, 100); pNodesGauge->SetValue (0); pVertexesStatic = new TStatic (this, IDC_VERTEXES); pSideDefsStatic = new TStatic (this, IDC_SIDEDEFS); pSegsStatic = new TStatic (this, IDC_SEGS); pSSectorsStatic = new TStatic (this, IDC_SSECTORS); // // Create interface object for REJECT building // pRejectFrame = new TStatic (this, IDC_FRAME_REJECT); // pRejectFrame->Attr.Style &= ~(WS_VISIBLE); pRejectText = new TStatic (this, IDC_BUILD_REJECT); // pRejectText->Attr.Style &= ~(WS_VISIBLE); pRejectGauge = new TGauge (this, "%d%%", 201, /* pRejectText->Attr.X, pRejectText->Attr.Y+10, pRejectText->Attr.W, pRejectText->Attr.H*/ 10, 50, 100, 10); // pRejectGauge->Attr.Style &= ~(WS_VISIBLE); pRejectGauge->SetRange (0, 100); pRejectGauge->SetValue (0); // // Create interface object for BLOCKMAP building // pBlockmapFrame = new TStatic (this, IDC_FRAME_BLOCKMAP); // pBlockmapFrame->Attr.Style &= ~(WS_VISIBLE); pBlockmapText = new TStatic (this, IDC_BUILD_BLOCKMAP); // pBlockmapText->Attr.Style &= ~(WS_VISIBLE); pBlockmapGauge = new TGauge (this, "%d%%", 202, /* pBlockmapText->Attr.X, pBlockmapText->Attr.Y+10, pBlockmapText->Attr.W, pBlockmapText->Attr.H*/ 10, 80, 100, 10); // pBlockmapGauge->Attr.Style &= ~(WS_VISIBLE); pBlockmapGauge->SetRange (0, 100); pBlockmapGauge->SetValue (0); } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // TLevelProgressDialog::~TLevelProgressDialog () { Destroy(); } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void TLevelProgressDialog::SetupWindow () { TRect wRect, cRect; TPoint TopLeft ; TDialog::SetupWindow(); ::CenterWindow (this); // Setup size and pos. of NODES gauge window pNodesText->GetClientRect(cRect); pNodesText->GetWindowRect(wRect); TopLeft = TPoint(wRect.left, wRect.top); ScreenToClient (TopLeft); pNodesGauge->MoveWindow (TopLeft.x, TopLeft.y + 16, cRect.right, 20, TRUE); // Setup size and pos. of REJECT gauge window pRejectText->GetClientRect(cRect); pRejectText->GetWindowRect(wRect); TopLeft = TPoint(wRect.left, wRect.top); ScreenToClient (TopLeft); pRejectGauge->MoveWindow (TopLeft.x, TopLeft.y + 16, cRect.right, 20, TRUE); // Setup size and pos. of BLOCKMAP gauge window pBlockmapText->GetClientRect(cRect); pBlockmapText->GetWindowRect(wRect); TopLeft = TPoint(wRect.left, wRect.top); ScreenToClient (TopLeft); pBlockmapGauge->MoveWindow (TopLeft.x, TopLeft.y + 16, cRect.right, 20, TRUE); /* pRejectText->ShowWindow (SW_HIDE); pRejectFrame->ShowWindow (SW_HIDE); pRejectGauge->ShowWindow (SW_HIDE); */ /* pBlockmapText->ShowWindow (SW_HIDE); pBlockmapFrame->ShowWindow (SW_HIDE); pBlockmapGauge->ShowWindow (SW_HIDE); */ } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void TLevelProgressDialog::ShowNodesProgress (int objtype) { static int SavedNumVertexes = 0; char msg[10] ; switch (objtype) { case OBJ_VERTEXES: wsprintf (msg, "%d", NumVertexes); pVertexesStatic->SetText (msg); break; case OBJ_SIDEDEFS: wsprintf (msg, "%d", NumSideDefs); pSideDefsStatic->SetText (msg); SavedNumVertexes = NumVertexes; break; case OBJ_SSECTORS: wsprintf (msg, "%d", NumSegs); pSegsStatic->SetText (msg); wsprintf (msg, "%d", NumSectors); pSSectorsStatic->SetText (msg); //BUG: We must test the division, because of empty levels // if (NumSideDefs + NumVertexes - SavedNumVertexes > 0 ) { pNodesGauge->SetValue (100.0 * ((float) NumSegs / (float) (NumSideDefs + NumVertexes - SavedNumVertexes))); } else pNodesGauge->SetValue (100); // If minimized, we must paint the icon, else we paint the gauge if ( Minimized ) { Invalidate(FALSE); // Don't repaint background UpdateWindow(); } else pNodesGauge->UpdateWindow(); break; } } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void TLevelProgressDialog::ShowRejectControls () { /* pRejectFrame->ShowWindow (SW_SHOW); pRejectText->ShowWindow (SW_SHOW); pRejectGauge->ShowWindow (SW_SHOW); */ } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void TLevelProgressDialog::ShowRejectProgress (int value) { pRejectGauge->SetValue (value); // If minimized, we must paint the icon, else we paint the gauge if ( Minimized ) { Invalidate(FALSE); // Don't repaint background UpdateWindow(); } else pRejectGauge->UpdateWindow (); } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void TLevelProgressDialog::ShowBlockmapControls () { /* pBlockmapFrame->ShowWindow (SW_SHOW); pBlockmapText->ShowWindow (SW_SHOW); pBlockmapGauge->ShowWindow (SW_SHOW); */ } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void TLevelProgressDialog::ShowBlockmapProgress (int value) { pBlockmapGauge->SetValue (value); // If minimized, we must paint the icon, else we paint the gauge if ( Minimized ) { Invalidate(FALSE); // Don't repaint background UpdateWindow(); } else pBlockmapGauge->UpdateWindow (); } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void TLevelProgressDialog::EvSize (UINT sizeType, TSize& size) { if ( sizeType == SIZE_MINIMIZED ) { Minimized = TRUE; Parent->ShowWindow(SW_HIDE); } else if ( sizeType == SIZE_RESTORED ) { Parent->ShowWindow(SW_SHOW); Minimized = FALSE; } else { Minimized = FALSE; TDialog::EvSize(sizeType, size); } } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void DrawIconicGauge(TDC &dc, int yPosition, int Width, int Height, int Value) { TBrush BleueBrush(TColor(0,0,255)); TPen BleuePen (TColor(0,0,255)); // TBrush GrayBrush (TColor(200,200,200)); TPen WhitePen (TColor(255,255,255)); TPen GrayPen (TColor(100,100,100)); // TPen GrayPen (TColor(0,0,0)); // Draw upper left white border dc.SelectObject(GrayPen); dc.MoveTo(0, yPosition + Height - 1); dc.LineTo(0, yPosition); dc.LineTo(Width - 1, yPosition); // Draw lower right border dc.SelectObject(WhitePen); dc.LineTo(Width - 1, yPosition + Height - 1); dc.LineTo(0, yPosition + Height - 1); // Draw gauge dc.SelectObject(BleueBrush); dc.SelectObject(BleuePen); dc.Rectangle(1, yPosition + 1, (Width - 1) * Value / 100, yPosition + Height - 1); dc.RestoreObjects(); } /////////////////////////////////////////////////////////////// // TLevelProgressDialog // -------------------- // void TLevelProgressDialog::EvPaint () { if ( Minimized ) { TPaintDC dc(*this); TRect ClientRect; // Get size of iconic window GetClientRect(ClientRect); int Width = ClientRect.Width(); int Height = ClientRect.Height(); DrawIconicGauge (dc, 0, Width, Height / 3, pNodesGauge->GetValue()); DrawIconicGauge (dc, Height / 3, Width, Height / 3, pRejectGauge->GetValue()); DrawIconicGauge (dc, 2 * Height / 3, Width, Height / 3, pBlockmapGauge->GetValue()); } else TDialog::EvPaint(); }
10,121
3,801
// // icloud.hpp // blockerd // // Created by Jozef on 05/06/2020. // #ifndef icloud_hpp #define icloud_hpp #include "base.hpp" struct ICloud : public CloudProvider { ICloud(const BlockLevel Bl, const std::vector<std::string> &Paths) { id = CloudProviderId::ICLOUD; bl = Bl; paths = Paths; allowedBundleIds = { "com.apple.bird", }; }; ~ICloud() = default; static std::vector<std::string> FindPaths(const std::string &homePath); }; #endif /* icloud_hpp */
531
198
#include <catch2/catch.hpp> #include "../../log/Logger.h" #include "../System.h" using namespace rdm; // TODO linux //TEST_CASE("System", "getProcessorCount") { // uint64_t min = 1; // uint64_t max = 1024; // ASSERT_LE(min, System::getProcessorCount()); // ASSERT_GE(max, System::getProcessorCount()); // // LOG_DEBUG("processor count: {}", // System::getProcessorCount()); //} // //TEST_CASE(System, getTotalVirtualMemory) { // uint64_t min = 1; // uint64_t max = 1ULL << 63; // ASSERT_LE(min, System::getTotalVirtualMemory()); // ASSERT_GE(max, System::getTotalVirtualMemory()); // // LOG_DEBUG("total virtual memory: {} GB", // System::getTotalVirtualMemory() / 1024 / 1024 / 1024.f); //} // //TEST_CASE(System, getVirtualMemoryUsage) { // uint64_t min = 1; // uint64_t max = 1ULL << 63; // ASSERT_LE(min, System::getVirtualMemoryUsage()); // ASSERT_GE(max, System::getVirtualMemoryUsage()); // // LOG_DEBUG("virtual memory usage: {} GB", // System::getVirtualMemoryUsage() / 1024 / 1024 / 1024.f); //} // //TEST_CASE(System, getVirtualMemoryUsageCurrentProcess) { // uint64_t min = 1; // uint64_t max = 1ULL << 63; // ASSERT_LE(min, System::getVirtualMemoryUsageCurrentProcess()); // ASSERT_GE(max, System::getVirtualMemoryUsageCurrentProcess()); // // LOG_DEBUG("virtual memory usage current process: {} MB", // System::getVirtualMemoryUsageCurrentProcess() / 1024 / 1024.f); //} // //TEST_CASE(System, getTotalPhysicalMemory) { // uint64_t min = 1; // uint64_t max = 1ULL << 63; // ASSERT_LE(min, System::getTotalPhysicalMemory()); // ASSERT_GE(max, System::getTotalPhysicalMemory()); // // LOG_DEBUG("total physical memory: {} GB", // System::getTotalPhysicalMemory() / 1024 / 1024 / 1024.f); //} // //TEST_CASE(System, getPhysicalMemoryUsage) { // uint64_t min = 1; // uint64_t max = 1ULL << 63; // ASSERT_LE(min, System::getPhysicalMemoryUsage()); // ASSERT_GE(max, System::getPhysicalMemoryUsage()); // // LOG_DEBUG("physical memory usage: {} GB", // System::getPhysicalMemoryUsage() / 1024 / 1024 / 1024.f); //} // //TEST_CASE(System, gePhysicalMemoryUsageCurrentProcess) { // uint64_t min = 1; // uint64_t max = 1ULL << 63; // ASSERT_LE(min <= System::gePhysicalMemoryUsageCurrentProcess()); // ASSERT_GE(max >= System::gePhysicalMemoryUsageCurrentProcess()); // // LOG_DEBUG("physical memory usage current process: {} MB", // System::gePhysicalMemoryUsageCurrentProcess() / 1024 / 1024.f); //} // //TEST_CASE(System, getCpuCurrentUsage) { // System::initCpuCurrentUsage(); // for (auto i = 0; i < 1 * 1000 * 1000; ++i) { // std::srand(0); // } // auto usage = System::getCpuCurrentUsage(); // ASSERT_LT(0 < usage); // ASSERT_GE(100 >= usage); // // LOG_DEBUG("cup current usage: {} %", usage); //} // //TEST_CASE(System, getCpuCurrentProcessUsage) { // System::initCpuCurrentProcessUsage(); // for (auto i = 0; i < 1 * 1000 * 1000; ++i) { // std::srand(0); // } // auto usage = System::getCpuCurrentProcessUsage(); // ASSERT_LT(0 < usage); // ASSERT_GE(100 >= usage); // // LOG_DEBUG("cup current process usage: {} %", usage); //}
3,298
1,245
/* * Copyright 2020 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "cros-camera/common.h" #include <base/notreached.h> #include <utility> #include "common/libcamera_connector/camera_module_callbacks.h" namespace cros { CameraModuleCallbacks::CameraModuleCallbacks( DeviceStatusCallback device_status_callback) : camera_module_callbacks_(this), device_status_callback_(std::move(device_status_callback)) {} mojo::PendingAssociatedRemote<mojom::CameraModuleCallbacks> CameraModuleCallbacks::GetModuleCallbacks() { if (camera_module_callbacks_.is_bound()) { camera_module_callbacks_.reset(); } return camera_module_callbacks_.BindNewEndpointAndPassRemote(); } void CameraModuleCallbacks::CameraDeviceStatusChange( int32_t camera_id, mojom::CameraDeviceStatus new_status) { LOGF(INFO) << "Camera " << camera_id << " status changed: " << new_status; switch (new_status) { case mojom::CameraDeviceStatus::CAMERA_DEVICE_STATUS_PRESENT: device_status_callback_.Run(camera_id, true); break; case mojom::CameraDeviceStatus::CAMERA_DEVICE_STATUS_NOT_PRESENT: device_status_callback_.Run(camera_id, false); break; default: NOTREACHED() << "Unexpected new device status: " << new_status; } } void CameraModuleCallbacks::TorchModeStatusChange( int32_t camera_id, mojom::TorchModeStatus new_status) { // We don't need to do anything for torch mode status change for now. } } // namespace cros
1,588
518
#include <google/protobuf/text_format.h> #include <cstring> #include "flutter/cpp/backends/external.h" #include "flutter/cpp/proto/backend_setting.pb.h" #include "main.h" extern "C" struct dart_ffi_backend_match_result *dart_ffi_backend_match( const char *lib_path, const char *manufacturer, const char *model) { ::mlperf::mobile::BackendFunctions backend(lib_path); if (*lib_path != '\0' && !backend.isLoaded()) { std::cerr << "backend '" << lib_path << "' can't be loaded\n"; return nullptr; } mlperf_device_info_t device_info{model, manufacturer}; // backends should set pbdata to a statically allocated string, so we don't // need to free it const char *pbdata = nullptr; auto result = new dart_ffi_backend_match_result; result->matches = backend.match(&result->error_message, &pbdata, &device_info); if (pbdata == nullptr) { std::cout << "Backend haven't filled settings" << std::endl; return result; } ::mlperf::mobile::BackendSetting setting; if (!google::protobuf::TextFormat::ParseFromString(pbdata, &setting)) { std::cout << "Can't parse backend settings before serialization:\n" << pbdata << std::endl; return result; } std::string res; if (!setting.SerializeToString(&res)) { std::cout << "Can't serialize backend settings\n"; return result; } result->pbdata_size = res.length(); result->pbdata = new char[result->pbdata_size]; memcpy(result->pbdata, res.data(), result->pbdata_size); return result; } extern "C" void dart_ffi_backend_match_free( dart_ffi_backend_match_result *result) { (void)result->error_message; // should be statically allocated delete result->pbdata; // pbdata is allocated in dart_ffi_backend_match delete result; }
1,780
605
#include "Math.hpp" Vector2 operator*(float s, const Vector2& v) { return { v.x * s, v.y * s }; } Vector3 operator*(float s, const Vector3& v) { return { v.x * s, v.y * s, v.z * s }; }
185
75
#include "PhysicsConstraint.h" namespace gameplay { inline float PhysicsConstraint::getBreakingImpulse() const { GP_ASSERT(_constraint); return _constraint->getBreakingImpulseThreshold(); } inline void PhysicsConstraint::setBreakingImpulse(float impulse) { GP_ASSERT(_constraint); _constraint->setBreakingImpulseThreshold(impulse); } inline bool PhysicsConstraint::isEnabled() const { GP_ASSERT(_constraint); return _constraint->isEnabled(); } inline void PhysicsConstraint::setEnabled(bool enabled) { GP_ASSERT(_constraint); _constraint->setEnabled(enabled); } }
632
186
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * 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 * * SeisComP Public License for more details. * ***************************************************************************/ #include "origintime.h" #include <iostream> #include <seiscomp3/gui/core/application.h> namespace Seiscomp { namespace Gui { OriginTimeDialog::OriginTimeDialog(double lon, double lat, Seiscomp::Core::Time time, QWidget * parent, Qt::WFlags f) : QDialog(parent, f) { _ui.setupUi(this); _ui.label->setFont(SCScheme.fonts.normal); _ui.label_2->setFont(SCScheme.fonts.normal); _ui.labelLatitude->setFont(SCScheme.fonts.highlight); _ui.labelLongitude->setFont(SCScheme.fonts.highlight); _ui.labelLatitude->setText(QString("%1 %2").arg(lat, 0, 'f', 2).arg(QChar(0x00b0))); _ui.labelLongitude->setText(QString("%1 %2").arg(lon, 0, 'f', 2).arg(QChar(0x00b0))); int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0; time.get(&y, &M, &d, &h, &m, &s); _ui.timeEdit->setTime(QTime(h, m, s)); _ui.dateEdit->setDate(QDate(y, M, d)); } Seiscomp::Core::Time OriginTimeDialog::time() const { QDateTime dt(_ui.dateEdit->date(), _ui.timeEdit->time()); Seiscomp::Core::Time t; t.set(_ui.dateEdit->date().year(), _ui.dateEdit->date().month(), _ui.dateEdit->date().day(), _ui.timeEdit->time().hour(), _ui.timeEdit->time().minute(), _ui.timeEdit->time().second(), 0); return t; } } }
2,146
712
#include "marker/marker.h" #include "data/tileData.h" #include "gl/texture.h" #include "scene/dataLayer.h" #include "scene/drawRule.h" #include "scene/scene.h" #include "style/style.h" #include "view/view.h" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtx/transform.hpp" namespace Tangram { Marker::Marker(MarkerID id) : m_id(id) { m_drawRuleSet.reset(new DrawRuleMergeSet()); } Marker::~Marker() { } void Marker::setBounds(BoundingBox bounds) { m_bounds = bounds; m_origin = bounds.min; // South-West corner } void Marker::setFeature(std::unique_ptr<Feature> feature) { m_feature = std::move(feature); } void Marker::setStyling(std::string styling, bool isPath) { m_styling.string = styling; m_styling.isPath = isPath; } bool Marker::evaluateRuleForContext(StyleContext& ctx) { return m_drawRuleSet->evaluateRuleForContext(*drawRule(), ctx); } void Marker::setDrawRuleData(std::unique_ptr<DrawRuleData> drawRuleData) { m_drawRuleData = std::move(drawRuleData); m_drawRule = std::make_unique<DrawRule>(*m_drawRuleData, "", 0); } void Marker::mergeRules(const SceneLayer& layer) { m_drawRuleSet->mergeRules(layer); } bool Marker::finalizeRuleMergingForName(const std::string& name) { bool found = false; for (auto& rule : m_drawRuleSet->matchedRules()) { if (name == *rule.name) { m_drawRule = std::make_unique<DrawRule>(rule); found = true; break; } } if (found) { // Clear leftover data (outside the loop so we don't invalidate iterators). m_drawRuleData.reset(nullptr); m_drawRuleSet->matchedRules().clear(); } return found; } void Marker::setMesh(uint32_t styleId, uint32_t zoom, std::unique_ptr<StyledMesh> mesh) { m_mesh = std::move(mesh); m_styleId = styleId; m_builtZoomLevel = zoom; float scale; if (m_feature && m_feature->geometryType == GeometryType::points) { scale = (MapProjection::HALF_CIRCUMFERENCE * 2) / (1 << zoom); } else { scale = modelScale(); } m_modelMatrix = glm::scale(glm::vec3(scale)); } void Marker::clearMesh() { m_mesh.reset(); } void Marker::setTexture(std::unique_ptr<Texture> texture) { m_texture = std::move(texture); } void Marker::setEase(const glm::dvec2& dest, float duration, EaseType e) { auto origin = m_origin; auto cb = [=](float t) { m_origin = { ease(origin.x, dest.x, t, e), ease(origin.y, dest.y, t, e) }; }; m_ease = { duration, cb }; } void Marker::update(float dt, const View& view) { // Update easing if (!m_ease.finished()) { m_ease.update(dt); } // Apply marker-view translation to the model matrix const auto& viewOrigin = view.getPosition(); m_modelMatrix[3][0] = m_origin.x - viewOrigin.x; m_modelMatrix[3][1] = m_origin.y - viewOrigin.y; m_modelViewProjectionMatrix = view.getViewProjectionMatrix() * m_modelMatrix; } void Marker::setVisible(bool visible) { m_visible = visible; } void Marker::setDrawOrder(int drawOrder) { m_drawOrder = drawOrder; } void Marker::setSelectionColor(uint32_t selectionColor) { m_selectionColor = selectionColor; } int Marker::builtZoomLevel() const { return m_builtZoomLevel; } int Marker::drawOrder() const { return m_drawOrder; } MarkerID Marker::id() const { return m_id; } uint32_t Marker::styleId() const { return m_styleId; } float Marker::extent() const { return glm::max(m_bounds.width(), m_bounds.height()); } float Marker::modelScale() const { return glm::max(extent(), 4096.0f); } Feature* Marker::feature() const { return m_feature.get(); } DrawRule* Marker::drawRule() const { return m_drawRule.get(); } StyledMesh* Marker::mesh() const { return m_mesh.get(); } Texture* Marker::texture() const { return m_texture.get(); } const BoundingBox& Marker::bounds() const { return m_bounds; } const glm::dvec2& Marker::origin() const { return m_origin; } const glm::mat4& Marker::modelMatrix() const { return m_modelMatrix; } const glm::mat4& Marker::modelViewProjectionMatrix() const { return m_modelViewProjectionMatrix; } bool Marker::isEasing() const { return !m_ease.finished(); } bool Marker::isVisible() const { return m_visible; } uint32_t Marker::selectionColor() const { return m_selectionColor; } bool Marker::compareByDrawOrder(const std::unique_ptr<Marker>& lhs, const std::unique_ptr<Marker>& rhs) { return lhs->m_drawOrder < rhs->m_drawOrder; } } // namespace Tangram
4,550
1,655
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDateTime> //biblioteca para trabalhar com da e hora MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); tempo = new QTimer(this); //instanciando o objeto 'tempo' connect(tempo, SIGNAL(timeout()), this, SLOT(relogio())); //conxão entr um sinal e um slot tempo->start(1000); //dispara o sinal 'tempo' a cada 1 segundo, executando a função 'funcaoTempo'. } MainWindow::~MainWindow() { delete ui; } void MainWindow::relogio() { QTime tempoatual = QTime::currentTime(); //retorna o tempo do sistema operacional QString data = tempoatual.toString("hh:mm:ss"); //converte de QString para QString ui->textEdit->setText(data); }
849
283
#include <omega-common/common.h> #include <iostream> using namespace OmegaCommon; static Map<String,String> srcs; inline void extractSources(StrRef lineBuffer){ std::string name,src; auto line_it = lineBuffer.begin(); while(line_it != lineBuffer.end()){ auto & c =*line_it; if(c == '=') { break; } name.push_back(c); ++line_it; }; ++line_it; while(line_it != lineBuffer.end()){ auto & c =*line_it; src.push_back(c); ++line_it; }; srcs.insert(std::make_pair(name,src)); }; auto header = R"(// WARNING!! This file was generated by omega-ebin. // )"; #define STATIC_BUFFER_DECLARE "const char " #define CHAR_LINE_MAX 20 int main(int argc,char *argv[]){ StrRef input; StrRef output; for(unsigned i = 1;i < argc;i++){ StrRef in(argv[i]); if(in == "-o"){ output = argv[++i]; } else if(in == "-i"){ input = argv[++i]; }; }; std::ifstream infile {input,std::ios::in}; if (infile.is_open()) { while(!infile.eof()){ std::string line; std::getline(infile,line); // std::cout << line << std::endl; extractSources(line); } } else { std::cerr << "ERROR: " << input.data() << " cannot be opened. Exiting..." << std::endl; exit(1); } infile.close(); std::ofstream out {output.data(),std::ios::out}; auto p = FS::Path(input); std::cout << p.dir() << std::endl; FS::changeCWD(p.dir()); out << header << std::endl; for(auto & s : srcs){ out << STATIC_BUFFER_DECLARE << s.first << "[] ="; out << "{"; std::ifstream binIn(s.second,std::ios::binary | std::ios::in); if(!binIn.is_open()){ std::cerr << "ERROR: " << s.second << " cannot be opened. Exiting..." << std::endl; exit(1); }; unsigned c_count = 0; out << std::hex; while(!binIn.eof()) { int c = binIn.get(); ++c_count; if(!binIn.eof()){ out << "0x" << c; } else { break; } if(!binIn.eof()){ out << ","; }; if(c_count >= CHAR_LINE_MAX){ out << std::endl; c_count = 0; }; } out << std::dec; out << "};" << std::endl; }; out.close(); return 0; };
2,551
878
/************************************************************************* * Copyright (C) [2019] by Cambricon, 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 * * 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 <glog/logging.h> #include <gtest/gtest.h> #include <cmath> #include <memory> #include <string> #include <vector> #include "cnstream_time_utility.hpp" #include "sqlite_db.hpp" #include "perf_calculator.hpp" #include "perf_manager.hpp" namespace cnstream { extern bool CreateDir(std::string path); extern std::string gTestPerfDir; extern std::string gTestPerfFile; TEST(PerfCalculator, PrintLatency) { PerfStats stats = {10100, 20010, 1600, 100.5}; PrintLatency(stats); } TEST(PerfCalculator, PrintThroughput) { PerfStats stats = {10100, 20010, 1600, 100.5}; PrintThroughput(stats); } TEST(PerfCalculator, PrintPerfStats) { PerfStats stats = {10123, 20001, 1600, 100.526}; PrintPerfStats(stats); } TEST(PerfCalculator, Construct) { PerfCalculator perf_cal; EXPECT_EQ(perf_cal.pre_time_, unsigned(0)); } TEST(PerfCalculator, CalcLatency) { CreateDir(gTestPerfDir); remove(gTestPerfFile.c_str()); PerfCalculator perf_cal; auto sql = std::make_shared<Sqlite>(gTestPerfFile); std::string table_name = "TEST"; sql->Connect(); std::vector<std::string> keys = {"a", "b"}; sql->CreateTable(table_name, "ID", keys); size_t total = 0; size_t max = 0; uint32_t data_num = 10; for (uint32_t i = 0; i < data_num; i++) { size_t start = TimeStamp::Current(); std::this_thread::sleep_for(std::chrono::microseconds(10 + i)); size_t end = TimeStamp::Current(); sql->Insert(table_name, "ID,a,b", std::to_string(i) + ","+ std::to_string(start) + "," + std::to_string(end)); size_t duration = end - start; total += duration; if (duration > max) max = duration; } PerfStats stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]); #ifdef HAVE_SQLITE EXPECT_EQ(stats.latency_avg, total / data_num); EXPECT_EQ(stats.latency_max, max); EXPECT_EQ(stats.frame_cnt, data_num); EXPECT_EQ(perf_cal.GetLatency().latency_avg, total / data_num); EXPECT_EQ(perf_cal.GetLatency().latency_max, max); EXPECT_EQ(perf_cal.GetLatency().frame_cnt, data_num); #else EXPECT_EQ(stats.latency_avg, (unsigned)0); EXPECT_EQ(stats.latency_max, (unsigned)0); EXPECT_EQ(stats.frame_cnt, (unsigned)0); #endif remove(gTestPerfFile.c_str()); } void CheckForZeroLatency(PerfStats stats, uint32_t line) { EXPECT_EQ(stats.latency_avg, (unsigned)0) << "wrong line = " << line; EXPECT_EQ(stats.latency_max, (unsigned)0) << "wrong line = " << line; EXPECT_EQ(stats.frame_cnt, (unsigned)0) << "wrong line = " << line; } TEST(PerfCalculator, CalcLatencyFailedCase) { CreateDir(gTestPerfDir); remove(gTestPerfFile.c_str()); PerfCalculator perf_cal; PerfStats stats = perf_cal.CalcLatency(nullptr, "", "", ""); CheckForZeroLatency(stats, __LINE__); auto sql = std::make_shared<Sqlite>(gTestPerfFile); std::string table_name = "TEST"; sql->Connect(); std::vector<std::string> keys = {"a", "b"}; sql->CreateTable(table_name, "ID", keys); stats = perf_cal.CalcLatency(sql, "", "", ""); CheckForZeroLatency(stats, __LINE__); // no start and end time stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]); CheckForZeroLatency(stats, __LINE__); // no start, but only end time size_t end = TimeStamp::Current(); sql->Insert(table_name, "ID,b", "0,"+ std::to_string(end)); stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]); CheckForZeroLatency(stats, __LINE__); std::this_thread::sleep_for(std::chrono::microseconds(10)); size_t start = TimeStamp::Current(); sql->Update(table_name, "a", std::to_string(start), "ID", "0"); // end - start is negtive stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]); CheckForZeroLatency(stats, __LINE__); remove(gTestPerfFile.c_str()); } TEST(PerfCalculator, CalcThroughputByTotalTime) { CreateDir(gTestPerfDir); remove(gTestPerfFile.c_str()); PerfCalculator perf_cal; auto sql = std::make_shared<Sqlite>(gTestPerfFile); std::string table_name = "TEST"; sql->Connect(); std::vector<std::string> keys = {"a", "b"}; sql->CreateTable(table_name, "ID", keys); uint32_t data_num = 10; size_t start = TimeStamp::Current(); sql->Insert(table_name, "ID,a,b", "0,"+ std::to_string(start) + "," + std::to_string(TimeStamp::Current())); for (uint32_t i = 1; i < data_num - 1; i++) { size_t s = TimeStamp::Current(); std::this_thread::sleep_for(std::chrono::microseconds(10 + i)); size_t e = TimeStamp::Current(); sql->Insert(table_name, "ID,a,b", std::to_string(i) + ","+ std::to_string(s) + "," + std::to_string(e)); } size_t end = TimeStamp::Current(); sql->Insert(table_name, "ID,a,b", std::to_string(data_num - 1) + "," + std::to_string(TimeStamp::Current()) + "," + std::to_string(end)); PerfStats stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]); #ifdef HAVE_SQLITE EXPECT_EQ(stats.frame_cnt, data_num); EXPECT_DOUBLE_EQ(stats.fps, ceil(static_cast<double>(data_num) * 1e7 / (end -start)) / 10.0); #else EXPECT_EQ(stats.frame_cnt, (unsigned)0); EXPECT_DOUBLE_EQ(stats.fps, 0); #endif EXPECT_DOUBLE_EQ(stats.fps, perf_cal.GetThroughput().fps); remove(gTestPerfFile.c_str()); } TEST(PerfCalculator, CalcThroughputByTotalTimeFailedCase) { CreateDir(gTestPerfDir); remove(gTestPerfFile.c_str()); PerfCalculator perf_cal; PerfStats stats = perf_cal.CalcThroughputByTotalTime(nullptr, "", "", ""); CheckForZeroLatency(stats, __LINE__); auto sql = std::make_shared<Sqlite>(gTestPerfFile); std::string table_name = "TEST"; sql->Connect(); std::vector<std::string> keys = {"a", "b"}; sql->CreateTable(table_name, "ID", keys); stats = perf_cal.CalcThroughputByTotalTime(sql, "", "", ""); CheckForZeroLatency(stats, __LINE__); // no start and end time stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]); CheckForZeroLatency(stats, __LINE__); // no start, but only end time size_t end = TimeStamp::Current(); sql->Insert(table_name, "ID,b", "0,"+ std::to_string(end)); stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]); CheckForZeroLatency(stats, __LINE__); std::this_thread::sleep_for(std::chrono::microseconds(10)); size_t start = TimeStamp::Current(); sql->Update(table_name, "a", std::to_string(start), "ID", "0"); // end - start is negtive stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]); CheckForZeroLatency(stats, __LINE__); // no end, but only start time sql->Delete(table_name, "ID", "0"); sql->Insert(table_name, "ID,a", "0,"+ std::to_string(start)); stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]); CheckForZeroLatency(stats, __LINE__); remove(gTestPerfFile.c_str()); } } // namespace cnstream
7,832
3,115
#ifndef STAN_LANG_AST_CHOLESKY_FACTOR_COV_BLOCK_TYPE_HPP #define STAN_LANG_AST_CHOLESKY_FACTOR_COV_BLOCK_TYPE_HPP #include <stan/lang/ast/node/expression.hpp> namespace stan { namespace lang { /** * Cholesky factor for covariance matrix block var type. * * Note: no 1-arg constructor for square matrix; * both row and column dimensions always required. */ struct cholesky_factor_cov_block_type { /** * Number of rows. */ expression M_; /** * Number of columns. */ expression N_; /** * Construct a block var type with default values. */ cholesky_factor_cov_block_type(); /** * Construct a block var type with specified values. * * @param M num rows * @param N num columns */ cholesky_factor_cov_block_type(const expression& M, const expression& N); /** * Get M (num rows). */ expression M() const; /** * Get N (num cols). */ expression N() const; }; } // namespace lang } // namespace stan #endif
982
350
#pragma once #include <sal.h> #include <codeanalysis/sourceannotations.h> // TEMPORARY INCLUDE #include <Windows.h> namespace WPFUtils { LONG ReadRegistryString(__in HKEY rootKey, __in LPCWSTR keyName, __in LPCWSTR valueName, __out LPWSTR value, size_t cchMax); HRESULT GetWPFInstallPath(__out_ecount(cchMaxPath) LPWSTR pszPath, size_t cchMaxPath); }
400
140
#include <cmath> #include <eepp/math/transform.hpp> namespace EE { namespace Math { const Transform Transform::Identity; Transform::Transform() { // Identity matrix mMatrix[0] = 1.f; mMatrix[4] = 0.f; mMatrix[8] = 0.f; mMatrix[12] = 0.f; mMatrix[1] = 0.f; mMatrix[5] = 1.f; mMatrix[9] = 0.f; mMatrix[13] = 0.f; mMatrix[2] = 0.f; mMatrix[6] = 0.f; mMatrix[10] = 1.f; mMatrix[14] = 0.f; mMatrix[3] = 0.f; mMatrix[7] = 0.f; mMatrix[11] = 0.f; mMatrix[15] = 1.f; } Transform::Transform( float a00, float a01, float a02, float a10, float a11, float a12, float a20, float a21, float a22 ) { mMatrix[0] = a00; mMatrix[4] = a01; mMatrix[8] = 0.f; mMatrix[12] = a02; mMatrix[1] = a10; mMatrix[5] = a11; mMatrix[9] = 0.f; mMatrix[13] = a12; mMatrix[2] = 0.f; mMatrix[6] = 0.f; mMatrix[10] = 1.f; mMatrix[14] = 0.f; mMatrix[3] = a20; mMatrix[7] = a21; mMatrix[11] = 0.f; mMatrix[15] = a22; } const float* Transform::getMatrix() const { return mMatrix; } Transform Transform::getInverse() const { // Compute the determinant float det = mMatrix[0] * ( mMatrix[15] * mMatrix[5] - mMatrix[7] * mMatrix[13] ) - mMatrix[1] * ( mMatrix[15] * mMatrix[4] - mMatrix[7] * mMatrix[12] ) + mMatrix[3] * ( mMatrix[13] * mMatrix[4] - mMatrix[5] * mMatrix[12] ); // Compute the inverse if the determinant is not zero // (don't use an epsilon because the determinant may *really* be tiny) if ( det != 0.f ) { return Transform( ( mMatrix[15] * mMatrix[5] - mMatrix[7] * mMatrix[13] ) / det, -( mMatrix[15] * mMatrix[4] - mMatrix[7] * mMatrix[12] ) / det, ( mMatrix[13] * mMatrix[4] - mMatrix[5] * mMatrix[12] ) / det, -( mMatrix[15] * mMatrix[1] - mMatrix[3] * mMatrix[13] ) / det, ( mMatrix[15] * mMatrix[0] - mMatrix[3] * mMatrix[12] ) / det, -( mMatrix[13] * mMatrix[0] - mMatrix[1] * mMatrix[12] ) / det, ( mMatrix[7] * mMatrix[1] - mMatrix[3] * mMatrix[5] ) / det, -( mMatrix[7] * mMatrix[0] - mMatrix[3] * mMatrix[4] ) / det, ( mMatrix[5] * mMatrix[0] - mMatrix[1] * mMatrix[4] ) / det ); } else { return Identity; } } Vector2f Transform::transformPoint( float x, float y ) const { return Vector2f( mMatrix[0] * x + mMatrix[4] * y + mMatrix[12], mMatrix[1] * x + mMatrix[5] * y + mMatrix[13] ); } Vector2f Transform::transformPoint( const Vector2f& point ) const { return transformPoint( point.x, point.y ); } Rectf Transform::transformRect( const Rectf& rectangle ) const { // Transform the 4 corners of the rectangle const Vector2f points[] = { transformPoint( rectangle.Left, rectangle.Top ), transformPoint( rectangle.Left, rectangle.Top + rectangle.Bottom ), transformPoint( rectangle.Left + rectangle.Right, rectangle.Top ), transformPoint( rectangle.Left + rectangle.Right, rectangle.Top + rectangle.Bottom )}; // Compute the bounding rectangle of the transformed points float left = points[0].x; float top = points[0].y; float right = points[0].x; float bottom = points[0].y; for ( int i = 1; i < 4; ++i ) { if ( points[i].x < left ) left = points[i].x; else if ( points[i].x > right ) right = points[i].x; if ( points[i].y < top ) top = points[i].y; else if ( points[i].y > bottom ) bottom = points[i].y; } return Rectf( left, top, right - left, bottom - top ); } Transform& Transform::combine( const Transform& transform ) { const float* a = mMatrix; const float* b = transform.mMatrix; *this = Transform( a[0] * b[0] + a[4] * b[1] + a[12] * b[3], a[0] * b[4] + a[4] * b[5] + a[12] * b[7], a[0] * b[12] + a[4] * b[13] + a[12] * b[15], a[1] * b[0] + a[5] * b[1] + a[13] * b[3], a[1] * b[4] + a[5] * b[5] + a[13] * b[7], a[1] * b[12] + a[5] * b[13] + a[13] * b[15], a[3] * b[0] + a[7] * b[1] + a[15] * b[3], a[3] * b[4] + a[7] * b[5] + a[15] * b[7], a[3] * b[12] + a[7] * b[13] + a[15] * b[15] ); return *this; } Transform& Transform::translate( float x, float y ) { Transform translation( 1, 0, x, 0, 1, y, 0, 0, 1 ); return combine( translation ); } Transform& Transform::translate( const Vector2f& offset ) { return translate( offset.x, offset.y ); } Transform& Transform::rotate( float angle ) { float rad = angle * 3.141592654f / 180.f; float cos = std::cos( rad ); float sin = std::sin( rad ); Transform rotation( cos, -sin, 0, sin, cos, 0, 0, 0, 1 ); return combine( rotation ); } Transform& Transform::rotate( float angle, float centerX, float centerY ) { float rad = angle * 3.141592654f / 180.f; float cos = std::cos( rad ); float sin = std::sin( rad ); Transform rotation( cos, -sin, centerX * ( 1 - cos ) + centerY * sin, sin, cos, centerY * ( 1 - cos ) - centerX * sin, 0, 0, 1 ); return combine( rotation ); } Transform& Transform::rotate( float angle, const Vector2f& center ) { return rotate( angle, center.x, center.y ); } Transform& Transform::scale( float scaleX, float scaleY ) { Transform scaling( scaleX, 0, 0, 0, scaleY, 0, 0, 0, 1 ); return combine( scaling ); } Transform& Transform::scale( float scaleX, float scaleY, float centerX, float centerY ) { Transform scaling( scaleX, 0, centerX * ( 1 - scaleX ), 0, scaleY, centerY * ( 1 - scaleY ), 0, 0, 1 ); return combine( scaling ); } Transform& Transform::scale( const Vector2f& factors ) { return scale( factors.x, factors.y ); } Transform& Transform::scale( const Vector2f& factors, const Vector2f& center ) { return scale( factors.x, factors.y, center.x, center.y ); } Transform operator*( const Transform& left, const Transform& right ) { return Transform( left ).combine( right ); } Transform& operator*=( Transform& left, const Transform& right ) { return left.combine( right ); } Vector2f operator*( const Transform& left, const Vector2f& right ) { return left.transformPoint( right ); } bool operator==( const Transform& left, const Transform& right ) { const float* a = left.getMatrix(); const float* b = right.getMatrix(); return ( ( a[0] == b[0] ) && ( a[1] == b[1] ) && ( a[3] == b[3] ) && ( a[4] == b[4] ) && ( a[5] == b[5] ) && ( a[7] == b[7] ) && ( a[12] == b[12] ) && ( a[13] == b[13] ) && ( a[15] == b[15] ) ); } bool operator!=( const Transform& left, const Transform& right ) { return !( left == right ); } }} // namespace EE::Math
6,283
2,780
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 02.01.01.0784 // ---------------------------------------------------------------------------- // Standard ImageIntegration Process Module Version 01.09.04.0322 // ---------------------------------------------------------------------------- // HDRCompositionParameters.cpp - Released 2016/02/21 20:22:43 UTC // ---------------------------------------------------------------------------- // This file is part of the standard ImageIntegration PixInsight module. // // Copyright (c) 2003-2016 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (http://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) 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 "HDRCompositionParameters.h" namespace pcl { // ---------------------------------------------------------------------------- HCImages* TheHCImagesParameter = 0; HCImageEnabled* TheHCImageEnabledParameter = 0; HCImagePath* TheHCImagePathParameter = 0; HCInputHints* TheHCInputHintsParameter = 0; HCMaskBinarizingThreshold* TheHCMaskBinarizingThresholdParameter = 0; HCMaskSmoothness* TheHCMaskSmoothnessParameter = 0; HCMaskGrowth* TheHCMaskGrowthParameter = 0; HCAutoExposures* TheHCAutoExposuresParameter = 0; HCRejectBlack* TheHCRejectBlackParameter = 0; HCUseFittingRegion* TheHCUseFittingRegionParameter = 0; HCFittingRectX0* TheHCFittingRectX0Parameter = 0; HCFittingRectY0* TheHCFittingRectY0Parameter = 0; HCFittingRectX1* TheHCFittingRectX1Parameter = 0; HCFittingRectY1* TheHCFittingRectY1Parameter = 0; HCGenerate64BitResult* TheHCGenerate64BitResultParameter = 0; HCOutputMasks* TheHCOutputMasksParameter = 0; HCClosePreviousImages* TheHCClosePreviousImagesParameter = 0; // ---------------------------------------------------------------------------- HCImages::HCImages( MetaProcess* P ) : MetaTable( P ) { TheHCImagesParameter = this; } IsoString HCImages::Id() const { return "images"; } // ---------------------------------------------------------------------------- HCImageEnabled::HCImageEnabled( MetaTable* T ) : MetaBoolean( T ) { TheHCImageEnabledParameter = this; } IsoString HCImageEnabled::Id() const { return "enabled"; } bool HCImageEnabled::DefaultValue() const { return true; } // ---------------------------------------------------------------------------- HCImagePath::HCImagePath( MetaTable* T ) : MetaString( T ) { TheHCImagePathParameter = this; } IsoString HCImagePath::Id() const { return "path"; } // ---------------------------------------------------------------------------- HCInputHints::HCInputHints( MetaProcess* P ) : MetaString( P ) { TheHCInputHintsParameter = this; } IsoString HCInputHints::Id() const { return "inputHints"; } // ---------------------------------------------------------------------------- HCMaskBinarizingThreshold::HCMaskBinarizingThreshold( MetaProcess* P ) : MetaFloat( P ) { TheHCMaskBinarizingThresholdParameter = this; } IsoString HCMaskBinarizingThreshold::Id() const { return "maskBinarizingThreshold"; } int HCMaskBinarizingThreshold::Precision() const { return 4; } double HCMaskBinarizingThreshold::DefaultValue() const { return 0.8; } double HCMaskBinarizingThreshold::MinimumValue() const { return 0; } double HCMaskBinarizingThreshold::MaximumValue() const { return 1; } // ---------------------------------------------------------------------------- HCMaskSmoothness::HCMaskSmoothness( MetaProcess* P ) : MetaInt32( P ) { TheHCMaskSmoothnessParameter = this; } IsoString HCMaskSmoothness::Id() const { return "maskSmoothness"; } double HCMaskSmoothness::DefaultValue() const { return 7; } double HCMaskSmoothness::MinimumValue() const { return 1; } double HCMaskSmoothness::MaximumValue() const { return 25; } // ---------------------------------------------------------------------------- HCMaskGrowth::HCMaskGrowth( MetaProcess* P ) : MetaInt32( P ) { TheHCMaskGrowthParameter = this; } IsoString HCMaskGrowth::Id() const { return "maskGrowth"; } double HCMaskGrowth::DefaultValue() const { return 1; } double HCMaskGrowth::MinimumValue() const { return 0; } double HCMaskGrowth::MaximumValue() const { return 15; } // ---------------------------------------------------------------------------- HCAutoExposures::HCAutoExposures( MetaProcess* P ) : MetaBoolean( P ) { TheHCAutoExposuresParameter = this; } IsoString HCAutoExposures::Id() const { return "autoExposures"; } bool HCAutoExposures::DefaultValue() const { return true; } // ---------------------------------------------------------------------------- HCRejectBlack::HCRejectBlack( MetaProcess* P ) : MetaBoolean( P ) { TheHCRejectBlackParameter = this; } IsoString HCRejectBlack::Id() const { return "rejectBlack"; } bool HCRejectBlack::DefaultValue() const { return true; } // ---------------------------------------------------------------------------- HCUseFittingRegion::HCUseFittingRegion( MetaProcess* P ) : MetaBoolean( P ) { TheHCUseFittingRegionParameter = this; } IsoString HCUseFittingRegion::Id() const { return "useFittingRegion"; } bool HCUseFittingRegion::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- HCFittingRectX0::HCFittingRectX0( MetaProcess* P ) : MetaInt32( P ) { TheHCFittingRectX0Parameter = this; } IsoString HCFittingRectX0::Id() const { return "fittingRectX0"; } double HCFittingRectX0::DefaultValue() const { return 0; } double HCFittingRectX0::MinimumValue() const { return 0; } double HCFittingRectX0::MaximumValue() const { return int32_max; } // ---------------------------------------------------------------------------- HCFittingRectY0::HCFittingRectY0( MetaProcess* P ) : MetaInt32( P ) { TheHCFittingRectY0Parameter = this; } IsoString HCFittingRectY0::Id() const { return "fittingRectY0"; } double HCFittingRectY0::DefaultValue() const { return 0; } double HCFittingRectY0::MinimumValue() const { return 0; } double HCFittingRectY0::MaximumValue() const { return int32_max; } // ---------------------------------------------------------------------------- HCFittingRectX1::HCFittingRectX1( MetaProcess* P ) : MetaInt32( P ) { TheHCFittingRectX1Parameter = this; } IsoString HCFittingRectX1::Id() const { return "fittingRectX1"; } double HCFittingRectX1::DefaultValue() const { return 0; } double HCFittingRectX1::MinimumValue() const { return 0; } double HCFittingRectX1::MaximumValue() const { return int32_max; } // ---------------------------------------------------------------------------- HCFittingRectY1::HCFittingRectY1( MetaProcess* P ) : MetaInt32( P ) { TheHCFittingRectY1Parameter = this; } IsoString HCFittingRectY1::Id() const { return "fittingRectY1"; } double HCFittingRectY1::DefaultValue() const { return 0; } double HCFittingRectY1::MinimumValue() const { return 0; } double HCFittingRectY1::MaximumValue() const { return int32_max; } // ---------------------------------------------------------------------------- HCGenerate64BitResult::HCGenerate64BitResult( MetaProcess* P ) : MetaBoolean( P ) { TheHCGenerate64BitResultParameter = this; } IsoString HCGenerate64BitResult::Id() const { return "generate64BitResult"; } bool HCGenerate64BitResult::DefaultValue() const { return true; } // ---------------------------------------------------------------------------- HCOutputMasks::HCOutputMasks( MetaProcess* P ) : MetaBoolean( P ) { TheHCOutputMasksParameter = this; } IsoString HCOutputMasks::Id() const { return "outputMasks"; } bool HCOutputMasks::DefaultValue() const { return true; } // ---------------------------------------------------------------------------- HCClosePreviousImages::HCClosePreviousImages( MetaProcess* P ) : MetaBoolean( P ) { TheHCClosePreviousImagesParameter = this; } IsoString HCClosePreviousImages::Id() const { return "closePreviousImages"; } bool HCClosePreviousImages::DefaultValue() const { return false; } // ---------------------------------------------------------------------------- } // pcl // ---------------------------------------------------------------------------- // EOF HDRCompositionParameters.cpp - Released 2016/02/21 20:22:43 UTC
10,721
3,418
// Copyright 2019- <dim-lang> // Apache License Version 2.0 #include "infra/Files.h" #include "infra/Log.h" #include <cerrno> #include <cstdio> #define BUF_SIZE 4096 namespace detail { FileInfo::FileInfo(const Cowstr &fileName) : fileName_(fileName), fp_(nullptr) {} FileInfo::~FileInfo() { if (fp_) { std::fclose(fp_); fp_ = nullptr; } } const Cowstr &FileInfo::fileName() const { return fileName_; } FileWriterImpl::FileWriterImpl(const Cowstr &fileName) : FileInfo(fileName) {} FileWriterImpl::~FileWriterImpl() { flush(); } void FileWriterImpl::reset(int offset) { std::fseek(fp_, offset, SEEK_SET); } int FileWriterImpl::flush() { if (buffer_.size() > 0) { buffer_.writefile(fp_); } return std::fflush(fp_) ? errno : 0; } int FileWriterImpl::write(const Cowstr &buf) { int r = buffer_.read(buf.rawstr(), buf.length()); if (buffer_.size() >= BUF_SIZE) { buffer_.writefile(fp_, BUF_SIZE); } return r; } int FileWriterImpl::writeln(const Cowstr &buf) { return write(buf) + write("\n"); } } // namespace detail FileReader::FileReader(const Cowstr &fileName) : detail::FileInfo(fileName) { fp_ = std::fopen(fileName.rawstr(), "r"); LOG_ASSERT(fp_, "fp_ is null, open fileName {} failed", fileName); } FileMode FileReader::mode() const { return FileMode::Read; } void FileReader::reset(int offset) { std::fseek(fp_, offset, SEEK_SET); } void FileReader::prepareFor(int n) { if (n <= 0) { return; } if (buffer_.size() < n) { int c = 0; do { c = buffer_.readfile(fp_, BUF_SIZE); if (buffer_.size() >= n) { break; } } while (c > 0); } } Cowstr FileReader::read(int n) { if (n <= 0) { return ""; } prepareFor(n); char *buf = new char[n + 1]; std::memset(buf, 0, n + 1); int c = buffer_.write(buf, n); Cowstr r(buf, c); delete[] buf; return r; } Cowstr FileReader::readall() { buffer_.readfile(fp_); char *buf = new char[buffer_.size() + 1]; std::memset(buf, 0, buffer_.size() + 1); int c = buffer_.write(buf, buffer_.size()); Cowstr r(buf, c); delete[] buf; return r; } Cowstr FileReader::readc() { prepareFor(1); char buf; int c = buffer_.write(&buf, 1); Cowstr r(&buf, c); return r; } char *FileReader::prepareUntil(char c) { char *linepos = nullptr; int n = 0; do { n = buffer_.readfile(fp_, BUF_SIZE); linepos = buffer_.search(c); if (linepos) { break; } } while (n > 0); return linepos; } Cowstr FileReader::readln() { char *linepos = prepareUntil('\n'); if (!linepos) { return ""; } int len = linepos - buffer_.begin() + 1; char *buf = new char[len + 1]; std::memset(buf, 0, len + 1); int c = buffer_.write(buf, len); Cowstr r(buf, c); delete[] buf; return r; } FileWriter::FileWriter(const Cowstr &fileName) : detail::FileWriterImpl(fileName) { fp_ = std::fopen(fileName.rawstr(), "w"); ASSERT(fp_, "error: cannot open file {}", fileName); } FileMode FileWriter::mode() const { return FileMode::Write; } void FileWriter::reset(int offset) { detail::FileWriterImpl::reset(offset); } FileAppender::FileAppender(const Cowstr &fileName) : detail::FileWriterImpl(fileName) { fp_ = std::fopen(fileName.rawstr(), "a"); LOG_ASSERT(fp_, "fp_ is null, open fileName {} failed", fileName); } void FileAppender::reset(int offset) { detail::FileWriterImpl::reset(offset); } FileMode FileAppender::mode() const { return FileMode::Append; }
3,468
1,320
/* * sdcard.c * * Created on: Sep 8, 2021 * Author: Danylo Ulianych */ #include <dirent.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <time.h> #include <sys/stat.h> #include "esp_log.h" #include "esp_err.h" #include "esp32-hal-log.h" #include "bsp_log.h" #include "sdcard.h" #include "record.h" #define SDCARD_USE_SPI #define SDCARD_ALLOCATION_UNIT_SIZE (16 * 1024) static int m_record_id = 0; const char *sdcard_mount_point = "/sd"; static char *m_sdcard_record_dir = NULL; static const char *TAG = "sdcard"; static int sdcard_count_dirs(char *dirpath); void sdcard_listdir(const char *name, int indent) { DIR *dir; struct dirent *entry; struct stat fstat; if (!(dir = opendir(name))) return; char path[512]; while ((entry = readdir(dir)) != NULL) { snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); if (entry->d_type == DT_DIR) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; printf("%*s[%s]\n", indent, "", entry->d_name); sdcard_listdir(path, indent + 2); } else { stat(path, &fstat); printf("%*s- %s: %ld bytes\n", indent, "", entry->d_name, fstat.st_size); } } closedir(dir); } static int sdcard_count_dirs(char *dirpath) { int dircnt = 0; DIR *directory; struct dirent *entry; directory = opendir(dirpath); if (directory == NULL) { return 0; } while ((entry = readdir(directory)) != NULL) { if (entry->d_type == DT_DIR) { /* a directory */ dircnt++; } } closedir(directory); return dircnt; } static int8_t sdcard_sdpfile_exists(uint32_t record_id) { char dirpath[128]; DIR *directory; struct dirent *entry; if (record_id == -1) record_id = m_record_id - 1; const char *sdp_pref = "SDP-"; snprintf(dirpath, sizeof(dirpath), "%s/RECORDS/%03d", sdcard_mount_point, record_id); directory = opendir(dirpath); if (directory == NULL) { return 0; } int8_t sdp_exists = 0; while ((entry = readdir(directory)) != NULL) { if (entry->d_type == DT_REG /* a regular file */ && strstr(entry->d_name, sdp_pref) == entry->d_name) { /* a prefix match */ sdp_exists = 1; break; } } closedir(directory); return sdp_exists; } static void sdcard_remove_record_files(int record_id) { char dirpath[300]; DIR *directory; struct dirent *entry; if (record_id == -1) record_id = m_record_id - 1; snprintf(dirpath, sizeof(dirpath), "%s/RECORDS/%03d", sdcard_mount_point, record_id); directory = opendir(dirpath); if (directory == NULL) { return; } while ((entry = readdir(directory)) != NULL) { if (entry->d_type == DT_REG ) { /* a regular file */ snprintf(dirpath, sizeof(dirpath), "%s/RECORDS/%03d/%s", sdcard_mount_point, record_id, entry->d_name); remove(dirpath); } } closedir(directory); BSP_LOGI(TAG, "Removed files in record %d", record_id); } static esp_err_t sdcard_get_sdpfile_path(char *path, int record_id) { char dirpath[300]; DIR *directory; struct dirent *entry; if (record_id == -1) record_id = m_record_id - 1; const char *sdp_pref = "SDP-"; snprintf(dirpath, sizeof(dirpath), "%s/RECORDS/%03d", sdcard_mount_point, record_id); directory = opendir(dirpath); if (directory == NULL) { return ESP_ERR_NOT_FOUND; } int sdp_cnt = 0; while ((entry = readdir(directory)) != NULL) { if (entry->d_type == DT_REG /* a regular file */ && strstr(entry->d_name, sdp_pref) == entry->d_name) { /* a prefix match */ // the files are sorted sdp_cnt++; } } if (sdp_cnt == 0) { return ESP_ERR_NOT_FOUND; } sprintf(path, "%s/%s%03d.BIN", dirpath, sdp_pref, sdp_cnt - 1); closedir(directory); return ESP_OK; } int sdcard_get_record_id() { return m_record_id; } void sdcard_create_record_dir() { char rec_folder[128]; struct stat dstat = { 0 }; snprintf(rec_folder, sizeof(rec_folder), "%s/RECORDS", sdcard_mount_point); if (stat(rec_folder, &dstat) == -1) { mkdir(rec_folder, 0700); } m_record_id = sdcard_count_dirs(rec_folder); if (m_record_id > 0) { m_record_id--; if (sdcard_sdpfile_exists(m_record_id)) { // file exists; increment ID m_record_id++; } sdcard_get_record_duration(-1); // remove logs, BMP files, etc. sdcard_remove_record_files(m_record_id); if (m_record_id >= 1000) { // SD cards don't like long paths m_record_id = 0; } } snprintf(rec_folder, sizeof(rec_folder), "%s/RECORDS/%03d", sdcard_mount_point, m_record_id); if (stat(rec_folder, &dstat) == -1) { mkdir(rec_folder, 0700); } char *rec_dir_heap = (char*) malloc(strlen(rec_folder)); strcpy(rec_dir_heap, rec_folder); if (m_sdcard_record_dir != NULL) { // clean-up from the previous call free(m_sdcard_record_dir); } m_sdcard_record_dir = rec_dir_heap; } const char* sdcard_get_record_dir() { return (const char*) m_sdcard_record_dir; } esp_err_t sdcard_print_content(const char *fpath) { FILE *f = fopen(fpath, "r"); if (f == NULL) { BSP_LOGW(TAG, "No such file: '%s'", fpath); return ESP_ERR_NOT_FOUND; } printf("\n>>> BEGIN '%s'\n", fpath); int c; while ((c = fgetc(f)) != EOF) { printf("%c", c); } fclose(f); printf("<<< END '%s'\n\n", fpath); return ESP_OK; } int64_t sdcard_get_record_duration(int record_id) { char fpath[512]; if (record_id == -1) record_id = m_record_id - 1; if (sdcard_get_sdpfile_path(fpath, record_id) != ESP_OK) { return 0; } FILE *f = fopen(fpath, "r"); if (f == NULL) { return 0; } fseek(f, 0L, SEEK_END); long int fsize = ftell(f); if (fsize % sizeof(SDPRecord) != 0) { BSP_LOGW(TAG, "%s file is corrupted", fpath); } long int records_cnt = fsize / sizeof(SDPRecord); fseek(f, (records_cnt - 1) * sizeof(SDPRecord), SEEK_SET); SDPRecord record; fread(&record, sizeof(SDPRecord), 1, f); fclose(f); time_t seconds = (time_t) (record.time / 1000000); BSP_LOGI(TAG, "Record %d ended %s", record_id, ctime(&seconds)); return record.time; } esp_err_t sdcard_print_content_prev(char *fname) { char fpath[128]; if (m_record_id == 0) { return ESP_ERR_NOT_FOUND; } snprintf(fpath, sizeof(fpath), "%s/RECORDS/%03d/%s", sdcard_mount_point, m_record_id - 1, fname); return sdcard_print_content(fpath); }
6,303
2,773
/*! force-random-dither.cpp -- Generate a dither matrix using the force-random-dither method from: W. Purgathofer, R. F. Tobler and M. Geiler. "Forced random dithering: improved threshold matrices for ordered dithering" Image Processing, 1994. Proceedings. ICIP-94., IEEE International Conference, Austin, TX, 1994, pp. 1032-1035 vol.2. doi: 10.1109/ICIP.1994.413512 */ // // Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE.txt file. // #include <iostream> #include "array2d.h" #include <nanogui/vector.h> #include <vector> #include <random> #include <algorithm> // std::random_shuffle #include <ctime> // std::time #include <cstdlib> // std::rand, std::srand using nanogui::Vector2i; using namespace std; const int Sm = 128; const int Smk = Sm*Sm; double toroidalMinimumDistance(const Vector2i & a, const Vector2i & b) { int x0 = min(a.x(), b.x()); int x1 = max(a.x(), b.x()); int y0 = min(a.y(), b.y()); int y1 = max(a.y(), b.y()); double deltaX = min(x1-x0, x0+Sm-x1); double deltaY = min(y1-y0, y0+Sm-y1); return sqrt(deltaX*deltaX + deltaY*deltaY); } double force(double r) { return exp(-sqrt(2*r)); } int main(int, char **) { srand(unsigned ( std::time(0) ) ); std::mt19937 g_rand(unsigned ( std::time(0) ) ); vector<Vector2i> freeLocations; Array2Dd M = Array2Dd(Sm,Sm,0.0); Array2Dd forceField = Array2Dd(Sm,Sm,0.0); // initialize free locations for (int y = 0; y < Sm; ++y) for (int x = 0; x < Sm; ++x) freeLocations.push_back(Vector2i(x,y)); for (int ditherValue = 0; ditherValue < Smk; ++ditherValue) { shuffle(freeLocations.begin(), freeLocations.end(), g_rand); double minimum = 1e20f; Vector2i minimumLocation(0,0); // int halfP = freeLocations.size(); int halfP = min(max(1, (int)sqrt(freeLocations.size()*3/4)), (int)freeLocations.size()); // int halfP = min(10, (int)freeLocations.size()); for (int i = 0; i < halfP; ++i) { const Vector2i & location = freeLocations[i]; if (forceField(location.x(), location.y()) < minimum) { minimum = forceField(location.x(), location.y()); minimumLocation = location; } } Vector2i cell(0,0); for (cell.y() = 0; cell.y() < Sm; ++cell.y()) for (cell.x() = 0; cell.x() < Sm; ++cell.x()) { double r = toroidalMinimumDistance(cell, minimumLocation); forceField(cell.x(), cell.y()) += force(r); } freeLocations.erase(remove(freeLocations.begin(), freeLocations.end(), minimumLocation), freeLocations.end()); M(minimumLocation.x(), minimumLocation.y()) = ditherValue; // if (ditherValue % 16 == 0) // { // std::stringstream ss; // ss << ditherValue; // writeEXR("forceField-" + ss.str() + ".exr", forceField/(ditherValue+1)); // } } // std::cout << M << std::endl; cout << "unsigned dither_matrix[" << Smk << "] = \n{\n "; printf("%5d", (int)M(0)); for (int i = 1; i < M.size(); ++i) { cout << ", "; if (i % Sm == 0) cout << endl << " "; printf("%5d", (int)M(i)); } cout << "\n};" << endl; return 0; }
3,146
1,351
/* * * Copyright (C) 1994-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmdata * * Author: Marco Eichelberg * * Purpose: singleton class that registers RLE decoder. * */ #include "dcmtk/config/osconfig.h" #include "dcmtk/dcmdata/dcrledrg.h" #include "dcmtk/dcmdata/dccodec.h" /* for DcmCodecStruct */ #include "dcmtk/dcmdata/dcrleccd.h" /* for class DcmRLECodecDecoder */ #include "dcmtk/dcmdata/dcrlecp.h" /* for class DcmRLECodecParameter */ // initialization of static members OFBool DcmRLEDecoderRegistration::registered = OFFalse; DcmRLECodecParameter *DcmRLEDecoderRegistration::cp = NULL; DcmRLECodecDecoder *DcmRLEDecoderRegistration::codec = NULL; void DcmRLEDecoderRegistration::registerCodecs( OFBool pCreateSOPInstanceUID, OFBool pReverseDecompressionByteOrder) { if (! registered) { cp = new DcmRLECodecParameter( pCreateSOPInstanceUID, 0, OFTrue, OFFalse, pReverseDecompressionByteOrder); if (cp) { codec = new DcmRLECodecDecoder(); if (codec) DcmCodecList::registerCodec(codec, NULL, cp); registered = OFTrue; } } } void DcmRLEDecoderRegistration::cleanup() { if (registered) { DcmCodecList::deregisterCodec(codec); delete codec; delete cp; registered = OFFalse; #ifdef DEBUG // not needed but useful for debugging purposes codec = NULL; cp = NULL; #endif } }
1,656
614
// slang-emit-precedence.cpp #include "slang-emit-precedence.h" namespace Slang { #define SLANG_OP_INFO_EXPAND(op, name, precedence) {name, kEPrecedence_##precedence##_Left, kEPrecedence_##precedence##_Right, }, /* static */const EmitOpInfo EmitOpInfo::s_infos[int(EmitOp::CountOf)] = { SLANG_OP_INFO(SLANG_OP_INFO_EXPAND) }; } // namespace Slang
355
149
#include "I2CBuffer.h"
27
16
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "runtime/binaryen/module/wasm_module_instance_impl.hpp" #include <binaryen/wasm.h> namespace kagome::runtime::binaryen { WasmModuleInstanceImpl::WasmModuleInstanceImpl( std::shared_ptr<wasm::Module> parent, const std::shared_ptr<RuntimeExternalInterface> &rei) : parent_{std::move(parent)}, rei_{rei}, module_instance_{ std::make_unique<wasm::ModuleInstance>(*parent_, rei.get())} { BOOST_ASSERT(parent_); BOOST_ASSERT(rei_); BOOST_ASSERT(module_instance_); } wasm::Literal WasmModuleInstanceImpl::callExportFunction( wasm::Name name, const wasm::LiteralList &arguments) { return module_instance_->callExport(name, arguments); } wasm::Literal WasmModuleInstanceImpl::getExportGlobal(wasm::Name name) { return module_instance_->getExport(name); } } // namespace kagome::runtime::binaryen
988
326
#pragma once #include "Record.hpp" namespace oless { namespace excel { namespace records { class ContinueRecord : public Record { public: ContinueRecord(IRecordParser* p, unsigned short type, std::vector<uint8_t> data) : Record(type, data) { Record* r = p->GetPrevRecordNotOfType(type); r->Data.insert(r->Data.end(), data.begin(), data.end()); //TODO: it is problematic to do this during parsing....need a better way //if (IReParseable* pr = dynamic_cast<IReParseable*>(r)) { // pr->ReParse(p); //} } }; } } }
575
241
#include "math.h" #include "mex.h" #define MAX(a, b) (a > b ? a:b) #define MIN(a, b) (a > b ? b:a) void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // Check for proper number of input and output arguments //nargineqchk(nrhs, 2); //nargouteqchk(nlhs, 2); // Check for input arguments type //argvectorchk(prhs, 0); //argvectorchk(prhs, 1); double* v = mxGetPr(prhs[0]); double* sz = mxGetPr(prhs[1]); double* res, *normVec; int sz_len = MAX(mxGetM(prhs[1]), mxGetN(prhs[1])); if(MIN(mxGetM(prhs[1]), mxGetN(prhs[1]) == 0)) { mexErrMsgTxt("sz can not be empty!"); } int v_len = MAX(mxGetM(prhs[0]), mxGetN(prhs[0])); int dim1 = (int)(sz[0]); int dim2 = (int)(sz[1]); int dim3 = (int)(sz[2]); int dim4 = (int)(sz[3]); int nnz = dim1*dim2*dim3*dim4; int number_of_dims = 4; mwSize dims[4]; dims[0] = dim1; dims[1] = dim2; dims[2] = dim3; dims[3] = dim4; int sum_sz = dim1+dim2+dim3+dim4; int rank = v_len / sum_sz; int U_len = dim1 * dim2 * dim3 * dim4; plhs[0] = mxCreateNumericArray(number_of_dims, (const mwSize*)dims, mxDOUBLE_CLASS, mxREAL); res = mxGetPr(plhs[0]); // normVec = mxGetPr(plhs[1]); double *i_start = v; double *j_start = v + dim1; double *k_start = v + dim1 + dim2; double *s_start = v + dim1 + dim2 + dim3; double tmp1, tmp2; for (int r = 0; r < rank; r ++) { for (double *s = s_start; s < s_start + dim4; s ++) { for (double *k = k_start; k < k_start + dim3; k ++) { tmp1 = *s * *k; for (double *j = j_start; j < j_start + dim2; j ++) { tmp2 = *j * tmp1; for (double *i = i_start; i < i_start + dim1; i ++) { *(res++) += *i * tmp2; } } } } i_start += sum_sz; j_start += sum_sz; k_start += sum_sz; s_start += sum_sz; res -= nnz; } }
1,955
901
#ifdef PEGASUS_OS_AIX #ifndef __UNIX_VLANENDPOINTSETTINGDATA_PRIVATE_H #define __UNIX_VLANENDPOINTSETTINGDATA_PRIVATE_H #endif #endif
140
76
/// @file #include "hwlib.hpp" #include "DS3231.hpp" /// \brief /// Test /// \details /// This program tests most of the functionality of the DS3231 Real Time clock. int main( void ){ namespace target = hwlib::target; auto scl = target::pin_oc( target::pins::d8 ); auto sda = target::pin_oc( target::pins::d9 ); auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda(scl, sda); auto clock = DS3231(i2c_bus); auto time = timeData(15, 20, 10); auto lastTime = timeData(5, 30); auto bigTime = timeData(50, 60, 80); //Uncomment is time is allowed to get overwritten //clock.setTime(14, 20); //clock.setDate(5, 7, 7, 2019); hwlib::wait_ms(1000); hwlib::cout << "---------------------------------TIME------------------------------" << hwlib::endl << hwlib::endl; hwlib::cout << hwlib::left << hwlib::boolalpha << hwlib::setw(45) << "Initialization: " << ((time.getHours() == 15) && time.getMinutes() == 20 && time.getSeconds() == 10) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Initialization Handling: " << ((bigTime.getHours() == 0) && bigTime.getMinutes() == 0 && bigTime.getSeconds() == 0) << hwlib::endl; time.setTime(11, 40, 55); hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting: " << ((time.getHours() == 11) && time.getMinutes() == 40 && time.getSeconds() == 55) << hwlib::endl; time.setTime(80, 90, 100); hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Setting Handling: " << (time == timeData(0, 0, 0)) << hwlib::endl; time.setTime(10, 30); hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Addition: " << time << " + " << lastTime << " = " << (time + lastTime) << hwlib::boolalpha << " " << ((time + lastTime) == timeData(16, 0, 0)) << hwlib::endl; lastTime.setHours(18); lastTime.setMinutes(15); lastTime.setSeconds(55); hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << time << " + " << lastTime << " = " << (time + lastTime) << hwlib::boolalpha << " " << ((time + lastTime) == timeData(4, 45, 55)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << timeData(0, 0) << " + " << timeData(0, 0) << " = " << (timeData(0+0, 0+0)) << " true" << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << timeData(23, 59) << " + " << timeData(23, 59) << " = " << (timeData(23, 59) + timeData(23, 59)) << " true" << hwlib::endl; lastTime.setTime(5, 30); time.setTime(10, 30); hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Setting and Substraction: " << time << " - " << lastTime << " = " << (time - lastTime) << hwlib::boolalpha << " " << ((time - lastTime) == timeData(5, 0, 0)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << lastTime << " - " << time << " = " << (lastTime - time) << hwlib::boolalpha << " " << ((lastTime - time) == timeData(19, 0, 0)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << timeData(23, 59) << " - " << timeData(23, 59) << " = " << (timeData(23, 59) - timeData(23, 59)) << " true" << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << timeData(0, 15) << " - " << timeData(0, 30) << " = " << (timeData(0, 15) - timeData(0, 30)) << " true" << hwlib::endl; lastTime.setTime(5, 30); time.setTime(10, 30); hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " < " << lastTime << " = " << (time < lastTime) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " < " << timeData(11, 30, 10) << " = " << (timeData(11, 30) < timeData(11, 30, 10)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " <= " << lastTime << " = " << (time <= lastTime) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " > " << lastTime << " = " << (time > lastTime) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " >= " << lastTime << " = " << (time >= lastTime) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " >= " << timeData(11, 30) << " = " << (timeData(11, 30) >= timeData(11, 30)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " <= " << timeData(11, 30) << " = " << (timeData(11, 30) <= timeData(11, 30)) << hwlib::endl; hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Equality: " << time << " == " << lastTime << " = " << (time == lastTime) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Unequality: " << lastTime << " != " << time << " = " << (lastTime != time) << hwlib::endl << hwlib::endl; hwlib::cout << "---------------------------------DATE------------------------------" << hwlib::endl << hwlib::endl; auto date = dateData(7, 30, 6, 2019); auto lastDate = dateData(10, 35, 14, 2019); hwlib::cout << hwlib::left << hwlib::setw(45) << "Initialization: " << (date.getWeekDay() == 7 && date.getMonthDay() == 30 && date.getMonth() == 6 && date.getYear() == 2019) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Initialization Handling: " << (lastDate.getWeekDay() == 1 && lastDate.getMonthDay() == 1 && lastDate.getMonth() == 1 && lastDate.getYear() == 2019) << hwlib::endl; lastDate.setDate(7, 30, 6, 2019); hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting: " << (lastDate.getWeekDay() == 7 && lastDate.getMonthDay() == 30 && lastDate.getMonth() == 6 && lastDate.getYear() == 2019) << hwlib::endl; lastDate.setDate(80, 90, 100, 2019); hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Setting Handling: " << (lastDate.getWeekDay() == 1 && lastDate.getMonthDay() == 1 && lastDate.getMonth() == 1 && lastDate.getYear() == 2019) << hwlib::endl; date.setDate(1, 1, 1, 2019); lastDate.setDate(7, 30, 6, 0); hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Addition: " << date.getWeekDay() << ", " << date << " + " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date + lastDate) << hwlib::boolalpha << " " << ((date + lastDate) == dateData(1, 1, 8, 2019)) << hwlib::endl; lastDate.setWeekDay(5); lastDate.setMonthDay(15); lastDate.setMonth(8); lastDate.setYear(2000); hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting and Addition: " << date.getWeekDay() << ", " << date << " + " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date + lastDate) << hwlib::boolalpha << " " << ((date + lastDate) == dateData(6, 16, 9, 4019)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << dateData(6, 20, 12, 2019) << " + " << dateData(6, 20, 5, 0) << " = " << (dateData(6, 20, 5, 0) + dateData(6, 20, 12, 2019)) << hwlib::boolalpha << " true" << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << dateData(1, 1, 1, 2000) << " + " << dateData(1, 1, 1, 0) << " = " << (dateData(1, 1, 1, 2000) + dateData(1, 1, 1, 0)) << hwlib::boolalpha << " true" << hwlib::endl; date.setDate(5, 8, 10, 2019); lastDate.setDate(4, 30, 8, 2000); hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Setting and Substraction: " << date.getWeekDay() << ", " << date << " - " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date - lastDate) << hwlib::boolalpha << " " << ((date - lastDate) == dateData(1, 8, 1, 19)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << lastDate.getWeekDay() << ", " << lastDate << " - " << date.getWeekDay() << ", " << date << " = " << (lastDate - date) << hwlib::boolalpha << " " << ((lastDate - date) == dateData(6, 22, 10, 0)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << dateData(6, 20, 12, 2019) << " - " << dateData(6, 20, 5, 0) << " = " << (dateData(6, 20, 12, 0) - dateData(6, 20, 5, 2019)) << hwlib::boolalpha << " true" << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << dateData(6, 1, 1, 2019) << " - " << dateData(6, 6, 6, 0) << " = " << (dateData(6, 1, 1, 2019) - dateData(6, 6, 6, 0)) << hwlib::boolalpha << " true" << hwlib::endl; lastTime.setTime(5, 30); time.setTime(10, 30); hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " < " << lastDate << " = " << (date < lastDate) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " <= " << lastDate << " = " << (date <= lastDate) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " <= " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) <= dateData(1, 1, 12, 2019)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " > " << lastDate << " = " << (date > lastDate) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " > " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) > dateData(1, 1, 12, 2019)) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " >= " << lastDate << " = " << (date >= lastDate) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " > " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) > dateData(1, 1, 12, 2019)) << hwlib::endl; hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Equality: " << date.getWeekDay() << ", " << date << " == " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date == lastDate) << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Unequality: " << date.getWeekDay() << ", " << date << " != " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date != lastDate) << hwlib::endl << hwlib::endl; hwlib::cout << "-------------------------------DS3231--------------------------------" << hwlib::endl << hwlib::endl; hwlib::cout << hwlib::left << hwlib::setw(45) << "Initialization: " << (clock.getAddress() == 0x68) << hwlib::endl; hwlib::cout << hwlib::endl; for(unsigned int i = 0; i < 3; i++){ time = clock.getTime(); date = clock.getDate(); hwlib::cout << "Time: " << clock.getTime() << hwlib::endl; hwlib::cout << "Temperature: " << int(clock.getTemperature() * 10) << hwlib::endl; hwlib::cout << "Date: " << clock.getDate() << hwlib::endl << hwlib::endl; hwlib::wait_ms(3000); } hwlib::cout << hwlib::endl; //Uncomment if time is allowed to get lost. You'll have to set it again later. //hwlib::cout << hwlib::left << hwlib::setw(45) << "Set time to 0:0:0 : "; //clock.setTime(0, 0, 0); //hwlib::cout << (clock.getTime() == timeData(0, 0, 0)) << hwlib::endl; auto curTime = timeData(); for(unsigned int i = 0; i < 3; i++){ hwlib::cout << "Time: " << clock.getTime() << hwlib::endl; hwlib::cout << "Temperature: " << int(clock.getTemperature() * 10) << hwlib::endl; hwlib::cout << "Date: " << clock.getDate() << hwlib::endl << hwlib::endl; curTime = clock.getTime(); curTime.setSeconds(curTime.getSeconds() + 10); hwlib::cout << "Time to Trigger: " << curTime << hwlib::endl; clock.clearAlarm(1); clock.changeFirstAlarm(curTime, dateData(0, 0, 1, 2019)); clock.setFirstAlarm(14); hwlib::cout << "Alarm set, should go in 10 seconds: "; hwlib::wait_ms(30); while(clock.checkAlarms() == 0){ hwlib::wait_ms(1000); hwlib::cout << clock.getTime() << hwlib::endl; } hwlib::cout << "Triggered!" << hwlib::endl; } }
11,814
5,275
//********************************************************* // IPF_Setup.cpp - initialize the IPF classes //********************************************************* #include "PopSyn.hpp" //--------------------------------------------------------- // IPF_Setup //--------------------------------------------------------- void PopSyn::IPF_Setup (Household_Model *model_ptr) { int i, attributes; Attribute_Type *at_ptr; //---- clear memory ---- ipf_data.Clear (); //---- copy the attribute types ---- attributes = model_ptr->Num_Attributes (); for (i=1; i <= attributes; i++) { at_ptr = model_ptr->Attribute (i); if (!ipf_data.Add_Attribute (at_ptr->Num_Types ())) { Error ("Adding IPF Attribute"); } } //---- set data cells ---- if (!ipf_data.Set_Cells ()) { Error ("Creating IPF Cells"); } //---- initialize the stage2 process ---- if (!stage2_data.Set_Stage_Two (&ipf_data)) { Error ("Creating Stage2 Data"); } //---- sum the zone targets and normalize the weights ---- model_ptr->Sum_Targets (); }
1,047
338
/** * Copyright (c) 2022 Suilteam, Carter Mbotho * * This library is free software; you can redistribute it and/or modify it * under the terms of the MIT license. See LICENSE for details. * * @author Carter * @date 2022-03-12 */ #include "suil/utils/console.hpp" namespace suil::Console { void cprint(uint8_t color, int bold, const char *str) { if (color >= 0 && color <= CYAN) printf("\033[%s3%dm", (bold ? "1;" : ""), color); (void) printf("%s", str); printf("\033[0m"); } void cprintv(uint8_t color, int bold, const char *fmt, va_list args) { if (color > 0 && color <= CYAN) printf("\033[%s3%dm", (bold ? "1;" : ""), color); (void) vprintf(fmt, args); printf("\033[0m"); } void cprintf(uint8_t color, int bold, const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(color, bold, fmt, args); va_end(args); } void println(const char *fmt, ...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); printf("\n"); } void red(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(RED, 0, fmt, args); va_end(args); } void blue(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(BLUE, 0, fmt, args); va_end(args); } void green(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(GREEN, 0, fmt, args); va_end(args); } void yellow(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(YELLOW, 0, fmt, args); va_end(args); } void magenta(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(MAGENTA, 0, fmt, args); va_end(args); } void cyan(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(CYAN, 0, fmt, args); va_end(args); } void log(const char *fmt, ...) { va_list args; va_start(args, fmt); printf(fmt, args); printf("\n"); printf("\n"); va_end(args); } void info(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(GREEN, 0, fmt, args); printf("\n"); va_end(args); } void error(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(RED, 0, fmt, args); printf("\n"); va_end(args); } void warn(const char *fmt, ...) { va_list args; va_start(args, fmt); cprintv(YELLOW, 0, fmt, args); printf("\n"); va_end(args); } }
2,799
1,015
/** * $File: JCSUEGameModeBase.cpp $ * $Date: 2017-03-01 $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright (c) 2017 by Shen, Jen-Chieh $ */ #include "JCSUEGameModeBase.h" #include "JCSUE.h"
297
123
#include <sstream> #include "CSE.h" #include "CodeGen_Internal.h" #include "CodeGen_Posix.h" #include "ConciseCasts.h" #include "Debug.h" #include "IREquality.h" #include "IRMatch.h" #include "IROperator.h" #include "IRPrinter.h" #include "LLVM_Headers.h" #include "Simplify.h" #include "Substitute.h" #include "Util.h" namespace Halide { namespace Internal { using std::ostringstream; using std::pair; using std::string; using std::vector; using namespace Halide::ConciseCasts; using namespace llvm; #if defined(WITH_ARM) || defined(WITH_AARCH64) namespace { /** A code generator that emits ARM code from a given Halide stmt. */ class CodeGen_ARM : public CodeGen_Posix { public: /** Create an ARM code generator for the given arm target. */ CodeGen_ARM(const Target &); protected: using CodeGen_Posix::visit; /** Assuming 'inner' is a function that takes two vector arguments, define a wrapper that * takes one vector argument and splits it into two to call inner. */ llvm::Function *define_concat_args_wrapper(llvm::Function *inner, const string &name); void init_module() override; /** Nodes for which we want to emit specific neon intrinsics */ // @{ void visit(const Cast *) override; void visit(const Sub *) override; void visit(const Min *) override; void visit(const Max *) override; void visit(const Store *) override; void visit(const Load *) override; void visit(const Call *) override; void visit(const LT *) override; void visit(const LE *) override; void codegen_vector_reduce(const VectorReduce *, const Expr &) override; // @} /** Various patterns to peephole match against */ struct Pattern { string intrin; ///< Name of the intrinsic Expr pattern; ///< The pattern to match against Pattern() = default; Pattern(const string &intrin, Expr p) : intrin(intrin), pattern(std::move(p)) { } }; vector<Pattern> casts, calls, averagings, negations; string mcpu() const override; string mattrs() const override; bool use_soft_float_abi() const override; int native_vector_bits() const override; // NEON can be disabled for older processors. bool neon_intrinsics_disabled() { return target.has_feature(Target::NoNEON); } }; CodeGen_ARM::CodeGen_ARM(const Target &target) : CodeGen_Posix(target) { // RADDHN - Add and narrow with rounding // These must come before other narrowing rounding shift patterns casts.emplace_back("rounding_add_narrow", i8(rounding_shift_right(wild_i16x_ + wild_i16x_, 8))); casts.emplace_back("rounding_add_narrow", u8(rounding_shift_right(wild_u16x_ + wild_u16x_, 8))); casts.emplace_back("rounding_add_narrow", i16(rounding_shift_right(wild_i32x_ + wild_i32x_, 16))); casts.emplace_back("rounding_add_narrow", u16(rounding_shift_right(wild_u32x_ + wild_u32x_, 16))); casts.emplace_back("rounding_add_narrow", i32(rounding_shift_right(wild_i64x_ + wild_i64x_, 32))); casts.emplace_back("rounding_add_narrow", u32(rounding_shift_right(wild_u64x_ + wild_u64x_, 32))); // RSUBHN - Add and narrow with rounding // These must come before other narrowing rounding shift patterns casts.emplace_back("rounding_sub_narrow", i8(rounding_shift_right(wild_i16x_ - wild_i16x_, 8))); casts.emplace_back("rounding_sub_narrow", u8(rounding_shift_right(wild_u16x_ - wild_u16x_, 8))); casts.emplace_back("rounding_sub_narrow", i16(rounding_shift_right(wild_i32x_ - wild_i32x_, 16))); casts.emplace_back("rounding_sub_narrow", u16(rounding_shift_right(wild_u32x_ - wild_u32x_, 16))); casts.emplace_back("rounding_sub_narrow", i32(rounding_shift_right(wild_i64x_ - wild_i64x_, 32))); casts.emplace_back("rounding_sub_narrow", u32(rounding_shift_right(wild_u64x_ - wild_u64x_, 32))); // QDMULH - Saturating doubling multiply keep high half calls.emplace_back("qdmulh", mul_shift_right(wild_i16x_, wild_i16x_, 15)); calls.emplace_back("qdmulh", mul_shift_right(wild_i32x_, wild_i32x_, 31)); // QRDMULH - Saturating doubling multiply keep high half with rounding calls.emplace_back("qrdmulh", rounding_mul_shift_right(wild_i16x_, wild_i16x_, 15)); calls.emplace_back("qrdmulh", rounding_mul_shift_right(wild_i32x_, wild_i32x_, 31)); // RSHRN - Rounding shift right narrow (by immediate in [1, output bits]) casts.emplace_back("rounding_shift_right_narrow", i8(rounding_shift_right(wild_i16x_, wild_u16_))); casts.emplace_back("rounding_shift_right_narrow", u8(rounding_shift_right(wild_u16x_, wild_u16_))); casts.emplace_back("rounding_shift_right_narrow", u8(rounding_shift_right(wild_i16x_, wild_u16_))); casts.emplace_back("rounding_shift_right_narrow", i16(rounding_shift_right(wild_i32x_, wild_u32_))); casts.emplace_back("rounding_shift_right_narrow", u16(rounding_shift_right(wild_u32x_, wild_u32_))); casts.emplace_back("rounding_shift_right_narrow", u16(rounding_shift_right(wild_i32x_, wild_u32_))); casts.emplace_back("rounding_shift_right_narrow", i32(rounding_shift_right(wild_i64x_, wild_u64_))); casts.emplace_back("rounding_shift_right_narrow", u32(rounding_shift_right(wild_u64x_, wild_u64_))); casts.emplace_back("rounding_shift_right_narrow", u32(rounding_shift_right(wild_i64x_, wild_u64_))); // SHRN - Shift right narrow (by immediate in [1, output bits]) casts.emplace_back("shift_right_narrow", i8(wild_i16x_ >> wild_u16_)); casts.emplace_back("shift_right_narrow", u8(wild_u16x_ >> wild_u16_)); casts.emplace_back("shift_right_narrow", i16(wild_i32x_ >> wild_u32_)); casts.emplace_back("shift_right_narrow", u16(wild_u32x_ >> wild_u32_)); casts.emplace_back("shift_right_narrow", i32(wild_i64x_ >> wild_u64_)); casts.emplace_back("shift_right_narrow", u32(wild_u64x_ >> wild_u64_)); // SQRSHL, UQRSHL - Saturating rounding shift left (by signed vector) // TODO: We need to match rounding shift right, and negate the RHS. // SQRSHRN, SQRSHRUN, UQRSHRN - Saturating rounding narrowing shift right narrow (by immediate in [1, output bits]) casts.emplace_back("saturating_rounding_shift_right_narrow", i8_sat(rounding_shift_right(wild_i16x_, wild_u16_))); casts.emplace_back("saturating_rounding_shift_right_narrow", u8_sat(rounding_shift_right(wild_u16x_, wild_u16_))); casts.emplace_back("saturating_rounding_shift_right_narrow", u8_sat(rounding_shift_right(wild_i16x_, wild_u16_))); casts.emplace_back("saturating_rounding_shift_right_narrow", i16_sat(rounding_shift_right(wild_i32x_, wild_u32_))); casts.emplace_back("saturating_rounding_shift_right_narrow", u16_sat(rounding_shift_right(wild_u32x_, wild_u32_))); casts.emplace_back("saturating_rounding_shift_right_narrow", u16_sat(rounding_shift_right(wild_i32x_, wild_u32_))); casts.emplace_back("saturating_rounding_shift_right_narrow", i32_sat(rounding_shift_right(wild_i64x_, wild_u64_))); casts.emplace_back("saturating_rounding_shift_right_narrow", u32_sat(rounding_shift_right(wild_u64x_, wild_u64_))); casts.emplace_back("saturating_rounding_shift_right_narrow", u32_sat(rounding_shift_right(wild_i64x_, wild_u64_))); // SQSHL, UQSHL, SQSHLU - Saturating shift left by signed register. for (const Expr &rhs : {wild_i8x_, wild_u8x_}) { casts.emplace_back("saturating_shift_left", i8_sat(widening_shift_left(wild_i8x_, rhs))); casts.emplace_back("saturating_shift_left", u8_sat(widening_shift_left(wild_u8x_, rhs))); casts.emplace_back("saturating_shift_left", u8_sat(widening_shift_left(wild_i8x_, rhs))); } for (const Expr &rhs : {wild_i16x_, wild_u16x_}) { casts.emplace_back("saturating_shift_left", i16_sat(widening_shift_left(wild_i16x_, rhs))); casts.emplace_back("saturating_shift_left", u16_sat(widening_shift_left(wild_u16x_, rhs))); casts.emplace_back("saturating_shift_left", u16_sat(widening_shift_left(wild_i16x_, rhs))); } for (const Expr &rhs : {wild_i32x_, wild_u32x_}) { casts.emplace_back("saturating_shift_left", i32_sat(widening_shift_left(wild_i32x_, rhs))); casts.emplace_back("saturating_shift_left", u32_sat(widening_shift_left(wild_u32x_, rhs))); casts.emplace_back("saturating_shift_left", u32_sat(widening_shift_left(wild_i32x_, rhs))); } // SQSHRN, UQSHRN, SQRSHRUN Saturating narrowing shift right by an (by immediate in [1, output bits]) casts.emplace_back("saturating_shift_right_narrow", i8_sat(wild_i16x_ >> wild_u16_)); casts.emplace_back("saturating_shift_right_narrow", u8_sat(wild_u16x_ >> wild_u16_)); casts.emplace_back("saturating_shift_right_narrow", u8_sat(wild_i16x_ >> wild_u16_)); casts.emplace_back("saturating_shift_right_narrow", i16_sat(wild_i32x_ >> wild_u32_)); casts.emplace_back("saturating_shift_right_narrow", u16_sat(wild_u32x_ >> wild_u32_)); casts.emplace_back("saturating_shift_right_narrow", u16_sat(wild_i32x_ >> wild_u32_)); casts.emplace_back("saturating_shift_right_narrow", i32_sat(wild_i64x_ >> wild_u64_)); casts.emplace_back("saturating_shift_right_narrow", u32_sat(wild_u64x_ >> wild_u64_)); casts.emplace_back("saturating_shift_right_narrow", u32_sat(wild_i64x_ >> wild_u64_)); // SRSHL, URSHL - Rounding shift left (by signed vector) // These are already written as rounding_shift_left // SRSHR, URSHR - Rounding shift right (by immediate in [1, output bits]) // These patterns are almost identity, we just need to strip off the broadcast. // SSHLL, USHLL - Shift left long (by immediate in [0, output bits - 1]) // These patterns are almost identity, we just need to strip off the broadcast. // SQXTN, UQXTN, SQXTUN - Saturating narrow. casts.emplace_back("saturating_narrow", i8_sat(wild_i16x_)); casts.emplace_back("saturating_narrow", u8_sat(wild_u16x_)); casts.emplace_back("saturating_narrow", u8_sat(wild_i16x_)); casts.emplace_back("saturating_narrow", i16_sat(wild_i32x_)); casts.emplace_back("saturating_narrow", u16_sat(wild_u32x_)); casts.emplace_back("saturating_narrow", u16_sat(wild_i32x_)); casts.emplace_back("saturating_narrow", i32_sat(wild_i64x_)); casts.emplace_back("saturating_narrow", u32_sat(wild_u64x_)); casts.emplace_back("saturating_narrow", u32_sat(wild_i64x_)); // SQNEG - Saturating negate negations.emplace_back("saturating_negate", -max(wild_i8x_, -127)); negations.emplace_back("saturating_negate", -max(wild_i16x_, -32767)); negations.emplace_back("saturating_negate", -max(wild_i32x_, -(0x7fffffff))); // clang-format on } constexpr int max_intrinsic_args = 4; struct ArmIntrinsic { const char *arm32; const char *arm64; halide_type_t ret_type; const char *name; halide_type_t arg_types[max_intrinsic_args]; int flags; enum { AllowUnsignedOp1 = 1 << 0, // Generate a second version of the instruction with the second operand unsigned. HalfWidth = 1 << 1, // This is a half-width instruction that should have a full width version generated as well. NoMangle = 1 << 2, // Don't mangle this intrinsic name. MangleArgs = 1 << 3, // Most intrinsics only mangle the return type. Some mangle the arguments instead. MangleRetArgs = 1 << 4, // Most intrinsics only mangle the return type. Some mangle the return type and arguments instead. ScalarsAreVectors = 1 << 5, // Some intrinsics have scalar arguments that are vector parameters :( SplitArg0 = 1 << 6, // This intrinsic requires splitting the argument into the low and high halves. NoPrefix = 1 << 7, // Don't prefix the intrinsic with llvm.* }; }; // clang-format off const ArmIntrinsic intrinsic_defs[] = { {"vabs", "abs", UInt(8, 8), "abs", {Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vabs", "abs", UInt(16, 4), "abs", {Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vabs", "abs", UInt(32, 2), "abs", {Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"llvm.fabs", "llvm.fabs", Float(32, 2), "abs", {Float(32, 2)}, ArmIntrinsic::HalfWidth}, {"llvm.sqrt", "llvm.sqrt", Float(32, 4), "sqrt_f32", {Float(32, 4)}}, {"llvm.sqrt", "llvm.sqrt", Float(64, 2), "sqrt_f64", {Float(64, 2)}}, // SABD, UABD - Absolute difference {"vabds", "sabd", UInt(8, 8), "absd", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vabdu", "uabd", UInt(8, 8), "absd", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"vabds", "sabd", UInt(16, 4), "absd", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vabdu", "uabd", UInt(16, 4), "absd", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"vabds", "sabd", UInt(32, 2), "absd", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vabdu", "uabd", UInt(32, 2), "absd", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, // SMULL, UMULL - Widening multiply {"vmulls", "smull", Int(16, 8), "widening_mul", {Int(8, 8), Int(8, 8)}}, {"vmullu", "umull", UInt(16, 8), "widening_mul", {UInt(8, 8), UInt(8, 8)}}, {"vmulls", "smull", Int(32, 4), "widening_mul", {Int(16, 4), Int(16, 4)}}, {"vmullu", "umull", UInt(32, 4), "widening_mul", {UInt(16, 4), UInt(16, 4)}}, {"vmulls", "smull", Int(64, 2), "widening_mul", {Int(32, 2), Int(32, 2)}}, {"vmullu", "umull", UInt(64, 2), "widening_mul", {UInt(32, 2), UInt(32, 2)}}, // SQADD, UQADD - Saturating add // On arm32, the ARM version of this seems to be missing on some configurations. // Rather than debug this, just use LLVM's saturating add intrinsic. {"llvm.sadd.sat", "sqadd", Int(8, 8), "saturating_add", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"llvm.uadd.sat", "uqadd", UInt(8, 8), "saturating_add", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"llvm.sadd.sat", "sqadd", Int(16, 4), "saturating_add", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"llvm.uadd.sat", "uqadd", UInt(16, 4), "saturating_add", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"llvm.sadd.sat", "sqadd", Int(32, 2), "saturating_add", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"llvm.uadd.sat", "uqadd", UInt(32, 2), "saturating_add", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, // SQSUB, UQSUB - Saturating subtract {"llvm.ssub.sat", "sqsub", Int(8, 8), "saturating_sub", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"llvm.usub.sat", "uqsub", UInt(8, 8), "saturating_sub", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"llvm.ssub.sat", "sqsub", Int(16, 4), "saturating_sub", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"llvm.usub.sat", "uqsub", UInt(16, 4), "saturating_sub", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"llvm.ssub.sat", "sqsub", Int(32, 2), "saturating_sub", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"llvm.usub.sat", "uqsub", UInt(32, 2), "saturating_sub", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, // SHADD, UHADD - Halving add {"vhadds", "shadd", Int(8, 8), "halving_add", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vhaddu", "uhadd", UInt(8, 8), "halving_add", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"vhadds", "shadd", Int(16, 4), "halving_add", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vhaddu", "uhadd", UInt(16, 4), "halving_add", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"vhadds", "shadd", Int(32, 2), "halving_add", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vhaddu", "uhadd", UInt(32, 2), "halving_add", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, // SHSUB, UHSUB - Halving subtract {"vhsubs", "shsub", Int(8, 8), "halving_sub", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vhsubu", "uhsub", UInt(8, 8), "halving_sub", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"vhsubs", "shsub", Int(16, 4), "halving_sub", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vhsubu", "uhsub", UInt(16, 4), "halving_sub", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"vhsubs", "shsub", Int(32, 2), "halving_sub", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vhsubu", "uhsub", UInt(32, 2), "halving_sub", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, // SRHADD, URHADD - Halving add with rounding {"vrhadds", "srhadd", Int(8, 8), "rounding_halving_add", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vrhaddu", "urhadd", UInt(8, 8), "rounding_halving_add", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"vrhadds", "srhadd", Int(16, 4), "rounding_halving_add", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vrhaddu", "urhadd", UInt(16, 4), "rounding_halving_add", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"vrhadds", "srhadd", Int(32, 2), "rounding_halving_add", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vrhaddu", "urhadd", UInt(32, 2), "rounding_halving_add", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, // SRHSUB, URHSUB - Halving sub with rounding {"vrhsubs", "srhsub", Int(8, 8), "rounding_halving_sub", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vrhsubu", "urhsub", UInt(8, 8), "rounding_halving_sub", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"vrhsubs", "srhsub", Int(16, 4), "rounding_halving_sub", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vrhsubu", "urhsub", UInt(16, 4), "rounding_halving_sub", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"vrhsubs", "srhsub", Int(32, 2), "rounding_halving_sub", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vrhsubu", "urhsub", UInt(32, 2), "rounding_halving_sub", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, // SMIN, UMIN, FMIN - Min {"vmins", "smin", Int(8, 8), "min", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vminu", "umin", UInt(8, 8), "min", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"vmins", "smin", Int(16, 4), "min", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vminu", "umin", UInt(16, 4), "min", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"vmins", "smin", Int(32, 2), "min", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vminu", "umin", UInt(32, 2), "min", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, {"vmins", "fmin", Float(32, 2), "min", {Float(32, 2), Float(32, 2)}, ArmIntrinsic::HalfWidth}, // SMAX, UMAX, FMAX - Max {"vmaxs", "smax", Int(8, 8), "max", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vmaxu", "umax", UInt(8, 8), "max", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::HalfWidth}, {"vmaxs", "smax", Int(16, 4), "max", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vmaxu", "umax", UInt(16, 4), "max", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::HalfWidth}, {"vmaxs", "smax", Int(32, 2), "max", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vmaxu", "umax", UInt(32, 2), "max", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::HalfWidth}, {"vmaxs", "fmax", Float(32, 2), "max", {Float(32, 2), Float(32, 2)}, ArmIntrinsic::HalfWidth}, // SQNEG, UQNEG - Saturating negation {"vqneg", "sqneg", Int(8, 8), "saturating_negate", {Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vqneg", "sqneg", Int(16, 4), "saturating_negate", {Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vqneg", "sqneg", Int(32, 2), "saturating_negate", {Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vqneg", "sqneg", Int(64, 2), "saturating_negate", {Int(64, 2)}}, // SQXTN, UQXTN, SQXTUN - Saturating narrowing {"vqmovns", "sqxtn", Int(8, 8), "saturating_narrow", {Int(16, 8)}}, {"vqmovnu", "uqxtn", UInt(8, 8), "saturating_narrow", {UInt(16, 8)}}, {"vqmovnsu", "sqxtun", UInt(8, 8), "saturating_narrow", {Int(16, 8)}}, {"vqmovns", "sqxtn", Int(16, 4), "saturating_narrow", {Int(32, 4)}}, {"vqmovnu", "uqxtn", UInt(16, 4), "saturating_narrow", {UInt(32, 4)}}, {"vqmovnsu", "sqxtun", UInt(16, 4), "saturating_narrow", {Int(32, 4)}}, {"vqmovns", "sqxtn", Int(32, 2), "saturating_narrow", {Int(64, 2)}}, {"vqmovnu", "uqxtn", UInt(32, 2), "saturating_narrow", {UInt(64, 2)}}, {"vqmovnsu", "sqxtun", UInt(32, 2), "saturating_narrow", {Int(64, 2)}}, // RSHRN - Rounding shift right narrow (by immediate in [1, output bits]) // arm32 expects a vector RHS of the same type as the LHS except signed. {"vrshiftn", nullptr, Int(8, 8), "rounding_shift_right_narrow", {Int(16, 8), Int(16, 8)}}, {"vrshiftn", nullptr, UInt(8, 8), "rounding_shift_right_narrow", {UInt(16, 8), Int(16, 8)}}, {"vrshiftn", nullptr, Int(16, 4), "rounding_shift_right_narrow", {Int(32, 4), Int(32, 4)}}, {"vrshiftn", nullptr, UInt(16, 4), "rounding_shift_right_narrow", {UInt(32, 4), Int(32, 4)}}, {"vrshiftn", nullptr, Int(32, 2), "rounding_shift_right_narrow", {Int(64, 2), Int(64, 2)}}, {"vrshiftn", nullptr, UInt(32, 2), "rounding_shift_right_narrow", {UInt(64, 2), Int(64, 2)}}, // arm64 expects a 32-bit constant. {nullptr, "rshrn", Int(8, 8), "rounding_shift_right_narrow", {Int(16, 8), UInt(32)}}, {nullptr, "rshrn", UInt(8, 8), "rounding_shift_right_narrow", {UInt(16, 8), UInt(32)}}, {nullptr, "rshrn", Int(16, 4), "rounding_shift_right_narrow", {Int(32, 4), UInt(32)}}, {nullptr, "rshrn", UInt(16, 4), "rounding_shift_right_narrow", {UInt(32, 4), UInt(32)}}, {nullptr, "rshrn", Int(32, 2), "rounding_shift_right_narrow", {Int(64, 2), UInt(32)}}, {nullptr, "rshrn", UInt(32, 2), "rounding_shift_right_narrow", {UInt(64, 2), UInt(32)}}, // SHRN - Shift right narrow (by immediate in [1, output bits]) // LLVM pattern matches these. // SQRSHL, UQRSHL - Saturating rounding shift left (by signed vector) {"vqrshifts", "sqrshl", Int(8, 8), "saturating_rounding_shift_left", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vqrshiftu", "uqrshl", UInt(8, 8), "saturating_rounding_shift_left", {UInt(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vqrshifts", "sqrshl", Int(16, 4), "saturating_rounding_shift_left", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vqrshiftu", "uqrshl", UInt(16, 4), "saturating_rounding_shift_left", {UInt(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vqrshifts", "sqrshl", Int(32, 2), "saturating_rounding_shift_left", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vqrshiftu", "uqrshl", UInt(32, 2), "saturating_rounding_shift_left", {UInt(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vqrshifts", "sqrshl", Int(64, 2), "saturating_rounding_shift_left", {Int(64, 2), Int(64, 2)}}, {"vqrshiftu", "uqrshl", UInt(64, 2), "saturating_rounding_shift_left", {UInt(64, 2), Int(64, 2)}}, // SQRSHRN, UQRSHRN, SQRSHRUN - Saturating rounding narrowing shift right (by immediate in [1, output bits]) // arm32 expects a vector RHS of the same type as the LHS except signed. {"vqrshiftns", nullptr, Int(8, 8), "saturating_rounding_shift_right_narrow", {Int(16, 8), Int(16, 8)}}, {"vqrshiftnu", nullptr, UInt(8, 8), "saturating_rounding_shift_right_narrow", {UInt(16, 8), Int(16, 8)}}, {"vqrshiftnsu", nullptr, UInt(8, 8), "saturating_rounding_shift_right_narrow", {Int(16, 8), Int(16, 8)}}, {"vqrshiftns", nullptr, Int(16, 4), "saturating_rounding_shift_right_narrow", {Int(32, 4), Int(32, 4)}}, {"vqrshiftnu", nullptr, UInt(16, 4), "saturating_rounding_shift_right_narrow", {UInt(32, 4), Int(32, 4)}}, {"vqrshiftnsu", nullptr, UInt(16, 4), "saturating_rounding_shift_right_narrow", {Int(32, 4), Int(32, 4)}}, {"vqrshiftns", nullptr, Int(32, 2), "saturating_rounding_shift_right_narrow", {Int(64, 2), Int(64, 2)}}, {"vqrshiftnu", nullptr, UInt(32, 2), "saturating_rounding_shift_right_narrow", {UInt(64, 2), Int(64, 2)}}, {"vqrshiftnsu", nullptr, UInt(32, 2), "saturating_rounding_shift_right_narrow", {Int(64, 2), Int(64, 2)}}, // arm64 expects a 32-bit constant. {nullptr, "sqrshrn", Int(8, 8), "saturating_rounding_shift_right_narrow", {Int(16, 8), UInt(32)}}, {nullptr, "uqrshrn", UInt(8, 8), "saturating_rounding_shift_right_narrow", {UInt(16, 8), UInt(32)}}, {nullptr, "sqrshrun", UInt(8, 8), "saturating_rounding_shift_right_narrow", {Int(16, 8), UInt(32)}}, {nullptr, "sqrshrn", Int(16, 4), "saturating_rounding_shift_right_narrow", {Int(32, 4), UInt(32)}}, {nullptr, "uqrshrn", UInt(16, 4), "saturating_rounding_shift_right_narrow", {UInt(32, 4), UInt(32)}}, {nullptr, "sqrshrun", UInt(16, 4), "saturating_rounding_shift_right_narrow", {Int(32, 4), UInt(32)}}, {nullptr, "sqrshrn", Int(32, 2), "saturating_rounding_shift_right_narrow", {Int(64, 2), UInt(32)}}, {nullptr, "uqrshrn", UInt(32, 2), "saturating_rounding_shift_right_narrow", {UInt(64, 2), UInt(32)}}, {nullptr, "sqrshrun", UInt(32, 2), "saturating_rounding_shift_right_narrow", {Int(64, 2), UInt(32)}}, // SQSHL, UQSHL, SQSHLU - Saturating shift left by signed register. // There is also an immediate version of this - hopefully LLVM does this matching when appropriate. {"vqshifts", "sqshl", Int(8, 8), "saturating_shift_left", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshiftu", "uqshl", UInt(8, 8), "saturating_shift_left", {UInt(8, 8), Int(8, 8)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshiftsu", "sqshlu", UInt(8, 8), "saturating_shift_left", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshifts", "sqshl", Int(16, 4), "saturating_shift_left", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshiftu", "uqshl", UInt(16, 4), "saturating_shift_left", {UInt(16, 4), Int(16, 4)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshiftsu", "sqshlu", UInt(16, 4), "saturating_shift_left", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshifts", "sqshl", Int(32, 2), "saturating_shift_left", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshiftu", "uqshl", UInt(32, 2), "saturating_shift_left", {UInt(32, 2), Int(32, 2)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshiftsu", "sqshlu", UInt(32, 2), "saturating_shift_left", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::AllowUnsignedOp1 | ArmIntrinsic::HalfWidth}, {"vqshifts", "sqshl", Int(64, 2), "saturating_shift_left", {Int(64, 2), Int(64, 2)}, ArmIntrinsic::AllowUnsignedOp1}, {"vqshiftu", "uqshl", UInt(64, 2), "saturating_shift_left", {UInt(64, 2), Int(64, 2)}, ArmIntrinsic::AllowUnsignedOp1}, {"vqshiftsu", "sqshlu", UInt(64, 2), "saturating_shift_left", {Int(64, 2), Int(64, 2)}, ArmIntrinsic::AllowUnsignedOp1}, // SQSHRN, UQSHRN, SQRSHRUN Saturating narrowing shift right by an (by immediate in [1, output bits]) // arm32 expects a vector RHS of the same type as the LHS. {"vqshiftns", nullptr, Int(8, 8), "saturating_shift_right_narrow", {Int(16, 8), Int(16, 8)}}, {"vqshiftnu", nullptr, UInt(8, 8), "saturating_shift_right_narrow", {UInt(16, 8), Int(16, 8)}}, {"vqshiftns", nullptr, Int(16, 4), "saturating_shift_right_narrow", {Int(32, 4), Int(32, 4)}}, {"vqshiftnu", nullptr, UInt(16, 4), "saturating_shift_right_narrow", {UInt(32, 4), Int(32, 4)}}, {"vqshiftns", nullptr, Int(32, 2), "saturating_shift_right_narrow", {Int(64, 2), Int(64, 2)}}, {"vqshiftnu", nullptr, UInt(32, 2), "saturating_shift_right_narrow", {UInt(64, 2), Int(64, 2)}}, {"vqshiftnsu", nullptr, UInt(8, 8), "saturating_shift_right_narrow", {Int(16, 8), Int(16, 8)}}, {"vqshiftnsu", nullptr, UInt(16, 4), "saturating_shift_right_narrow", {Int(32, 4), Int(32, 4)}}, {"vqshiftnsu", nullptr, UInt(32, 2), "saturating_shift_right_narrow", {Int(64, 2), Int(64, 2)}}, // arm64 expects a 32-bit constant. {nullptr, "sqshrn", Int(8, 8), "saturating_shift_right_narrow", {Int(16, 8), UInt(32)}}, {nullptr, "uqshrn", UInt(8, 8), "saturating_shift_right_narrow", {UInt(16, 8), UInt(32)}}, {nullptr, "sqshrn", Int(16, 4), "saturating_shift_right_narrow", {Int(32, 4), UInt(32)}}, {nullptr, "uqshrn", UInt(16, 4), "saturating_shift_right_narrow", {UInt(32, 4), UInt(32)}}, {nullptr, "sqshrn", Int(32, 2), "saturating_shift_right_narrow", {Int(64, 2), UInt(32)}}, {nullptr, "uqshrn", UInt(32, 2), "saturating_shift_right_narrow", {UInt(64, 2), UInt(32)}}, {nullptr, "sqshrun", UInt(8, 8), "saturating_shift_right_narrow", {Int(16, 8), UInt(32)}}, {nullptr, "sqshrun", UInt(16, 4), "saturating_shift_right_narrow", {Int(32, 4), UInt(32)}}, {nullptr, "sqshrun", UInt(32, 2), "saturating_shift_right_narrow", {Int(64, 2), UInt(32)}}, // SRSHL, URSHL - Rounding shift left (by signed vector) {"vrshifts", "srshl", Int(8, 8), "rounding_shift_left", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vrshiftu", "urshl", UInt(8, 8), "rounding_shift_left", {UInt(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vrshifts", "srshl", Int(16, 4), "rounding_shift_left", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vrshiftu", "urshl", UInt(16, 4), "rounding_shift_left", {UInt(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vrshifts", "srshl", Int(32, 2), "rounding_shift_left", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vrshiftu", "urshl", UInt(32, 2), "rounding_shift_left", {UInt(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vrshifts", "srshl", Int(64, 2), "rounding_shift_left", {Int(64, 2), Int(64, 2)}}, {"vrshiftu", "urshl", UInt(64, 2), "rounding_shift_left", {UInt(64, 2), Int(64, 2)}}, // SSHL, USHL - Shift left (by signed vector) {"vshifts", "sshl", Int(8, 8), "shift_left", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vshiftu", "ushl", UInt(8, 8), "shift_left", {UInt(8, 8), Int(8, 8)}, ArmIntrinsic::HalfWidth}, {"vshifts", "sshl", Int(16, 4), "shift_left", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vshiftu", "ushl", UInt(16, 4), "shift_left", {UInt(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vshifts", "sshl", Int(32, 2), "shift_left", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vshiftu", "ushl", UInt(32, 2), "shift_left", {UInt(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, {"vshifts", "sshl", Int(64, 2), "shift_left", {Int(64, 2), Int(64, 2)}}, {"vshiftu", "ushl", UInt(64, 2), "shift_left", {UInt(64, 2), Int(64, 2)}}, // SRSHR, URSHR - Rounding shift right (by immediate in [1, output bits]) // LLVM wants these expressed as SRSHL by negative amounts. // SSHLL, USHLL - Shift left long (by immediate in [0, output bits - 1]) // LLVM pattern matches these for us. // RADDHN - Add and narrow with rounding. {"vraddhn", "raddhn", Int(8, 8), "rounding_add_narrow", {Int(16, 8), Int(16, 8)}}, {"vraddhn", "raddhn", UInt(8, 8), "rounding_add_narrow", {UInt(16, 8), UInt(16, 8)}}, {"vraddhn", "raddhn", Int(16, 4), "rounding_add_narrow", {Int(32, 4), Int(32, 4)}}, {"vraddhn", "raddhn", UInt(16, 4), "rounding_add_narrow", {UInt(32, 4), UInt(32, 4)}}, {"vraddhn", "raddhn", Int(32, 2), "rounding_add_narrow", {Int(64, 2), Int(64, 2)}}, {"vraddhn", "raddhn", UInt(32, 2), "rounding_add_narrow", {UInt(64, 2), UInt(64, 2)}}, // RSUBHN - Sub and narrow with rounding. {"vrsubhn", "rsubhn", Int(8, 8), "rounding_sub_narrow", {Int(16, 8), Int(16, 8)}}, {"vrsubhn", "rsubhn", UInt(8, 8), "rounding_sub_narrow", {UInt(16, 8), UInt(16, 8)}}, {"vrsubhn", "rsubhn", Int(16, 4), "rounding_sub_narrow", {Int(32, 4), Int(32, 4)}}, {"vrsubhn", "rsubhn", UInt(16, 4), "rounding_sub_narrow", {UInt(32, 4), UInt(32, 4)}}, {"vrsubhn", "rsubhn", Int(32, 2), "rounding_sub_narrow", {Int(64, 2), Int(64, 2)}}, {"vrsubhn", "rsubhn", UInt(32, 2), "rounding_sub_narrow", {UInt(64, 2), UInt(64, 2)}}, // SQDMULH - Saturating doubling multiply keep high half. {"vqdmulh", "sqdmulh", Int(16, 4), "qdmulh", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vqdmulh", "sqdmulh", Int(32, 2), "qdmulh", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, // SQRDMULH - Saturating doubling multiply keep high half with rounding. {"vqrdmulh", "sqrdmulh", Int(16, 4), "qrdmulh", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::HalfWidth}, {"vqrdmulh", "sqrdmulh", Int(32, 2), "qrdmulh", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::HalfWidth}, // PADD - Pairwise add. // 32-bit only has half-width versions. {"vpadd", nullptr, Int(8, 8), "pairwise_add", {Int(8, 16)}, ArmIntrinsic::SplitArg0}, {"vpadd", nullptr, UInt(8, 8), "pairwise_add", {UInt(8, 16)}, ArmIntrinsic::SplitArg0}, {"vpadd", nullptr, Int(16, 4), "pairwise_add", {Int(16, 8)}, ArmIntrinsic::SplitArg0}, {"vpadd", nullptr, UInt(16, 4), "pairwise_add", {UInt(16, 8)}, ArmIntrinsic::SplitArg0}, {"vpadd", nullptr, Int(32, 2), "pairwise_add", {Int(32, 4)}, ArmIntrinsic::SplitArg0}, {"vpadd", nullptr, UInt(32, 2), "pairwise_add", {UInt(32, 4)}, ArmIntrinsic::SplitArg0}, {"vpadd", nullptr, Float(32, 2), "pairwise_add", {Float(32, 4)}, ArmIntrinsic::SplitArg0}, {nullptr, "addp", Int(8, 8), "pairwise_add", {Int(8, 16)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "addp", UInt(8, 8), "pairwise_add", {UInt(8, 16)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "addp", Int(16, 4), "pairwise_add", {Int(16, 8)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "addp", UInt(16, 4), "pairwise_add", {UInt(16, 8)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "addp", Int(32, 2), "pairwise_add", {Int(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "addp", UInt(32, 2), "pairwise_add", {UInt(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "faddp", Float(32, 2), "pairwise_add", {Float(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "faddp", Float(64, 2), "pairwise_add", {Float(64, 4)}, ArmIntrinsic::SplitArg0}, // SADDLP, UADDLP - Pairwise add long. {"vpaddls", "saddlp", Int(16, 4), "pairwise_widening_add", {Int(8, 8)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs}, {"vpaddlu", "uaddlp", UInt(16, 4), "pairwise_widening_add", {UInt(8, 8)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs}, {"vpaddlu", "uaddlp", Int(16, 4), "pairwise_widening_add", {UInt(8, 8)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs}, {"vpaddls", "saddlp", Int(32, 2), "pairwise_widening_add", {Int(16, 4)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs}, {"vpaddlu", "uaddlp", UInt(32, 2), "pairwise_widening_add", {UInt(16, 4)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs}, {"vpaddlu", "uaddlp", Int(32, 2), "pairwise_widening_add", {UInt(16, 4)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs}, {"vpaddls", "saddlp", Int(64, 1), "pairwise_widening_add", {Int(32, 2)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs | ArmIntrinsic::ScalarsAreVectors}, {"vpaddlu", "uaddlp", UInt(64, 1), "pairwise_widening_add", {UInt(32, 2)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs | ArmIntrinsic::ScalarsAreVectors}, {"vpaddlu", "uaddlp", Int(64, 1), "pairwise_widening_add", {UInt(32, 2)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleRetArgs | ArmIntrinsic::ScalarsAreVectors}, // SPADAL, UPADAL - Pairwise add and accumulate long. {"vpadals", nullptr, Int(16, 4), "pairwise_widening_add_accumulate", {Int(16, 4), Int(8, 8)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs}, {"vpadalu", nullptr, UInt(16, 4), "pairwise_widening_add_accumulate", {UInt(16, 4), UInt(8, 8)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs}, {"vpadalu", nullptr, Int(16, 4), "pairwise_widening_add_accumulate", {Int(16, 4), UInt(8, 8)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs}, {"vpadals", nullptr, Int(32, 2), "pairwise_widening_add_accumulate", {Int(32, 2), Int(16, 4)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs}, {"vpadalu", nullptr, UInt(32, 2), "pairwise_widening_add_accumulate", {UInt(32, 2), UInt(16, 4)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs}, {"vpadalu", nullptr, Int(32, 2), "pairwise_widening_add_accumulate", {Int(32, 2), UInt(16, 4)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs}, {"vpadals", nullptr, Int(64, 1), "pairwise_widening_add_accumulate", {Int(64, 1), Int(32, 2)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs | ArmIntrinsic::ScalarsAreVectors}, {"vpadalu", nullptr, UInt(64, 1), "pairwise_widening_add_accumulate", {UInt(64, 1), UInt(32, 2)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs | ArmIntrinsic::ScalarsAreVectors}, {"vpadalu", nullptr, Int(64, 1), "pairwise_widening_add_accumulate", {Int(64, 1), UInt(32, 2)}, ArmIntrinsic::HalfWidth | ArmIntrinsic::MangleArgs | ArmIntrinsic::ScalarsAreVectors}, // SMAXP, UMAXP, FMAXP - Pairwise max. {nullptr, "smaxp", Int(8, 8), "pairwise_max", {Int(8, 16)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "umaxp", UInt(8, 8), "pairwise_max", {UInt(8, 16)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "smaxp", Int(16, 4), "pairwise_max", {Int(16, 8)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "umaxp", UInt(16, 4), "pairwise_max", {UInt(16, 8)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "smaxp", Int(32, 2), "pairwise_max", {Int(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "umaxp", UInt(32, 2), "pairwise_max", {UInt(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "fmaxp", Float(32, 2), "pairwise_max", {Float(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, // On arm32, we only have half-width versions of these. {"vpmaxs", nullptr, Int(8, 8), "pairwise_max", {Int(8, 16)}, ArmIntrinsic::SplitArg0}, {"vpmaxu", nullptr, UInt(8, 8), "pairwise_max", {UInt(8, 16)}, ArmIntrinsic::SplitArg0}, {"vpmaxs", nullptr, Int(16, 4), "pairwise_max", {Int(16, 8)}, ArmIntrinsic::SplitArg0}, {"vpmaxu", nullptr, UInt(16, 4), "pairwise_max", {UInt(16, 8)}, ArmIntrinsic::SplitArg0}, {"vpmaxs", nullptr, Int(32, 2), "pairwise_max", {Int(32, 4)}, ArmIntrinsic::SplitArg0}, {"vpmaxu", nullptr, UInt(32, 2), "pairwise_max", {UInt(32, 4)}, ArmIntrinsic::SplitArg0}, {"vpmaxs", nullptr, Float(32, 2), "pairwise_max", {Float(32, 4)}, ArmIntrinsic::SplitArg0}, // SMINP, UMINP, FMINP - Pairwise min. {nullptr, "sminp", Int(8, 8), "pairwise_min", {Int(8, 16)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "uminp", UInt(8, 8), "pairwise_min", {UInt(8, 16)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "sminp", Int(16, 4), "pairwise_min", {Int(16, 8)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "uminp", UInt(16, 4), "pairwise_min", {UInt(16, 8)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "sminp", Int(32, 2), "pairwise_min", {Int(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "uminp", UInt(32, 2), "pairwise_min", {UInt(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, {nullptr, "fminp", Float(32, 2), "pairwise_min", {Float(32, 4)}, ArmIntrinsic::SplitArg0 | ArmIntrinsic::HalfWidth}, // On arm32, we only have half-width versions of these. {"vpmins", nullptr, Int(8, 8), "pairwise_min", {Int(8, 16)}, ArmIntrinsic::SplitArg0}, {"vpminu", nullptr, UInt(8, 8), "pairwise_min", {UInt(8, 16)}, ArmIntrinsic::SplitArg0}, {"vpmins", nullptr, Int(16, 4), "pairwise_min", {Int(16, 8)}, ArmIntrinsic::SplitArg0}, {"vpminu", nullptr, UInt(16, 4), "pairwise_min", {UInt(16, 8)}, ArmIntrinsic::SplitArg0}, {"vpmins", nullptr, Int(32, 2), "pairwise_min", {Int(32, 4)}, ArmIntrinsic::SplitArg0}, {"vpminu", nullptr, UInt(32, 2), "pairwise_min", {UInt(32, 4)}, ArmIntrinsic::SplitArg0}, {"vpmins", nullptr, Float(32, 2), "pairwise_min", {Float(32, 4)}, ArmIntrinsic::SplitArg0}, // SDOT, UDOT - Dot products. // Mangle this one manually, there aren't that many and it is a special case. {nullptr, "sdot.v2i32.v8i8", Int(32, 2), "dot_product", {Int(32, 2), Int(8, 8), Int(8, 8)}, ArmIntrinsic::NoMangle}, {nullptr, "udot.v2i32.v8i8", Int(32, 2), "dot_product", {Int(32, 2), UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::NoMangle}, {nullptr, "udot.v2i32.v8i8", UInt(32, 2), "dot_product", {UInt(32, 2), UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::NoMangle}, {nullptr, "sdot.v4i32.v16i8", Int(32, 4), "dot_product", {Int(32, 4), Int(8, 16), Int(8, 16)}, ArmIntrinsic::NoMangle}, {nullptr, "udot.v4i32.v16i8", Int(32, 4), "dot_product", {Int(32, 4), UInt(8, 16), UInt(8, 16)}, ArmIntrinsic::NoMangle}, {nullptr, "udot.v4i32.v16i8", UInt(32, 4), "dot_product", {UInt(32, 4), UInt(8, 16), UInt(8, 16)}, ArmIntrinsic::NoMangle}, // ABDL - Widening absolute difference // Need to be able to handle both signed and unsigned outputs for signed inputs. {"vabdl_i8x8", "vabdl_i8x8", Int(16, 8), "widening_absd", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, {"vabdl_i8x8", "vabdl_i8x8", UInt(16, 8), "widening_absd", {Int(8, 8), Int(8, 8)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, {"vabdl_u8x8", "vabdl_u8x8", UInt(16, 8), "widening_absd", {UInt(8, 8), UInt(8, 8)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, {"vabdl_i16x4", "vabdl_i16x4", Int(32, 4), "widening_absd", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, {"vabdl_i16x4", "vabdl_i16x4", UInt(32, 4), "widening_absd", {Int(16, 4), Int(16, 4)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, {"vabdl_u16x4", "vabdl_u16x4", UInt(32, 4), "widening_absd", {UInt(16, 4), UInt(16, 4)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, {"vabdl_i32x2", "vabdl_i32x2", Int(64, 2), "widening_absd", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, {"vabdl_i32x2", "vabdl_i32x2", UInt(64, 2), "widening_absd", {Int(32, 2), Int(32, 2)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, {"vabdl_u32x2", "vabdl_u32x2", UInt(64, 2), "widening_absd", {UInt(32, 2), UInt(32, 2)}, ArmIntrinsic::NoMangle | ArmIntrinsic::NoPrefix}, }; // clang-format on llvm::Function *CodeGen_ARM::define_concat_args_wrapper(llvm::Function *inner, const string &name) { llvm::FunctionType *inner_ty = inner->getFunctionType(); internal_assert(inner_ty->getNumParams() == 2); llvm::Type *inner_arg0_ty = inner_ty->getParamType(0); llvm::Type *inner_arg1_ty = inner_ty->getParamType(1); int inner_arg0_lanes = get_vector_num_elements(inner_arg0_ty); int inner_arg1_lanes = get_vector_num_elements(inner_arg1_ty); llvm::Type *concat_arg_ty = get_vector_type(inner_arg0_ty->getScalarType(), inner_arg0_lanes + inner_arg1_lanes); // Make a wrapper. llvm::FunctionType *wrapper_ty = llvm::FunctionType::get(inner_ty->getReturnType(), {concat_arg_ty}, false); llvm::Function *wrapper = llvm::Function::Create(wrapper_ty, llvm::GlobalValue::InternalLinkage, name, module.get()); llvm::BasicBlock *block = llvm::BasicBlock::Create(module->getContext(), "entry", wrapper); IRBuilderBase::InsertPoint here = builder->saveIP(); builder->SetInsertPoint(block); // Call the real intrinsic. Value *low = slice_vector(wrapper->getArg(0), 0, inner_arg0_lanes); Value *high = slice_vector(wrapper->getArg(0), inner_arg0_lanes, inner_arg1_lanes); Value *ret = builder->CreateCall(inner, {low, high}); builder->CreateRet(ret); // Always inline these wrappers. wrapper->addFnAttr(llvm::Attribute::AlwaysInline); builder->restoreIP(here); llvm::verifyFunction(*wrapper); return wrapper; } void CodeGen_ARM::init_module() { CodeGen_Posix::init_module(); if (neon_intrinsics_disabled()) { return; } string prefix = target.bits == 32 ? "llvm.arm.neon." : "llvm.aarch64.neon."; for (const ArmIntrinsic &intrin : intrinsic_defs) { // Get the name of the intrinsic with the appropriate prefix. const char *intrin_name = nullptr; if (target.bits == 32) { intrin_name = intrin.arm32; } else { intrin_name = intrin.arm64; } if (!intrin_name) { continue; } string full_name = intrin_name; if (!starts_with(full_name, "llvm.") && (intrin.flags & ArmIntrinsic::NoPrefix) == 0) { full_name = prefix + full_name; } // We might have to generate versions of this intrinsic with multiple widths. vector<int> width_factors = {1}; if (intrin.flags & ArmIntrinsic::HalfWidth) { width_factors.push_back(2); } for (int width_factor : width_factors) { Type ret_type = intrin.ret_type; ret_type = ret_type.with_lanes(ret_type.lanes() * width_factor); internal_assert(ret_type.bits() * ret_type.lanes() <= 128) << full_name << "\n"; vector<Type> arg_types; arg_types.reserve(4); for (halide_type_t i : intrin.arg_types) { if (i.bits == 0) { break; } Type arg_type = i; if (arg_type.is_vector()) { arg_type = arg_type.with_lanes(arg_type.lanes() * width_factor); } arg_types.emplace_back(arg_type); } // Generate the LLVM mangled name. std::stringstream mangled_name_builder; mangled_name_builder << full_name; if (starts_with(full_name, "llvm.") && (intrin.flags & ArmIntrinsic::NoMangle) == 0) { // Append LLVM name mangling for either the return type or the arguments, or both. vector<Type> types; if (intrin.flags & ArmIntrinsic::MangleArgs) { types = arg_types; } else if (intrin.flags & ArmIntrinsic::MangleRetArgs) { types = {ret_type}; types.insert(types.end(), arg_types.begin(), arg_types.end()); } else { types = {ret_type}; } for (const Type &t : types) { mangled_name_builder << ".v" << t.lanes(); if (t.is_int() || t.is_uint()) { mangled_name_builder << "i"; } else if (t.is_float()) { mangled_name_builder << "f"; } mangled_name_builder << t.bits(); } } string mangled_name = mangled_name_builder.str(); llvm::Function *intrin_impl = nullptr; if (intrin.flags & ArmIntrinsic::SplitArg0) { // This intrinsic needs a wrapper to split the argument. string wrapper_name = intrin.name + unique_name("_wrapper"); Type split_arg_type = arg_types[0].with_lanes(arg_types[0].lanes() / 2); llvm::Function *to_wrap = get_llvm_intrin(ret_type, mangled_name, {split_arg_type, split_arg_type}); intrin_impl = define_concat_args_wrapper(to_wrap, wrapper_name); } else { bool scalars_are_vectors = intrin.flags & ArmIntrinsic::ScalarsAreVectors; intrin_impl = get_llvm_intrin(ret_type, mangled_name, arg_types, scalars_are_vectors); } intrin_impl->addFnAttr(llvm::Attribute::ReadNone); intrin_impl->addFnAttr(llvm::Attribute::NoUnwind); declare_intrin_overload(intrin.name, ret_type, intrin_impl, arg_types); if (intrin.flags & ArmIntrinsic::AllowUnsignedOp1) { // Also generate a version of this intrinsic where the second operand is unsigned. arg_types[1] = arg_types[1].with_code(halide_type_uint); declare_intrin_overload(intrin.name, ret_type, intrin_impl, arg_types); } } } } void CodeGen_ARM::visit(const Cast *op) { if (!neon_intrinsics_disabled() && op->type.is_vector()) { vector<Expr> matches; for (const Pattern &pattern : casts) { if (expr_match(pattern.pattern, op, matches)) { if (pattern.intrin.find("shift_right_narrow") != string::npos) { // The shift_right_narrow patterns need the shift to be constant in [1, output_bits]. const uint64_t *const_b = as_const_uint(matches[1]); if (!const_b || *const_b == 0 || (int)*const_b > op->type.bits()) { continue; } } if (target.bits == 32 && pattern.intrin.find("shift_right") != string::npos) { // The 32-bit ARM backend wants right shifts as negative values. matches[1] = simplify(-cast(matches[1].type().with_code(halide_type_int), matches[1])); } value = call_overloaded_intrin(op->type, pattern.intrin, matches); if (value) { return; } } } // Catch signed widening of absolute difference. // Catch widening of absolute difference Type t = op->type; if ((t.is_int() || t.is_uint()) && (op->value.type().is_int() || op->value.type().is_uint()) && t.bits() == op->value.type().bits() * 2) { if (const Call *absd = Call::as_intrinsic(op->value, {Call::absd})) { value = call_overloaded_intrin(t, "widening_absd", absd->args); return; } } // If we didn't find a pattern, try rewriting the cast. static const vector<pair<Expr, Expr>> cast_rewrites = { // Double or triple narrowing saturating casts are better expressed as // regular narrowing casts. {u8_sat(wild_u32x_), u8_sat(u16_sat(wild_u32x_))}, {u8_sat(wild_i32x_), u8_sat(i16_sat(wild_i32x_))}, {i8_sat(wild_u32x_), i8_sat(u16_sat(wild_u32x_))}, {i8_sat(wild_i32x_), i8_sat(i16_sat(wild_i32x_))}, {u16_sat(wild_u64x_), u16_sat(u32_sat(wild_u64x_))}, {u16_sat(wild_i64x_), u16_sat(i32_sat(wild_i64x_))}, {i16_sat(wild_u64x_), i16_sat(u32_sat(wild_u64x_))}, {i16_sat(wild_i64x_), i16_sat(i32_sat(wild_i64x_))}, {u8_sat(wild_u64x_), u8_sat(u16_sat(u32_sat(wild_u64x_)))}, {u8_sat(wild_i64x_), u8_sat(i16_sat(i32_sat(wild_i64x_)))}, {i8_sat(wild_u64x_), i8_sat(u16_sat(u32_sat(wild_u64x_)))}, {i8_sat(wild_i64x_), i8_sat(i16_sat(i32_sat(wild_i64x_)))}, }; for (const auto &i : cast_rewrites) { if (expr_match(i.first, op, matches)) { Expr replacement = substitute("*", matches[0], with_lanes(i.second, op->type.lanes())); debug(3) << "rewriting cast to: " << replacement << " from " << Expr(op) << "\n"; value = codegen(replacement); return; } } } CodeGen_Posix::visit(op); } void CodeGen_ARM::visit(const Sub *op) { if (neon_intrinsics_disabled()) { CodeGen_Posix::visit(op); return; } if (op->type.is_vector()) { vector<Expr> matches; for (size_t i = 0; i < negations.size(); i++) { if (expr_match(negations[i].pattern, op, matches)) { value = call_overloaded_intrin(op->type, negations[i].intrin, matches); return; } } } // llvm will generate floating point negate instructions if we ask for (-0.0f)-x if (op->type.is_float() && op->type.bits() >= 32 && is_const_zero(op->a)) { Constant *a; if (op->type.bits() == 32) { a = ConstantFP::getNegativeZero(f32_t); } else if (op->type.bits() == 64) { a = ConstantFP::getNegativeZero(f64_t); } else { a = nullptr; internal_error << "Unknown bit width for floating point type: " << op->type << "\n"; } Value *b = codegen(op->b); if (op->type.lanes() > 1) { a = ConstantVector::getSplat(element_count(op->type.lanes()), a); } value = builder->CreateFSub(a, b); return; } CodeGen_Posix::visit(op); } void CodeGen_ARM::visit(const Min *op) { // Use a 2-wide vector for scalar floats. if (!neon_intrinsics_disabled() && (op->type == Float(32) || op->type.is_vector())) { value = call_overloaded_intrin(op->type, "min", {op->a, op->b}); if (value) { return; } } CodeGen_Posix::visit(op); } void CodeGen_ARM::visit(const Max *op) { // Use a 2-wide vector for scalar floats. if (!neon_intrinsics_disabled() && (op->type == Float(32) || op->type.is_vector())) { value = call_overloaded_intrin(op->type, "max", {op->a, op->b}); if (value) { return; } } CodeGen_Posix::visit(op); } void CodeGen_ARM::visit(const Store *op) { // Predicated store if (!is_const_one(op->predicate)) { CodeGen_Posix::visit(op); return; } if (neon_intrinsics_disabled()) { CodeGen_Posix::visit(op); return; } // A dense store of an interleaving can be done using a vst2 intrinsic const Ramp *ramp = op->index.as<Ramp>(); // We only deal with ramps here if (!ramp) { CodeGen_Posix::visit(op); return; } // First dig through let expressions Expr rhs = op->value; vector<pair<string, Expr>> lets; while (const Let *let = rhs.as<Let>()) { rhs = let->body; lets.emplace_back(let->name, let->value); } const Shuffle *shuffle = rhs.as<Shuffle>(); // Interleaving store instructions only exist for certain types. bool type_ok_for_vst = false; Type intrin_type = Handle(); if (shuffle) { Type t = shuffle->vectors[0].type(); intrin_type = t; Type elt = t.element_of(); int vec_bits = t.bits() * t.lanes(); if (elt == Float(32) || elt == Int(8) || elt == Int(16) || elt == Int(32) || elt == UInt(8) || elt == UInt(16) || elt == UInt(32)) { if (vec_bits % 128 == 0) { type_ok_for_vst = true; intrin_type = intrin_type.with_lanes(128 / t.bits()); } else if (vec_bits % 64 == 0) { type_ok_for_vst = true; intrin_type = intrin_type.with_lanes(64 / t.bits()); } } } if (is_const_one(ramp->stride) && shuffle && shuffle->is_interleave() && type_ok_for_vst && 2 <= shuffle->vectors.size() && shuffle->vectors.size() <= 4) { const int num_vecs = shuffle->vectors.size(); vector<Value *> args(num_vecs); Type t = shuffle->vectors[0].type(); // Assume element-aligned. int alignment = t.bytes(); // Codegen the lets for (size_t i = 0; i < lets.size(); i++) { sym_push(lets[i].first, codegen(lets[i].second)); } // Codegen all the vector args. for (int i = 0; i < num_vecs; ++i) { args[i] = codegen(shuffle->vectors[i]); } // Declare the function std::ostringstream instr; vector<llvm::Type *> arg_types; if (target.bits == 32) { instr << "llvm.arm.neon.vst" << num_vecs << ".p0i8" << ".v" << intrin_type.lanes() << (t.is_float() ? 'f' : 'i') << t.bits(); arg_types = vector<llvm::Type *>(num_vecs + 2, llvm_type_of(intrin_type)); arg_types.front() = i8_t->getPointerTo(); arg_types.back() = i32_t; } else { instr << "llvm.aarch64.neon.st" << num_vecs << ".v" << intrin_type.lanes() << (t.is_float() ? 'f' : 'i') << t.bits() << ".p0" << (t.is_float() ? 'f' : 'i') << t.bits(); arg_types = vector<llvm::Type *>(num_vecs + 1, llvm_type_of(intrin_type)); arg_types.back() = llvm_type_of(intrin_type.element_of())->getPointerTo(); } llvm::FunctionType *fn_type = FunctionType::get(llvm::Type::getVoidTy(*context), arg_types, false); llvm::FunctionCallee fn = module->getOrInsertFunction(instr.str(), fn_type); internal_assert(fn); // How many vst instructions do we need to generate? int slices = t.lanes() / intrin_type.lanes(); internal_assert(slices >= 1); for (int i = 0; i < t.lanes(); i += intrin_type.lanes()) { Expr slice_base = simplify(ramp->base + i * num_vecs); Expr slice_ramp = Ramp::make(slice_base, ramp->stride, intrin_type.lanes() * num_vecs); Value *ptr = codegen_buffer_pointer(op->name, shuffle->vectors[0].type().element_of(), slice_base); vector<Value *> slice_args = args; // Take a slice of each arg for (int j = 0; j < num_vecs; j++) { slice_args[j] = slice_vector(slice_args[j], i, intrin_type.lanes()); } if (target.bits == 32) { // The arm32 versions take an i8*, regardless of the type stored. ptr = builder->CreatePointerCast(ptr, i8_t->getPointerTo()); // Set the pointer argument slice_args.insert(slice_args.begin(), ptr); // Set the alignment argument slice_args.push_back(ConstantInt::get(i32_t, alignment)); } else { // Set the pointer argument slice_args.push_back(ptr); } CallInst *store = builder->CreateCall(fn, slice_args); add_tbaa_metadata(store, op->name, slice_ramp); } // pop the lets from the symbol table for (size_t i = 0; i < lets.size(); i++) { sym_pop(lets[i].first); } return; } // If the stride is one or minus one, we can deal with that using vanilla codegen const IntImm *stride = ramp->stride.as<IntImm>(); if (stride && (stride->value == 1 || stride->value == -1)) { CodeGen_Posix::visit(op); return; } // We have builtins for strided stores with fixed but unknown stride, but they use inline assembly if (target.bits != 64 /* Not yet implemented for aarch64 */) { ostringstream builtin; builtin << "strided_store_" << (op->value.type().is_float() ? "f" : "i") << op->value.type().bits() << "x" << op->value.type().lanes(); llvm::Function *fn = module->getFunction(builtin.str()); if (fn) { Value *base = codegen_buffer_pointer(op->name, op->value.type().element_of(), ramp->base); Value *stride = codegen(ramp->stride * op->value.type().bytes()); Value *val = codegen(op->value); debug(4) << "Creating call to " << builtin.str() << "\n"; Value *store_args[] = {base, stride, val}; Instruction *store = builder->CreateCall(fn, store_args); (void)store; add_tbaa_metadata(store, op->name, op->index); return; } } CodeGen_Posix::visit(op); } void CodeGen_ARM::visit(const Load *op) { // Predicated load if (!is_const_one(op->predicate)) { CodeGen_Posix::visit(op); return; } if (neon_intrinsics_disabled()) { CodeGen_Posix::visit(op); return; } const Ramp *ramp = op->index.as<Ramp>(); // We only deal with ramps here if (!ramp) { CodeGen_Posix::visit(op); return; } // If the stride is in [-1, 4], we can deal with that using vanilla codegen const IntImm *stride = ramp ? ramp->stride.as<IntImm>() : nullptr; if (stride && (-1 <= stride->value && stride->value <= 4)) { CodeGen_Posix::visit(op); return; } // We have builtins for strided loads with fixed but unknown stride, but they use inline assembly. if (target.bits != 64 /* Not yet implemented for aarch64 */) { ostringstream builtin; builtin << "strided_load_" << (op->type.is_float() ? "f" : "i") << op->type.bits() << "x" << op->type.lanes(); llvm::Function *fn = module->getFunction(builtin.str()); if (fn) { Value *base = codegen_buffer_pointer(op->name, op->type.element_of(), ramp->base); Value *stride = codegen(ramp->stride * op->type.bytes()); debug(4) << "Creating call to " << builtin.str() << "\n"; Value *args[] = {base, stride}; Instruction *load = builder->CreateCall(fn, args, builtin.str()); add_tbaa_metadata(load, op->name, op->index); value = load; return; } } CodeGen_Posix::visit(op); } void CodeGen_ARM::visit(const Call *op) { if (op->is_intrinsic(Call::sorted_avg)) { value = codegen(halving_add(op->args[0], op->args[1])); return; } if (op->is_intrinsic(Call::rounding_shift_right)) { // LLVM wants these as rounding_shift_left with a negative b instead. Expr b = op->args[1]; if (!b.type().is_int()) { b = Cast::make(b.type().with_code(halide_type_int), b); } value = codegen(rounding_shift_left(op->args[0], simplify(-b))); return; } else if (op->is_intrinsic(Call::widening_shift_right) && op->args[1].type().is_int()) { // We want these as left shifts with a negative b instead. value = codegen(widening_shift_left(op->args[0], simplify(-op->args[1]))); return; } else if (op->is_intrinsic(Call::shift_right) && op->args[1].type().is_int()) { // We want these as left shifts with a negative b instead. value = codegen(op->args[0] << simplify(-op->args[1])); return; } if (op->type.is_vector()) { vector<Expr> matches; for (const Pattern &pattern : calls) { if (expr_match(pattern.pattern, op, matches)) { value = call_overloaded_intrin(op->type, pattern.intrin, matches); if (value) { return; } } } } CodeGen_Posix::visit(op); } void CodeGen_ARM::visit(const LT *op) { if (op->a.type().is_float() && op->type.is_vector()) { // Fast-math flags confuse LLVM's aarch64 backend, so // temporarily clear them for this instruction. // See https://bugs.llvm.org/show_bug.cgi?id=45036 llvm::IRBuilderBase::FastMathFlagGuard guard(*builder); builder->clearFastMathFlags(); CodeGen_Posix::visit(op); return; } CodeGen_Posix::visit(op); } void CodeGen_ARM::visit(const LE *op) { if (op->a.type().is_float() && op->type.is_vector()) { // Fast-math flags confuse LLVM's aarch64 backend, so // temporarily clear them for this instruction. // See https://bugs.llvm.org/show_bug.cgi?id=45036 llvm::IRBuilderBase::FastMathFlagGuard guard(*builder); builder->clearFastMathFlags(); CodeGen_Posix::visit(op); return; } CodeGen_Posix::visit(op); } void CodeGen_ARM::codegen_vector_reduce(const VectorReduce *op, const Expr &init) { if (neon_intrinsics_disabled() || op->op == VectorReduce::Or || op->op == VectorReduce::And || op->op == VectorReduce::Mul) { CodeGen_Posix::codegen_vector_reduce(op, init); return; } struct Pattern { VectorReduce::Operator reduce_op; int factor; Expr pattern; const char *intrin; Target::Feature required_feature; }; // clang-format off static const Pattern patterns[] = { {VectorReduce::Add, 4, i32(widening_mul(wild_i8x_, wild_i8x_)), "dot_product", Target::ARMDotProd}, {VectorReduce::Add, 4, i32(widening_mul(wild_u8x_, wild_u8x_)), "dot_product", Target::ARMDotProd}, {VectorReduce::Add, 4, u32(widening_mul(wild_u8x_, wild_u8x_)), "dot_product", Target::ARMDotProd}, }; // clang-format on int factor = op->value.type().lanes() / op->type.lanes(); vector<Expr> matches; for (const Pattern &p : patterns) { if (op->op != p.reduce_op || factor % p.factor != 0) { continue; } if (!target.has_feature(p.required_feature)) { continue; } if (expr_match(p.pattern, op->value, matches)) { if (factor != 4) { Expr equiv = VectorReduce::make(op->op, op->value, op->value.type().lanes() / 4); equiv = VectorReduce::make(op->op, equiv, op->type.lanes()); codegen_vector_reduce(equiv.as<VectorReduce>(), init); return; } Expr i = init; if (!i.defined()) { i = make_zero(op->type); } if (const Shuffle *s = matches[0].as<Shuffle>()) { if (s->is_broadcast()) { // LLVM wants the broadcast as the second operand for the broadcasting // variant of udot/sdot. std::swap(matches[0], matches[1]); } } value = call_overloaded_intrin(op->type, p.intrin, {i, matches[0], matches[1]}); if (value) { return; } } } // TODO: Move this to be patterns? The patterns are pretty trivial, but some // of the other logic is tricky. const char *intrin = nullptr; vector<Expr> intrin_args; Expr accumulator = init; if (op->op == VectorReduce::Add && factor == 2) { Type narrow_type = op->type.narrow().with_lanes(op->value.type().lanes()); Expr narrow = lossless_cast(narrow_type, op->value); if (!narrow.defined() && op->type.is_int()) { // We can also safely accumulate from a uint into a // wider int, because the addition uses at most one // extra bit. narrow = lossless_cast(narrow_type.with_code(Type::UInt), op->value); } if (narrow.defined()) { if (init.defined() && target.bits == 32) { // On 32-bit, we have an intrinsic for widening add-accumulate. intrin = "pairwise_widening_add_accumulate"; intrin_args = {accumulator, narrow}; accumulator = Expr(); } else { // On 64-bit, LLVM pattern matches widening add-accumulate if // we give it the widening add. intrin = "pairwise_widening_add"; intrin_args = {narrow}; } } else { intrin = "pairwise_add"; intrin_args = {op->value}; } } else if (op->op == VectorReduce::Min && factor == 2) { intrin = "pairwise_min"; intrin_args = {op->value}; } else if (op->op == VectorReduce::Max && factor == 2) { intrin = "pairwise_max"; intrin_args = {op->value}; } if (intrin) { value = call_overloaded_intrin(op->type, intrin, intrin_args); if (value) { if (accumulator.defined()) { // We still have an initial value to take care of string n = unique_name('t'); sym_push(n, value); Expr v = Variable::make(accumulator.type(), n); switch (op->op) { case VectorReduce::Add: accumulator += v; break; case VectorReduce::Min: accumulator = min(accumulator, v); break; case VectorReduce::Max: accumulator = max(accumulator, v); break; default: internal_error << "unreachable"; } codegen(accumulator); sym_pop(n); } return; } } CodeGen_Posix::codegen_vector_reduce(op, init); } string CodeGen_ARM::mcpu() const { if (target.bits == 32) { if (target.has_feature(Target::ARMv7s)) { return "swift"; } else { return "cortex-a9"; } } else { if (target.os == Target::IOS) { return "cyclone"; } else if (target.os == Target::OSX) { return "apple-a12"; } else { return "generic"; } } } string CodeGen_ARM::mattrs() const { if (target.bits == 32) { if (target.has_feature(Target::ARMv7s)) { return "+neon"; } if (!target.has_feature(Target::NoNEON)) { return "+neon"; } else { return "-neon"; } } else { // TODO: Should Halide's SVE flags be 64-bit only? string arch_flags; string separator; if (target.has_feature(Target::SVE2)) { arch_flags = "+sve2"; separator = ","; } else if (target.has_feature(Target::SVE)) { arch_flags = "+sve"; separator = ","; } if (target.has_feature(Target::ARMv81a)) { arch_flags += separator + "+v8.1a"; separator = ","; } if (target.has_feature(Target::ARMDotProd)) { arch_flags += separator + "+dotprod"; separator = ","; } if (target.os == Target::IOS || target.os == Target::OSX) { return arch_flags + separator + "+reserve-x18"; } else { return arch_flags; } } } bool CodeGen_ARM::use_soft_float_abi() const { // One expects the flag is irrelevant on 64-bit, but we'll make the logic // exhaustive anyway. It is not clear the armv7s case is necessary either. return target.has_feature(Target::SoftFloatABI) || (target.bits == 32 && ((target.os == Target::Android) || (target.os == Target::IOS && !target.has_feature(Target::ARMv7s)))); } int CodeGen_ARM::native_vector_bits() const { return 128; } } // namespace std::unique_ptr<CodeGen_Posix> new_CodeGen_ARM(const Target &target) { return std::make_unique<CodeGen_ARM>(target); } #else // WITH_ARM || WITH_AARCH64 std::unique_ptr<CodeGen_Posix> new_CodeGen_ARM(const Target &target) { user_error << "ARM not enabled for this build of Halide.\n"; return nullptr; } #endif // WITH_ARM || WITH_AARCH64 } // namespace Internal } // namespace Halide
71,325
28,897
/* * Copyright (C) 2009-2021 Intel Corporation. * SPDX-License-Identifier: MIT */ /*! @file * This application verifies that pin tool can correctly emulate exceptions on behalf of the application */ #include <string> #include <iostream> #include <fpieee.h> #include <excpt.h> #include <float.h> #if defined(TARGET_WINDOWS) #include "windows.h" #define EXPORT_CSYM extern "C" __declspec(dllexport) #else #error Unsupported OS #endif using std::cout; using std::endl; using std::flush; using std::hex; using std::string; //========================================================================== // Printing utilities //========================================================================== string UnitTestName("internal_exception_handler_app"); string FunctionTestName; static void StartFunctionTest(const string& functionTestName) { if (FunctionTestName != "") { cout << UnitTestName << "[" << FunctionTestName << "] Success" << endl << flush; } FunctionTestName = functionTestName; } static void ExitUnitTest() { if (FunctionTestName != "") { cout << UnitTestName << "[" << FunctionTestName << "] Success" << endl << flush; } cout << UnitTestName << " : Completed successfully" << endl << flush; exit(0); } static void Abort(const string& msg) { cout << UnitTestName << "[" << FunctionTestName << "] Failure: " << msg << endl << flush; exit(1); } //========================================================================== // Exception handling utilities //========================================================================== /*! * Exception filter for the ExecuteSafe function: copy the exception record * to the specified structure. * @param[in] exceptPtr pointers to the exception context and the exception * record prepared by the system * @param[in] pExceptRecord pointer to the structure that receives the * exception record * @return the exception disposition */ static int SafeExceptionFilter(LPEXCEPTION_POINTERS exceptPtr) { return EXCEPTION_EXECUTE_HANDLER; } static int SafeExceptionFilterFloating(_FPIEEE_RECORD* pieee) { return EXCEPTION_EXECUTE_HANDLER; } /*! * Execute the specified function and return to the caller even if the function raises * an exception. * @param[in] pExceptRecord pointer to the structure that receives the * exception record if the function raises an exception * @return TRUE, if the function raised an exception */ template< typename FUNC > bool ExecuteSafe(FUNC fp, DWORD* pExceptCode) { __try { fp(); return false; } __except (*pExceptCode = GetExceptionCode(), SafeExceptionFilter(GetExceptionInformation())) { return true; } } #pragma float_control(except, on) template< typename FUNC > bool ExecuteSafeFloating(FUNC fp, DWORD* pExceptCode) { unsigned int currentControl; errno_t err = _controlfp_s(&currentControl, ~_EM_ZERODIVIDE, _MCW_EM); __try { fp(); return false; } __except (*pExceptCode = GetExceptionCode(), SafeExceptionFilter(GetExceptionInformation()) /*_fpieee_flt( GetExceptionCode(), GetExceptionInformation(), SafeExceptionFilterFloating )*/) { return true; } } /*! * The tool replaces this function and raises the EXCEPTION_INT_DIVIDE_BY_ZERO system exception. */ EXPORT_CSYM void RaiseIntDivideByZeroException() { volatile int zero = 0; volatile int i = 1 / zero; } /*! * The tool replaces this function and raises the EXCEPTION_FLT_DIVIDE_BY_ZERO system exception. */ EXPORT_CSYM void RaiseFltDivideByZeroException() { volatile float zero = 0.0; volatile float i = 1.0 / zero; } EXPORT_CSYM void End() { return; } /*! * The tool replace this function and raises the specified system exception. */ EXPORT_CSYM void RaiseSystemException(unsigned int sysExceptCode) { RaiseException(sysExceptCode, 0, 0, NULL); } /*! * Check to see if the specified exception record represents an exception with the * specified exception code. */ static bool CheckExceptionCode(DWORD exceptCode, DWORD expectedExceptCode) { if (exceptCode != expectedExceptCode) { cout << "Unexpected exception code " << hex << exceptCode << ". Should be " << hex << expectedExceptCode << endl << flush; return false; } return true; } /*! * Convert a pointer to <SRC> type into a pointer to <DST> type. * Allows any combination of data/function types. */ #if defined(TARGET_IA32) || defined(TARGET_IA32E) template< typename DST, typename SRC > DST* CastPtr(SRC* src) { union CAST { DST* dstPtr; SRC* srcPtr; } cast; cast.srcPtr = src; return cast.dstPtr; } #else #error Unsupported architechture #endif typedef void FUNC_NOARGS(); /*! * The main procedure of the application. */ int main(int argc, char* argv[]) { DWORD exceptCode; bool exceptionCaught; // Raise int divide by zero exception in the tool StartFunctionTest("Raise int divide by zero in the tool"); exceptionCaught = ExecuteSafe(RaiseIntDivideByZeroException, &exceptCode); if (!exceptionCaught) { Abort("Unhandled exception"); } if (!CheckExceptionCode(exceptCode, EXCEPTION_INT_DIVIDE_BY_ZERO)) { Abort("Incorrect exception information (EXCEPTION_INT_DIVIDE_BY_ZERO)"); } // Raise flt divide by zero exception in the tool StartFunctionTest("Raise FP divide by zero in the tool"); exceptionCaught = ExecuteSafeFloating(RaiseFltDivideByZeroException, &exceptCode); if (!exceptionCaught) { Abort("Unhandled exception"); } if (EXCEPTION_FLT_DIVIDE_BY_ZERO != exceptCode && STATUS_FLOAT_MULTIPLE_TRAPS != exceptCode) { CheckExceptionCode(exceptCode, EXCEPTION_FLT_DIVIDE_BY_ZERO); // For reporting only Abort("Incorrect exception information (EXCEPTION_FLT_DIVIDE_BY_ZERO)"); } ExitUnitTest(); }
6,051
1,876
#include "Cylinder.h" #include "core/world.h" #include "core/application.h" #include "core/components/model.h" #include "platform/resource.h" #include "platform/renderer.h" #include "core/components/fps_controller.h" #include "core/components/directional_light.h" #include <glm/gtc/quaternion.hpp> namespace pronto { //----------------------------------------------------------------------------------------------- Cylinder::Cylinder(World* world) : Entity(world), model_(nullptr) { model_ = AddComponent<Model>(); model_->SetModel("resource/cylinder/scene.gltf"); transform()->SetScale(glm::vec3(0.05f)); AddComponent<DirectionalLight>(); } void Cylinder::Update() { Entity::Update(); } }
734
243
/* * Copyright (c) 2018, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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 <Argus/Argus.h> #include "ArgusHelpers.h" #include "CommonOptions.h" #include "CudaBayerDemosaicConsumer.h" namespace ArgusSamples { /** * Main thread function opens connection to Argus driver, creates a capture session for * a given camera device and sensor mode, then creates a RAW16 stream attached to a * CudaBayerConsumer such that the CUDA consumer will acquire the outputs of capture * results as raw Bayer data (which it then demosaics to RGBA for demonstration purposes). */ static bool execute(const CommonOptions& options) { EGLDisplayHolder eglDisplay; // Initialize the preview window and EGL display. Window &window = Window::getInstance(); window.setWindowRect(options.windowRect()); PROPAGATE_ERROR(eglDisplay.initialize(window.getEGLNativeDisplay())); // Create the Argus CameraProvider object UniqueObj<CameraProvider> cameraProvider(CameraProvider::create()); ICameraProvider *iCameraProvider = interface_cast<ICameraProvider>(cameraProvider); if (!iCameraProvider) { ORIGINATE_ERROR("Failed to create CameraProvider"); } printf("Argus Version: %s\n", iCameraProvider->getVersion().c_str()); // Get the selected camera device and sensor mode. CameraDevice* cameraDevice = ArgusHelpers::getCameraDevice( cameraProvider.get(), options.cameraDeviceIndex()); if (!cameraDevice) ORIGINATE_ERROR("Selected camera device is not available"); SensorMode* sensorMode = ArgusHelpers::getSensorMode(cameraDevice, options.sensorModeIndex()); ISensorMode *iSensorMode = interface_cast<ISensorMode>(sensorMode); if (!iSensorMode) ORIGINATE_ERROR("Selected sensor mode not available"); // Create the capture session using the selected device. UniqueObj<CaptureSession> captureSession(iCameraProvider->createCaptureSession(cameraDevice)); ICaptureSession *iCaptureSession = interface_cast<ICaptureSession>(captureSession); if (!iCaptureSession) { ORIGINATE_ERROR("Failed to create CaptureSession"); } // Create the RAW16 output EGLStream using the sensor mode resolution. UniqueObj<OutputStreamSettings> streamSettings( iCaptureSession->createOutputStreamSettings(STREAM_TYPE_EGL)); IEGLOutputStreamSettings *iEGLStreamSettings = interface_cast<IEGLOutputStreamSettings>(streamSettings); if (!iEGLStreamSettings) { ORIGINATE_ERROR("Failed to create OutputStreamSettings"); } iEGLStreamSettings->setEGLDisplay(eglDisplay.get()); iEGLStreamSettings->setPixelFormat(PIXEL_FMT_RAW16); iEGLStreamSettings->setResolution(iSensorMode->getResolution()); iEGLStreamSettings->setMode(EGL_STREAM_MODE_FIFO); UniqueObj<OutputStream> outputStream(iCaptureSession->createOutputStream(streamSettings.get())); IEGLOutputStream *iEGLOutputStream = interface_cast<IEGLOutputStream>(outputStream); if (!iEGLOutputStream) { ORIGINATE_ERROR("Failed to create EGLOutputStream"); } // Create capture request and enable output stream. UniqueObj<Request> request(iCaptureSession->createRequest()); IRequest *iRequest = interface_cast<IRequest>(request); if (!iRequest) { ORIGINATE_ERROR("Failed to create Request"); } iRequest->enableOutputStream(outputStream.get()); // Set the sensor mode in the request. ISourceSettings *iSourceSettings = interface_cast<ISourceSettings>(request); if (!iSourceSettings) ORIGINATE_ERROR("Failed to get source settings request interface"); iSourceSettings->setSensorMode(sensorMode); // Create the CUDA Bayer consumer and connect it to the RAW16 output stream. CudaBayerDemosaicConsumer cudaConsumer(iEGLOutputStream->getEGLDisplay(), iEGLOutputStream->getEGLStream(), iEGLStreamSettings->getResolution(), options.frameCount()); PROPAGATE_ERROR(cudaConsumer.initialize()); PROPAGATE_ERROR(cudaConsumer.waitRunning()); // Submit the batch of capture requests. for (unsigned int frame = 0; frame < options.frameCount(); ++frame) { Argus::Status status; uint32_t result = iCaptureSession->capture(request.get(), TIMEOUT_INFINITE, &status); if (result == 0) { ORIGINATE_ERROR("Failed to submit capture request (status %x)", status); } } // Wait until all captures have completed. iCaptureSession->waitForIdle(); // Shutdown the CUDA consumer. PROPAGATE_ERROR(cudaConsumer.shutdown()); return true; } }; // namespace ArgusSamples int main(int argc, char** argv) { printf("Executing Argus Sample: %s\n", basename(argv[0])); ArgusSamples::CommonOptions options(basename(argv[0]), ArgusSamples::CommonOptions::Option_D_CameraDevice | ArgusSamples::CommonOptions::Option_M_SensorMode | ArgusSamples::CommonOptions::Option_R_WindowRect | ArgusSamples::CommonOptions::Option_F_FrameCount); if (!options.parse(argc, argv)) return EXIT_FAILURE; if (options.requestedExit()) return EXIT_SUCCESS; if (!ArgusSamples::execute(options)) return EXIT_FAILURE; printf("Argus sample '%s' completed successfully.\n", basename(argv[0])); return EXIT_SUCCESS; }
7,086
2,084
/** * Copyright (c) 2018, University Osnabrück * 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 University Osnabrück 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 University Osnabrück 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. */ /* * OptionsDMC.hpp * * Created on: May 13, 2020 * Author: Benedikt SChumacher */ #ifndef OPTIONSDMC_H_ #define OPTIONSDMC_H_ #include "lvr2/config/BaseOption.hpp" #include <boost/program_options.hpp> #include <float.h> #include <iostream> #include <string> #include <vector> using std::cout; using std::endl; using std::ostream; using std::string; using std::vector; using namespace lvr2; namespace dmc_reconstruction { class Options : public BaseOption { public: Options(int argc, char** argv); virtual ~Options(); string getInputFileName() const; int getMaxLevel() const; float getMaxError() const; /* * prints information about needed command-line-inputs e.g: input-file (ply) */ bool printUsage() const; int getKd() const; int getKn() const; int getKi() const; int getNumThreads() const; string getPCM() const; bool useRansac() const; string getScanPoseFile() const; private: /// The maximum allows octree level int m_maxLevel; /// The max allowed error between points and surfaces in an octree cell float m_maxError; /// The number of neighbors for distance function evaluation int m_kd; /// The number of neighbors for normal estimation int m_kn; /// The number of neighbors for normal interpolation int m_ki; /// The number of threads to use int m_numThreads; /// The used point cloud manager string m_pcm; }; /// Output the Options - overloaded output Operator inline ostream& operator<<(ostream& os, const Options& o) { // o.printTransformation(os); cout << "##### InputFile-Name: " << o.getInputFileName() << endl; cout << "##### Max Level: " << o.getMaxLevel() << endl; cout << "##### Max Error: " << o.getMaxError() << endl; cout << "##### PCM: " << o.getPCM() << endl; cout << "##### KD: " << o.getKd() << endl; cout << "##### KI: " << o.getKi() << endl; cout << "##### KN: " << o.getKn() << endl; return os; } } // namespace dmc_reconstruction #endif // OPTIONSDMC_H_
3,680
1,238
// /* Slightly modified versions of the "polint" routine from // * Press, William H., Brian P. Flannery, Saul A. Teukolsky and // * William T. Vetterling, 1986, "Numerical Recipes: The Art of // * Scientific Computing" (Fortran), Cambrigde University Press, // * pp. 80-82. // */ // // #include <stdio.h> // #include <malloc.h> // #include <math.h> // // void polint( double *xa, double *ya, int n, double x, double *y, double *dy ); // // void polint( double *xa, double *ya, int n, double x, double *y, double *dy ) // { // double *c = NULL; // double *d = NULL; // double den; // double dif; // double dift; // double ho; // double hp; // double w; // // int i; // int m; // int ns; // // if( (c = (double *)malloc( n * sizeof( double ) )) == NULL || // (d = (double *)malloc( n * sizeof( double ) )) == NULL ) { // fprintf( stderr, "polint error: allocating workspace\n" ); // fprintf( stderr, "polint error: setting y = 0 and dy = 1e9\n" ); // *y = 0.0; // *dy = 1.e9; // // if( c != NULL ) // free( c ); // if( d != NULL ) // free( d ); // return; // } // // ns = 0; // dif = fabs(x-xa[0]); // for( i = 0; i < n; ++i ) { // dift = fabs( x-xa[i] ); // if( dift < dif ) { // ns = i; // dif = dift; // } // c[i] = ya[i]; // d[i] = ya[i]; // } // *y = ya[ns]; // ns = ns-1; // for( m = 0; m < n-1; ++m ) { // for( i = 0; i < n-m-1; ++i ) { // ho = xa[i]-x; // hp = xa[i+m+1]-x; // w = c[i+1]-d[i]; // den = ho-hp; // if( den == 0 ) { // fprintf( stderr, "polint error: den = 0\n" ); // fprintf( stderr, "polint error: setting y = 0 and dy = 1e9\n" ); // *y = 0.0; // *dy = 1.e9; // // if( c != NULL ) // free( c ); // if( d != NULL ) // free( d ); // return; // } // den = w/den; // d[i] = hp*den; // c[i] = ho*den; // } // if( 2*(ns+1) < n-m-1 ) { // *dy = c[ns+1]; // } else { // *dy = d[ns]; // ns = ns-1; // } // *y = (*y)+(*dy); // } // // // if( c != NULL ) // free( c ); // if( d != NULL ) // free( d ); // return; // }
2,558
978
#pragma once #include "schemas/ev42_events_generated.h" // WARNING: // the schema has to match to the serialise template type // this must change namespace SINQAmorSim { /// \author Michele Brambilla <mib.mic@gmail.com> /// \date Thu Jul 28 14:32:29 2016 class FlatBufferSerialiser { public: FlatBufferSerialiser(const std::string &source_name = "AMOR.event.stream") : source{source_name} {} FlatBufferSerialiser(const FlatBufferSerialiser &other) = default; FlatBufferSerialiser(FlatBufferSerialiser &&other) = default; ~FlatBufferSerialiser() = default; // WARNING: template parameter has to match schema data type template <class T> std::vector<char> &serialise(const int &message_id, const std::chrono::nanoseconds &pulse_time, const std::vector<T> &message = {}) { auto nev = message.size() / 2; flatbuffers::FlatBufferBuilder builder; auto source_name = builder.CreateString(source); auto time_of_flight = builder.CreateVector(&message[0], nev); auto detector_id = builder.CreateVector(&message[nev], nev); auto event = CreateEventMessage(builder, source_name, message_id, pulse_time.count(), time_of_flight, detector_id); FinishEventMessageBuffer(builder, event); buffer_.resize(builder.GetSize()); buffer_.assign(builder.GetBufferPointer(), builder.GetBufferPointer() + builder.GetSize()); return buffer_; } template <class T> void extract(const std::vector<char> &message, std::vector<T> &data, uint64_t &pid, std::chrono::nanoseconds &pulse_time, std::string &source_name) { extract_impl<T>(static_cast<const void *>(&message[0]), data, pid, pulse_time, source_name); } template <class T> void extract(const char *msg, std::vector<T> &data, uint64_t &pid, std::chrono::nanoseconds &pulse_time, std::string &source_name) { extract_impl<T>(static_cast<const void *>(msg), data, pid, pulse_time, source_name); } char *get() { return &buffer_[0]; } size_t size() { return buffer_.size(); } const std::vector<char> &buffer() { return buffer_; } bool verify() { auto p = const_cast<const char *>(&buffer_[0]); flatbuffers::Verifier verifier(reinterpret_cast<const unsigned char *>(p), buffer_.size()); return VerifyEventMessageBuffer(verifier); } bool verify(const std::vector<char> &other) { auto p = const_cast<const char *>(&other[0]); flatbuffers::Verifier verifier(reinterpret_cast<const unsigned char *>(p), buffer_.size()); return VerifyEventMessageBuffer(verifier); } private: template <class T> void extract_impl(const void *msg, std::vector<T> &data, uint64_t &pid, std::chrono::nanoseconds &pulse_time, std::string &source_name) { auto event = GetEventMessage(msg); data.resize(2 * event->time_of_flight()->size()); std::copy(event->time_of_flight()->begin(), event->time_of_flight()->end(), data.begin()); std::copy(event->detector_id()->begin(), event->detector_id()->end(), data.begin() + event->time_of_flight()->size()); pid = event->message_id(); size_t timestamp = event->pulse_time(); pulse_time = std::chrono::nanoseconds(timestamp); source_name = std::string{event->source_name()->c_str()}; } std::vector<char> buffer_; std::string source; }; /// \author Michele Brambilla <mib.mic@gmail.com> /// \date Fri Jun 17 12:22:01 2016 class NoSerialiser { public: NoSerialiser(const std::string & = "") {} NoSerialiser(const NoSerialiser &other) = default; NoSerialiser(NoSerialiser &&other) = default; ~NoSerialiser() = default; NoSerialiser() = default; char *get() { return nullptr; } const int size() { return 0; } }; } // serialiser
3,991
1,281
// MacroCommandTestVO.hpp // PureMVC_C++ Test suite // // PureMVC Port to C++ by Tang Khai Phuong <phuong.tang@puremvc.org> // PureMVC - Copyright(c) 2006-2011 Futurescale, Inc., Some rights reserved. // Your reuse is governed by the Creative Commons Attribution 3.0 License // #if !defined(MACRO_COMMAND_TEST_VO_HPP) #define MACRO_COMMAND_TEST_VO_HPP namespace data { /** * A utility class used by MacroCommandTest. */ struct MacroCommandTestVO { int input; int result1; int result2; /** * Constructor. * * @param input the number to be fed to the MacroCommandTestCommand */ MacroCommandTestVO(int input) { this->input = input; this->result1 = 0; this->result2 = 0; } }; } #endif /* MACRO_COMMAND_TEST_VO_HPP */
910
321
#include <bits/stdc++.h> using namespace std; template <typename T> using V = vector<T>; typedef long double ld; typedef long long ll; #define FO(i, N) for (int (i) = 0; (i) < (N); ++(i)) #define FOll(i, N) for (ll (i) = 0; (i) < (N); ++(i)) #define READALL(c) for (auto &e : c) { cin >> e; } #define PRINTALL(c) for (const auto &e : c) { cout << e << " "; } cout << "\n"; #define MP(x, y) (make_pair((x), (y))) #define MT(...) make_tuple(__VA_ARGS__) #define ALL(x) begin(x), end(x) #define D(x...) fprintf(stderr, x) const int MAXN = 500, MAXQ = 1e7; int R, C, Q; ll DPul[MAXN+5][MAXN+5], DPbr[MAXN+5][MAXN+5], G[MAXN+5][MAXN+5], GG[MAXN+5][MAXN+5], ans[MAXQ]; tuple<int,int,int,int> Qs[MAXQ]; void fill_dp(int r, int c, int minr, int minc, int maxr, int maxc) { for (int i = minr-1; i <= maxr+1; ++i) for (int j = minc-1; j <= maxc+1; ++j) DPul[i][j] = DPbr[i][j] = -1e18; DPul[r+1][c]=0; for (int i = r; i >= minr; --i) for (int j = c; j >= minc; --j) DPul[i][j] = max(DPul[i+1][j],DPul[i][j+1])+G[i][j]; DPbr[r-1][c]=0; for (int i = r; i <= maxr; ++i) for (int j = c; j <= maxc; ++j) DPbr[i][j] = max(DPbr[i-1][j],DPbr[i][j-1])+G[i][j]; } void dc(int minr, int minc, int maxr, int maxc, vector<int> query_inds) { if (minr > maxr || minc > maxc) return; int r, c = (maxc+minc)/2; vector<int> query_inds_tmp; for (int i : query_inds) { int qr, qc, qrr, qcc; tie(qr, qc, qrr, qcc) = Qs[i]; if (qr < minr || qc < minc || qr > maxr || qc > maxc) continue; if (qrr < minr || qcc < minc || qrr > maxr || qcc > maxc) continue; query_inds_tmp.push_back(i); } query_inds = query_inds_tmp; if (query_inds.size() == 0) return; for (r = minr; r <= maxr; ++r) { fill_dp(r, c, minr, minc, maxr, maxc); for (int i : query_inds) { int qr, qc, qrr, qcc; tie(qr, qc, qrr, qcc) = Qs[i]; if (qr <= r && qrr >= r && qc <= c && qcc >= c) { ans[i] = max(ans[i], DPul[qr][qc]+DPbr[qrr][qcc]-G[r][c]); } } } r = (minr+maxr)/2; for (c = minc; c <= maxc; ++c) if (c != (maxc+minc)/2 && G[r][c] != '1') { fill_dp(r, c, minr, minc, maxr, maxc); for (int i : query_inds) { int qr, qc, qrr, qcc; tie(qr, qc, qrr, qcc) = Qs[i]; if (qr <= r && qrr >= r && qc <= c && qcc >= c) { ans[i] = max(ans[i], DPul[qr][qc]+DPbr[qrr][qcc]-G[r][c]); } } } dc(minr, minc, (maxr+minr)/2-1, (maxc+minc)/2-1, query_inds); dc(minr, (maxc+minc)/2+1, (maxr+minr)/2-1, maxc, query_inds); dc((maxr+minr)/2+1, minc, maxr, (maxc+minc)/2-1, query_inds); dc((maxr+minr)/2+1, (maxc+minc)/2+1, maxr, maxc, query_inds); } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> R >> C; FO(i,R) FO(j,C) { cin >> GG[i+1][j+1]; G[i+1][j+1] = max(GG[i+1][j+1],0ll); } cin >> Q; V<int> all_inds; FO(i,Q) { int x,y,xx,yy; cin>>x>>y>>xx>>yy; Qs[i] = make_tuple(x,y,xx,yy); all_inds.push_back(i); } if(Q == 0) { Q++; Qs[0] = make_tuple(1, 1, R, C); all_inds.push_back(0); } fill(ans,ans+Q,-1e18); dc(1,1,R,C,all_inds); for(int i = 0; i < Q; i++) { int x,y,xx,yy; tie(x, y, xx, yy) = Qs[i]; if (GG[x][y] < 0) { ans[i] += GG[x][y]; } if (GG[xx][yy] < 0) { ans[i] += GG[xx][yy]; } } FO(i,Q) cout << ans[i] << "\n"; }
3,289
1,807
/* * Copyright 2013-2021 Will Mason * * 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 <chucho/kafka_configuration.hpp> #include <chucho/exception.hpp> namespace chucho { kafka_configuration::kafka_configuration(const std::map<std::string, std::string>& key_values) : conf_(rd_kafka_conf_new()) { char msg[1024]; for (auto& p : key_values) { auto rc = rd_kafka_conf_set(conf_, p.first.c_str(), p.second.c_str(), msg, sizeof(msg)); if (rc != RD_KAFKA_CONF_OK) throw exception("kafka_writer_factory: Error setting Kafka configuration (" + p.first + ", " + p.second + "): " + msg); } } kafka_configuration::~kafka_configuration() { if (conf_ != nullptr) rd_kafka_conf_destroy(conf_); } rd_kafka_conf_t* kafka_configuration::get_conf() { auto local = conf_; conf_ = nullptr; return local; } }
1,413
469
#ifndef GODOT_CPP_TEXTURELAYERED_HPP #define GODOT_CPP_TEXTURELAYERED_HPP #include <gdnative_api_struct.gen.h> #include <stdint.h> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include "Image.hpp" #include "Resource.hpp" namespace godot { class Image; class TextureLayered : public Resource { struct ___method_bindings { godot_method_bind *mb__get_data; godot_method_bind *mb__set_data; godot_method_bind *mb_create; godot_method_bind *mb_get_depth; godot_method_bind *mb_get_flags; godot_method_bind *mb_get_format; godot_method_bind *mb_get_height; godot_method_bind *mb_get_layer_data; godot_method_bind *mb_get_width; godot_method_bind *mb_set_data_partial; godot_method_bind *mb_set_flags; godot_method_bind *mb_set_layer_data; }; static ___method_bindings ___mb; public: static void ___init_method_bindings(); static inline const char *___get_class_name() { return (const char *) "TextureLayered"; } static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; } // enums enum Flags { FLAG_MIPMAPS = 1, FLAG_REPEAT = 2, FLAG_FILTER = 4, FLAGS_DEFAULT = 4, }; // constants // methods Dictionary _get_data() const; void _set_data(const Dictionary data); void create(const int64_t width, const int64_t height, const int64_t depth, const int64_t format, const int64_t flags = 4); int64_t get_depth() const; int64_t get_flags() const; Image::Format get_format() const; int64_t get_height() const; Ref<Image> get_layer_data(const int64_t layer) const; int64_t get_width() const; void set_data_partial(const Ref<Image> image, const int64_t x_offset, const int64_t y_offset, const int64_t layer, const int64_t mipmap = 0); void set_flags(const int64_t flags); void set_layer_data(const Ref<Image> image, const int64_t layer); }; } #endif
1,995
812
#include "ProgramState.h" using namespace std; ProgramState::ProgramState(int numLines){ m_numLines = numLines; m_nextLine = 1; m_line = 0; m_over = 0; } void ProgramState::updateVal(std::string var, int val){ if (m_varMap.count(var) > 0){ m_varMap[var] = val; } else { m_varMap.insert(std::pair<string, int>(var, val)); } } int ProgramState::getVal(std::string var){ return m_varMap.at(var); } void ProgramState::toStream(std::string var, std::ostream& outf){ map<std::string, int>::iterator it = m_varMap.find(var); outf << it->first << " : " << it->second << std::endl; } void ProgramState::toStreamAll(std::ostream &outf){ map<std::string, int>::iterator it; for (it = m_varMap.begin(); it != m_varMap.end(); it++){ outf << it->first << " : " << it->second << std::endl; } } int ProgramState::getCurrLine(){ return m_line; } void ProgramState::goNextLine(){ m_line = m_nextLine; } void ProgramState::updateNextLine(int val){ m_nextLine = val; } int ProgramState::getReturnLine(){ int temp = m_stack.top(); m_stack.pop(); return temp; } void ProgramState::addReturnLine(int val){ m_stack.push(val); } void ProgramState::endProgram(){ m_over = 1; } bool ProgramState::isOver(){ if (m_over) { return true; } return false; }
1,273
507
/** ** Copyright (C) Manas Kamal Choudhury 2021 ** ** sysmem.cpp -- System Memory Callbacks ** ** /PORJECT - Aurora {Xeneva} ** /AUTHOR - Manas Kamal Choudhury ** **/ #ifdef ARCH_X64 #include <arch\x86_64\mmngr\vmmngr.h> #include <arch\x86_64\thread.h> #include <_null.h> #include <stdio.h> #endif void map_shared_memory (uint16_t dest_id,uint64_t pos, size_t size) { x64_cli (); thread_t* t = thread_iterate_ready_list (dest_id); if (t == NULL) { t = thread_iterate_block_list(dest_id); } uint64_t *current_cr3 = (uint64_t*)get_current_thread()->cr3; uint64_t *cr3 = (uint64_t*)t->cr3; for (int i = 0; i < size/4096; i++) { if (map_page ((uint64_t)pmmngr_alloc(),pos + i * 4096, PAGING_USER)) { cr3[pml4_index(pos + i * 4096)] = current_cr3[pml4_index(pos + i * 4096)]; } } } void unmap_shared_memory (uint16_t dest_id, uint64_t pos, size_t size) { x64_cli (); thread_t* t = thread_iterate_ready_list (dest_id); if (t == NULL) { t = thread_iterate_block_list(dest_id); } uint64_t *cr3 = (uint64_t*)t->cr3; for (int i = 0; i < size/4096; i++) { unmap_page (pos + i * 4096); unmap_page_ex(cr3,pos + i * 4096, false); } } uint64_t sys_get_used_ram () { x64_cli (); return pmmngr_get_used_ram (); } uint64_t sys_get_free_ram () { x64_cli (); return pmmngr_get_free_ram (); }
1,336
676
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2005 INRIA * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr> */ #include "llc-snap-header.h" #include "ns3/assert.h" #include "ns3/log.h" #include <string> namespace ns3 { NS_LOG_COMPONENT_DEFINE ("LlcSnalHeader"); NS_OBJECT_ENSURE_REGISTERED (LlcSnapHeader); LlcSnapHeader::LlcSnapHeader () { NS_LOG_FUNCTION (this); } void LlcSnapHeader::SetType (uint16_t type) { NS_LOG_FUNCTION (this); m_etherType = type; } uint16_t LlcSnapHeader::GetType (void) { NS_LOG_FUNCTION (this); return m_etherType; } uint32_t LlcSnapHeader::GetSerializedSize (void) const { NS_LOG_FUNCTION (this); return LLC_SNAP_HEADER_LENGTH; } TypeId LlcSnapHeader::GetTypeId (void) { static TypeId tid = TypeId ("ns3::LlcSnapHeader") .SetParent<Header> () .AddConstructor<LlcSnapHeader> () ; return tid; } TypeId LlcSnapHeader::GetInstanceTypeId (void) const { return GetTypeId (); } void LlcSnapHeader::Print (std::ostream &os) const { NS_LOG_FUNCTION (this << &os); os << "type 0x"; os.setf (std::ios::hex, std::ios::basefield); os << m_etherType; os.setf (std::ios::dec, std::ios::basefield); } void LlcSnapHeader::Serialize (Buffer::Iterator start) const { NS_LOG_FUNCTION (this << &start); Buffer::Iterator i = start; uint8_t buf[] = { 0xaa, 0xaa, 0x03, 0, 0, 0}; i.Write (buf, 6); i.WriteHtonU16 (m_etherType); } uint32_t LlcSnapHeader::Deserialize (Buffer::Iterator start) { NS_LOG_FUNCTION (this << &start); Buffer::Iterator i = start; i.Next (5+1); m_etherType = i.ReadNtohU16 (); return GetSerializedSize (); } } // namespace ns3
2,335
933
#include <iostream> using namespace std; int myStrLen(const char *str) { int tam; for (tam = 0; str[tam] != '\0'; tam++); return tam; } char* myStrCat(const char *dest, const char *orig) { char *resultado = new char[myStrLen(dest) + myStrLen(orig) + 1]; int i = 0; for (int j = 0; dest[j] != '\0'; j++, i++) { resultado[i] = dest[j]; } for (int j = 0; orig[j] != '\0'; j++, i++) { resultado[i] = orig[j]; } resultado[i] = '\0'; return resultado; } int main() { const char *str1 = "abra"; const char *str2 = "cadabra"; char *str3 = myStrCat(str1, str2); cout << str1 << endl << str2 << endl << str3 << endl << endl; return 0; }
662
304
#include <boost/test/unit_test.hpp> #include <boost/test/data/test_case.hpp> #include <boost/mpl/list.hpp> #include <binary/converters/little_endian_converter.hpp> namespace mikodev::binary::tests::converters::little_endian_converter_tests { namespace mk = mikodev::binary; namespace mkc = mikodev::binary::converters; using __test_types = boost::mpl::list<int8_t, int32_t, uint16_t, uint64_t>; BOOST_AUTO_TEST_CASE_TEMPLATE(little_endian_converter__length, T, __test_types) { auto converter = mkc::little_endian_converter<T>(); BOOST_REQUIRE_EQUAL(sizeof(T), converter.length()); } template <typename TArgs> void __test_encode_decode(TArgs source) { byte_t buffer[16] = { static_cast<byte_t>(0) }; auto converter = mkc::little_endian_converter<TArgs>(); auto allocator = mk::allocator(buffer, sizeof(buffer)); converter.encode(allocator, source); BOOST_REQUIRE_EQUAL(sizeof(TArgs), allocator.length()); auto span = allocator.as_span(); auto result = converter.decode(span); BOOST_REQUIRE_EQUAL(source, result); BOOST_REQUIRE_EQUAL(sizeof(TArgs), span.length()); } auto __int64_data = std::vector<int64_t>{ -65536, 0x11223344AABBCCDD }; BOOST_DATA_TEST_CASE(little_endian_converter__encode_decode__int64, __int64_data) { __test_encode_decode<int64_t>(sample); } }
1,424
540
#include <KrisLibrary/Logger.h> #include "Line3D.h" #include "Segment3D.h" #include "clip.h" #include "misc.h" #include "errors.h" #include <iostream> using namespace Math3D; using namespace std; bool Line3D::Read(File& f) { if(!source.Read(f)) return false; if(!direction.Read(f)) return false; return true; } bool Line3D::Write(File& f) const { if(!source.Write(f)) return false; if(!direction.Write(f)) return false; return true; } void Line3D::setPoints(const Point3D& a, const Point3D& b) { source = a; direction.sub(b,a); } void Line3D::setSegment(const Segment3D& s) { source = s.a; direction.sub(s.b,s.a); } void Line3D::setTransformed(const Line3D& l, const Matrix4& xform) { xform.mulPoint(l.source,source); xform.mulVector(l.direction,direction); } void Line3D::eval(Real t, Point3D& out) const { out = source; out.madd(direction,t); } Real Line3D::closestPointParameter(const Point3D& in) const { Real denom = dot(direction,direction); if(denom == Zero) return Zero; return dot(in-source,direction)/denom; } Real Line3D::closestPoint(const Point3D& in, Point3D& out) const { Real t=closestPointParameter(in); eval(t,out); return t; } Real Line3D::closestPoint(const Point3D& in, Point3D& out, Real tmin, Real tmax) const { Real denom = dot(direction,direction); Real numer = dot(in-source,direction); //t = numer/denom with denom >= 0 Real t; if(numer<=tmin*denom) t=tmin; else if(numer>=tmax*denom) t=tmax; else t = numer/denom; eval(t,out); return t; } Real Line3D::distance(const Point3D& pt) const { Point3D closest; closestPoint(pt,closest); return (pt-closest).norm(); } //a generalized line test for rays a + t*as, b + u*bs bool Line3D::intersects(const Line3D& l, Real* t, Real* u, Real epsilon) const { //take the vector normal to both lines, project their offsets onto the lines //if they are coplanar, do some more checking Vector3 n = cross(direction,l.direction); Vector3 local = l.source - source; if(n.isZero()) //a,b parallel { //project l onto this line (in local coords) Real projDist = dot(local,direction)/dot(direction,direction); if (DistanceLEQ(local,projDist*direction,epsilon)) { if(t) *t=projDist; if(u) *u=0; return true; } return false; } if(Abs(dot(n, local))<=epsilon) { //get the coordinates of "shift" on the plane //an orthogonal basis is B={a.slope, n*a.slope} //get bslope' and boffset' in B coordinates //bslope' = B = (b1,b2) = (dot(bslope,aslope)/dot(aslope,aslope), dot(bslope,na)/dot(na,na)) //boffset' = A = (a1,a2) = (dot(bofs,aslope)/dot(aslope,aslope), dot(bofs,na)/dot(na,na)) //get an equation R = A + Bt //get the t value of the intersection point with the x axis (x,0), 0 = a2 + b2*t, t = -a2/b2 = dot(bofs,na)/dot(bslope,na) Vector3 na = cross(n,direction); Real myt = -dot(local,na)/dot(l.direction,na); if(t) { *t = myt; } if(u) { Real al2=Inv(dot(direction,direction)); Real a1,b1; a1 = dot(local,direction)*al2; b1 = dot(l.direction,direction)*al2; *u = a1 + b1*myt; } return true; } return false; } void Line3D::closestPoint(const Line3D& l, Real& t, Real& u) const { //take the vector normal to both lines, project their offsets onto the lines //if they are coplanar, do some more checking Vector3 n = cross(direction,l.direction); Vector3 local = l.source - source; if(n.isZero()) { //a,b parallel //project l onto this line (in local coords) t = dot(local,direction)/dot(direction,direction); u = 0; return; } //get the coordinates of "shift" on the plane //an orthogonal basis is B={a.slope, n*a.slope} //get bslope' and boffset' in B coordinates //bslope' = B = (b1,b2) = (dot(bslope,aslope)/dot(aslope,aslope), dot(bslope,na)/dot(na,na)) //boffset' = A = (a1,a2) = (dot(bofs,aslope)/dot(aslope,aslope), dot(bofs,na)/dot(na,na)) //get an equation R = A + Bt //get the t value of the intersection point with the x axis (x,0), 0 = a2 + b2*t, t = -a2/b2 = dot(bofs,na)/dot(bslope,na) //THIS IS MESSED UP /* Vector3 na = cross(n,direction); t = -dot(local,na)/dot(l.direction,na); Real al2=Inv(dot(direction,direction)); Real a1,b1; a1 = dot(local,direction)*al2; b1 = dot(l.direction,direction)*al2; u = a1 + b1*t; */ Matrix2 AtA,AtAinv; AtA(0,0) = dot(direction,direction); AtA(1,0) = -dot(l.direction,direction); AtA(0,1) = -dot(l.direction,direction); AtA(1,1) = dot(l.direction,l.direction); bool res=AtA.getInverse(AtAinv); if(!res) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, Line3D closest points matrix inverse failed\n"); t=u=0; return; } Vector2 tu = AtAinv*Vector2(dot(direction,local),-dot(l.direction,local)); t = tu.x; u = tu.y; } void Line3D::getAABB(AABB3D& bb,Real tmin,Real tmax) const { Point3D a,b; eval(tmin,a); eval(tmax,b); bb.setPoint(a); bb.expand(b); } bool Line3D::lineIntersects(const AABB3D& bb) const { Real u1=-Inf,u2=Inf; return intersects(bb,u1,u2); } bool Line3D::rayIntersects(const AABB3D& bb) const { Real u1=0,u2=Inf; return intersects(bb,u1,u2); } bool Line3D::intersects(const AABB3D& bb, Real& u1, Real& u2) const { return ClipLine(source, direction, bb, u1,u2); } Real Line3D::distance(const AABB3D& bb) const { Real tclosest; Vector3 bbclosest; return distance(bb,tclosest,bbclosest); } Real Line3D::distance(const AABB3D& bb, Real& tclosest, Vector3& bbclosest) const { Real tmin=-Inf,tmax=Inf; if(intersects(bb,tmin,tmax)) { tclosest = tmin; eval(tmin,bbclosest); return 0; } //recompute matrices to get distances between axis-aligned segments to this Matrix2 AtA,Ax,Ay,Az; AtA(0,0) = dot(direction,direction); AtA(0,1) = AtA(1,0) = -direction.x; AtA(1,1) = 1; bool res=AtA.getInverse(Ax); if(!res) Ax.setZero(); AtA(0,1) = AtA(1,0) = -direction.y; res=AtA.getInverse(Ay); if(!res) Ay.setZero(); AtA(0,1) = AtA(1,0) = -direction.z; res=AtA.getInverse(Az); if(!res) Az.setZero(); Vector3 bmin = bb.bmin - source, bmax = bb.bmax - source; //for an x-aligned segment, (t,u)^T = Ax*(direction^T x,-bmin.x)^T gives the //parameter on this segment t and the x value of the point bmin.x+u Real dxmin=direction.x*bmin.x,dxmax=direction.x*bmax.x; Real dymin=direction.y*bmin.y,dymax=direction.y*bmax.y; Real dzmin=direction.z*bmin.z,dzmax=direction.z*bmax.z; Real dps [8] = {dzmin+dymin+dxmin, dzmin+dymin+dxmax, dzmin+dymax+dxmin, dzmin+dymax+dxmax, dzmax+dymin+dxmin, dzmax+dymin+dxmax, dzmax+dymax+dxmin, dzmax+dymax+dxmax}; Real bxt = -Ax(0,1)*bmin.x; Real bxu = -Ax(1,1)*bmin.x; Real byt = -Ay(0,1)*bmin.y; Real byu = -Ay(1,1)*bmin.y; Real bzt = -Az(0,1)*bmin.z; Real bzu = -Az(1,1)*bmin.z; Real tx[4] ={ Ax(0,0)*dps[0]+bxt, Ax(0,0)*dps[2]+bxt, Ax(0,0)*dps[4]+bxt, Ax(0,0)*dps[6]+bxt}; Real ux[4] ={ Ax(1,0)*dps[0]+bxu, Ax(1,0)*dps[2]+bxu, Ax(1,0)*dps[4]+bxu, Ax(1,0)*dps[6]+bxu}; Real ty[4] ={ Ay(0,0)*dps[0]+byt, Ay(0,0)*dps[1]+byt, Ay(0,0)*dps[4]+byt, Ay(0,0)*dps[5]+byt}; Real uy[4] ={ Ay(1,0)*dps[0]+byu, Ay(1,0)*dps[1]+byu, Ay(1,0)*dps[4]+byu, Ay(1,0)*dps[5]+byu}; Real tz[4] ={ Az(0,0)*dps[0]+bzt, Az(0,0)*dps[1]+bzt, Az(0,0)*dps[2]+bzt, Az(0,0)*dps[3]+bzt}; Real uz[4] ={ Az(1,0)*dps[0]+bzu, Az(1,0)*dps[1]+bzu, Az(1,0)*dps[2]+bzu, Az(1,0)*dps[3]+bzu}; bool testcorners [8] = {0,0,0,0,0,0,0,0}; Vector3 bbtemp,ltemp; Real dmin = Inf; //check the x's for(int i=0;i<4;i++) { if(ux[i] < 0) testcorners[i] = true; else if(ux[i] > (bmax.x-bmin.x)) testcorners[i+1] = true; else { Vector3 diff = (-tx[i])*direction; diff.x += ux[i] + bmin.x; diff.y += (i&1? bmax.y : bmin.y); diff.z += (i&2? bmax.z : bmin.z); Real d2 = diff.normSquared(); if(d2 < dmin) { tclosest = tx[i]; eval(tclosest,ltemp); dmin = bb.distanceSquared(ltemp,bbclosest); } } } //check the y's for(int i=0;i<4;i++) { if(uy[i] < 0) testcorners[i] = true; else if(uy[i] > (bmax.y-bmin.y)) testcorners[i+2] = true; else { Vector3 diff = (-ty[i])*direction; diff.y += uy[i] + bmin.y; diff.x += (i&1? bmax.x : bmin.x); diff.z += (i&2? bmax.z : bmin.z); Real d2 = diff.normSquared(); if(d2 < dmin) { tclosest = ty[i]; eval(tclosest,ltemp); dmin = bb.distanceSquared(ltemp,bbclosest); } } } //check the z's for(int i=0;i<4;i++) { if(uz[i] < 0) testcorners[i] = true; else if(uz[i] > (bmax.z-bmin.z)) testcorners[i+4] = true; else { Vector3 diff = (-tz[i])*direction; diff.z += uz[i] + bmin.z; diff.x += (i&1 ? bmax.x : bmin.x); diff.y += (i&2 ? bmax.y : bmin.y); Real d2 = diff.normSquared(); if(d2 < dmin) { tclosest = tz[i]; eval(tclosest,ltemp); dmin = bb.distanceSquared(ltemp,bbclosest); } } } //check the corners for(int i=0;i<8;i++) { if(testcorners[i]) { Vector3 pt; pt.x = (i & 1 ? bb.bmax.x : bb.bmin.x); pt.y = (i & 2 ? bb.bmax.y : bb.bmin.y); pt.z = (i & 4 ? bb.bmax.z : bb.bmin.z); Real ttemp = closestPoint(pt,ltemp); Real d2 = pt.distanceSquared(ltemp); if(d2 < dmin) { dmin = d2; tclosest = ttemp; bbclosest = pt; } } } return Sqrt(dmin); } namespace Math3D { ostream& operator << (ostream& out,const Line3D& line) { out<<line.source<<" "<<line.direction; return out; } istream& operator >> (istream& in,Line3D& line) { in>>line.source>>line.direction; return in; } }
9,613
4,512
#ifndef INCLUDED_STDDEFX #include "stddefx.h" #define INCLUDED_STDDEFX #endif #ifndef INCLUDED_CALC_MEMORYEXCHANGEITEMSTRING #include "calc_MemoryExchangeItemString.h" #define INCLUDED_CALC_MEMORYEXCHANGEITEMSTRING #endif // External headers. #ifndef INCLUDED_CSTRING #include <cstring> #define INCLUDED_CSTRING #endif // Project headers. // Module headers. /*! \file This file contains the implementation of the MemoryExchangeItemString class. */ namespace calc { // Code that is private to this module. namespace detail { } // namespace detail //------------------------------------------------------------------------------ // DEFINITION OF STATIC MEMORYEXCHANGEITEMSTRING MEMBERS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF MEMORYEXCHANGEITEMSTRING MEMBERS //------------------------------------------------------------------------------ MemoryExchangeItemString::MemoryExchangeItemString() { } MemoryExchangeItemString::MemoryExchangeItemString( std::string const& name, size_t memoryId, std::string const& value): MemoryExchangeItem(name,memoryId), d_value(value) { } MemoryExchangeItemString::~MemoryExchangeItemString() { } void* MemoryExchangeItemString::rawValue() const { return (void *)d_value.c_str(); } //! copy c_str() representation of value into dest. void MemoryExchangeItemString::beMemCpySrc(void *dest) const { const char *src = d_value.c_str(); std::strcpy((char *)dest, src); } //------------------------------------------------------------------------------ // DEFINITION OF FREE OPERATORS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF FREE FUNCTIONS //------------------------------------------------------------------------------ } // namespace calc
1,996
560
#include <iostream> #include <vector> #include <cmath> #include <opencv2/opencv.hpp> #include <opencv2/viz.hpp> #include <opencv2/viz/widgets.hpp> #include "RadarControl.h" #include <thread> #include <future> #include <unistd.h> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/containers/vector.hpp> #include <boost/interprocess/allocators/allocator.hpp> #include <boost/interprocess/sync/named_mutex.hpp> typedef boost::interprocess::allocator<cv::Vec3f, boost::interprocess::managed_shared_memory::segment_manager> ShmemAllocator; typedef boost::interprocess::vector<cv::Vec3f, ShmemAllocator> radar_shared; //X scale, lidar height, x, y, z offsets std::vector<float> paramsL = { 1.037013, -124.968, -95.25, -22.352, -57.658 }; std::vector<float> paramsR = { 1.037013, -124.968, 96.52, -21.828, -58.42 }; std::mutex mutex; std::queue<std::vector<cv::Vec3f> > radarBufferQueueL; std::vector<cv::Vec3f> radarBufferL; std::queue<std::vector<cv::Vec3f> > firstObjectQueueL; std::vector<cv::Vec3f> firstObjectBufferL; std::queue<std::vector<cv::Vec3f> > secondObjectQueueL; std::vector<cv::Vec3f> secondObjectBufferL; std::queue<std::vector<cv::Vec3f> > radarBufferQueueR; std::vector<cv::Vec3f> radarBufferR; std::queue<std::vector<cv::Vec3f> > firstObjectQueueR; std::vector<cv::Vec3f> firstObjectBufferR; std::queue<std::vector<cv::Vec3f> > secondObjectQueueR; std::vector<cv::Vec3f> secondObjectBufferR; bool newData = false; void exposeRadarBuffer(std::vector<cv::Vec3f>& radarBuffer, std::vector<cv::Vec3f>& firstObjectBuffer, std::vector<cv::Vec3f>& secondObjectBuffer, std::queue<std::vector<cv::Vec3f> > radarBufferQueue, std::queue<std::vector<cv::Vec3f> > firstObjectQueue, std::queue<std::vector<cv::Vec3f> > secondObjectQueue) { while (true) { if (mutex.try_lock()) { radarBuffer.clear(); firstObjectBuffer.clear(); secondObjectBuffer.clear(); if (!radarBufferQueue.empty()) { radarBuffer = std::move(radarBufferQueue.front()); radarBufferQueue.pop(); newData = true; if (!firstObjectQueue.empty()) { firstObjectBuffer = std::move(firstObjectQueue.front()); firstObjectQueue.pop(); } if (!secondObjectQueue.empty()) { secondObjectBuffer = std::move(secondObjectQueue.front()); secondObjectQueue.pop(); } } mutex.unlock(); break; } } } std::deque<radar::RadarPacket> prevL; std::deque<radar::RadarPacket> prevR; void generateRadarQueue(radar::RadarServer* radar, std::deque<radar::RadarPacket> prev, std::queue<std::vector<cv::Vec3f> > radarBufferQueue, std::queue<std::vector<cv::Vec3f> > firstObjectQueue, std::queue<std::vector<cv::Vec3f> > secondObjectQueue) { int cycles = 0; while (!radar->isEmpty()) { radar::RadarPacket data; *radar >> data; std::vector<cv::Vec3f> temp; if (cycles < 10) { radarBufferQueue.push( data.generatePointVec(data.getBoundaryIndex())); prev.push_back(data); } else { firstObjectQueue.push(data.generateBoundaryFromKernel(prev, 0.02)); secondObjectQueue.push(data.generateAllPointVec()); radarBufferQueue.push(data.findBoundary(prev, 20.)); prev.push_back(data); prev.pop_front(); } cycles++; } } void timedFunction(std::function<void(void)> func, unsigned int interval) { std::thread([func, interval]() { while (true) { auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval); func(); std::this_thread::sleep_until(x); } }).detach(); } boost::interprocess::named_mutex mem_mutex{ boost::interprocess::open_or_create, "radar_mutex" }; int main(int argc, char* argv[]) { struct shm_remove { shm_remove() { boost::interprocess::shared_memory_object::remove("radar_vector"); } ~shm_remove(){ boost::interprocess::shared_memory_object::remove("radar_vector"); } } remover; boost::interprocess::managed_shared_memory segmentL(boost::interprocess::create_only, "radar_vector", 1048576); boost::interprocess::managed_shared_memory segmentR(boost::interprocess::create_only, "radar_vector", 1048576); const ShmemAllocator alloc_instL (segmentL.get_segment_manager()); const ShmemAllocator alloc_instR (segmentR.get_segment_manager()); boost::interprocess::named_mutex::remove("radar_mutex"); radar_shared *sharedL = segmentL.construct<radar_shared>("radar_sharedL")(alloc_instL); radar_shared *sharedR = segmentR.construct<radar_shared>("radar_sharedR")(alloc_instR); sharedL->push_back(cv::Vec3f(std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN())); sharedR->push_back(cv::Vec3f(std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::quiet_NaN())); mem_mutex.lock(); std::system("rm -rf /tmp/radarPacketL"); std::string portL = "/tmp/radarPacketL"; radar::RadarServer radarServerL(portL, paramsL); std::system("rm -rf /tmp/radarPacketR"); std::string portR = "/tmp/radarPacketR"; radar::RadarServer radarServerR(portR, paramsR); std::vector<cv::Vec3f> localRadarBufferL, firstObjectL, secondObjectL; std::vector<cv::Vec3f> localRadarBufferR, firstObjectR, secondObjectR; bool firstRun = true; while (true) { if (firstRun && !radarServerL.isRun() && !radarServerR.isRun()) { generateRadarQueue(&radarServerL, prevL, radarBufferQueueL, firstObjectQueueL, secondObjectQueueL); generateRadarQueue(&radarServerR, prevR, radarBufferQueueR, firstObjectQueueR, secondObjectQueueR); firstObjectL = firstObjectQueueL.front(); sharedL->assign(firstObjectL.begin(), firstObjectL.end()); firstObjectR = firstObjectQueueR.front(); sharedR->assign(firstObjectR.begin(), firstObjectR.end()); timedFunction(std::bind(exposeRadarBuffer, radarBufferL, firstObjectL, secondObjectL, radarBufferQueueL, firstObjectQueueL, secondObjectQueueL), 250); timedFunction(std::bind(exposeRadarBuffer, radarBufferR, firstObjectR, secondObjectR, radarBufferQueueR, firstObjectQueueR, secondObjectQueueR), 250); firstRun = false; mem_mutex.unlock(); continue; } while (true && !firstRun) { if (mutex.try_lock()) { if (localRadarBufferL.size() != radarBufferL.size()) { localRadarBufferL = radarBufferL; } if (localRadarBufferR.size() != radarBufferR.size()) { localRadarBufferR = radarBufferR; } if (secondObjectL.size() != secondObjectBufferL.size() && secondObjectBufferL.size()) { secondObjectL = secondObjectBufferL; } if (secondObjectR.size() != secondObjectBufferR.size() && secondObjectBufferR.size()) { secondObjectR = secondObjectBufferR; } if (firstObjectL != firstObjectBufferR && firstObjectBufferR.size()) { firstObjectL = firstObjectBufferR; mem_mutex.lock(); segmentL.destroy<radar_shared>("radar_sharedL"); radar_shared *sharedL = segmentL.construct<radar_shared>("radar_sharedL")(alloc_instL); sharedR->assign(firstObjectL.begin(), firstObjectL.end()); std::cout << sharedL[0][0] << std::endl; } if (firstObjectR != firstObjectBufferR && firstObjectBufferR.size()) { firstObjectR = firstObjectBufferR; segmentR.destroy<radar_shared>("radar_sharedR"); radar_shared *sharedR = segmentR.construct<radar_shared>("radar_sharedR")(alloc_instR); sharedR->assign(firstObjectR.begin(), firstObjectR.end()); std::cout << sharedR[0][0] << std::endl; mem_mutex.unlock(); } mutex.unlock(); } } usleep(10000); } return 0; }
8,556
2,735
/* * * Second Algorithm to test image * against known dataset * */ #include "alg_two.hpp" Algorithm_Two::Algorithm_Two(vector<Mat> users, vector<int> labels) { model = createFisherFaceRecognizer(); model->train(users, labels); } int Algorithm_Two::compare(Mat face) { int predictedLabel = -1; double confidence = 0.0; model->predict(face, predictedLabel, confidence); // string result_message = format("Predicted class = %d | confidence = %f", predictedLabel, confidence); // cout << result_message << endl; if (confidence < ACCEPTANCE_THRESHOLD) { // cout << "accepted" << endl; return predictedLabel; } else { return -1; } }
731
234
#include "osrm/match_parameters.hpp" #include "osrm/nearest_parameters.hpp" #include "osrm/route_parameters.hpp" #include "osrm/table_parameters.hpp" #include "osrm/trip_parameters.hpp" #include "osrm/coordinate.hpp" #include "osrm/engine_config.hpp" #include "osrm/json_container.hpp" #include "osrm/osrm.hpp" #include "osrm/status.hpp" #include <exception> #include <iostream> #include <string> #include <utility> #include <chrono> #include <cstdlib> /* Usage: ./get_routes [map.osrm] [block_data] [block_count] */ typedef struct{ double id; /* GEOID for block */ double latitude; double longitude; double pop; }block_data; /* All-purpose function to write data to file */ static void overwrite_data_to_file(void *data, const char *fileName, size_t numBytes){ FILE *f=fopen(fileName,"w"); fwrite(data,1,numBytes,f); fclose(f); } /* All-purpose function to read data from file */ static void *get_file_data(const char *fileName){ FILE *f = fopen(fileName,"r"); size_t fsize; fseek(f,0L,SEEK_END); fsize = ftell(f); fseek(f,0L,SEEK_SET); void *data = malloc(fsize); fread(data,1,fsize,f); fclose(f); return data; } int main(int argc, const char *argv[]) { if (argc < 4) { std::cerr << "Usage: " << argv[0] << " [map.osrm] [block_data] [block_count]\n"; return EXIT_FAILURE; } /* Read in the block data */ block_data *stateData = (block_data*)get_file_data(argv[2]); int pcount = atoi(argv[3]); /* Initialize output holder */ double *output = (double *)calloc(pcount*pcount,sizeof(double)); /* Adapted from OSRM sample code */ using namespace osrm; EngineConfig config; config.storage_config = {argv[1]}; config.use_shared_memory = false; /* From OSRM sample code: // We support two routing speed up techniques: // - Contraction Hierarchies (CH): requires extract+contract pre-processing // - Multi-Level Dijkstra (MLD): requires extract+partition+customize pre-processing */ // config.algorithm = EngineConfig::Algorithm::CH; // config.algorithm = EngineConfig::Algorithm::MLD; const OSRM osrm{config}; TableParameters tableParameters; for(int i = 0; i < pcount; i++){ tableParameters.coordinates.push_back({util::FloatLongitude{stateData[i].longitude}, util::FloatLatitude{stateData[i].latitude}}); } for(int source = 0; source < pcount; source++){ std::cout << (double)source/(double)pcount << " % complete" << std::endl; tableParameters.sources.clear(); tableParameters.sources.push_back(source); // Single source //tableParameters.destinations.push_back(dest); // Leaving blank does 1 -> All json::Object tableResult; const auto rc = osrm.Table(tableParameters, tableResult); const auto code = tableResult.values.at("code").get<json::String>().value; const auto &durations_array = tableResult.values.at("durations").get<json::Array>().values; const auto durations_matrix = durations_array[0].get<json::Array>().values; for(int j = 0; j < durations_matrix.size(); j++){ output[source*pcount + j] = durations_matrix.at(j).get<json::Number>().value; } } /* Save output to file */ overwrite_data_to_file(output, "route_dist", pcount*pcount*sizeof(double)); free(output); return 0; }
3,528
1,181
#if COMPILATION_INSTRUCTIONS mpicxx -O3 -std=c++14 -Wall -Wfatal-errors $0 -o $0x.x && time mpirun -np 4s $0x.x $@ && rm -f $0x.x; exit #endif #define BOOST_MPI3_DISALLOW_AUTOMATIC_POD_COMMUNICATION #include "alf/boost/mpi3/main.hpp" #include "alf/boost/mpi3/communicator.hpp" namespace mpi3 = boost::mpi3; using std::cout; int mpi3::main(int argc, char* argv[], mpi3::communicator& world){ mpi3::type t = mpi3::type::int_[100]; // mpi3::type::int_.contiguous(100); t.commit_as<std::array<int, 100>>(); t.commit_as<int[100]>(); // std::array<int, 100> buffer; int buffer[100]; if(world.rank() == 0) world.send_n(&buffer, 1, 1, 123); else if(world.rank() == 1) world.receive_n(&buffer, 1, 0, 123); return 0; }
723
359
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp //! \author Eli Moll //! \brief Decoupled photon production reaction factory class declaration //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_DECOUPLED_PHOTON_PRODUCTION_REACTION_ACE_FACTORY_HPP #define MONTE_CARLO_DECOUPLED_PHOTON_PRODUCTION_REACTION_ACE_FACTORY_HPP // Standard Includes #include <memory> #include <unordered_map> #include <unordered_set> // FRENSIE Includes #include "MonteCarlo_DecoupledPhotonProductionReaction.hpp" #include "MonteCarlo_PhotonProductionNuclearScatteringDistributionACEFactory.hpp" #include "MonteCarlo_NeutronNuclearReactionACEFactory.hpp" #include "MonteCarlo_NuclearReactionType.hpp" #include "Utility_UnivariateDistribution.hpp" #include "Utility_HashBasedGridSearcher.hpp" #include "Utility_ArrayView.hpp" #include "Utility_Vector.hpp" namespace MonteCarlo{ /*! The decoupled photon production reaction factory class * \details This factory class stores all of the data blocks found in the * ACE tables that describe specific reactions (except for fission reactions). * The array parameters used in the class constructor have the same name as * the corresponding ACE data block. */ class DecoupledPhotonProductionReactionACEFactory : public NeutronNuclearReactionACEFactory { public: //! Constructor DecoupledPhotonProductionReactionACEFactory( const std::string& table_name, const double atomic_weight_ratio, const double temperature, const std::shared_ptr<const std::vector<double> >& energy_grid, const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >& grid_searcher, const SimulationProperties& properties, const Data::XSSNeutronDataExtractor& raw_nuclide_data ); //! Destructor ~DecoupledPhotonProductionReactionACEFactory() { /* ... */ } //! Create the yield based photon production reactions void createPhotonProductionReactions( std::unordered_map<unsigned,std::shared_ptr<const DecoupledPhotonProductionReaction> >& yield_based_photon_production_reactions ) const; protected: //! Create the reaction type ordering map static void createReactionOrderingMap( const Utility::ArrayView<const double>& mtrp_block, std::unordered_map<unsigned,unsigned>& reaction_ordering ); //! Create the total reaction void createTotalReaction( const Utility::ArrayView<const double>& total_xs_block, const std::shared_ptr<const std::vector<double> >& energy_grid, const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >& grid_searcher, const double temperature ); //! Parse the SIGP Block static void parseSIGP( const std::string& table_name, const size_t energy_grid_size, const Utility::ArrayView<const double>& lsigp_block, const Utility::ArrayView<const double>& sigp_block, const std::unordered_map<unsigned,unsigned>& reaction_ordering, std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map, std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_values_map, std::unordered_map<unsigned,std::shared_ptr<std::vector<double> > >& xs_based_map, std::unordered_map<unsigned,unsigned>& threshold_energy_map, std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map ); //! Construct the base reaction map void constructBaseReactionMap( std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map, std::unordered_map<NuclearReactionType,std::shared_ptr<const NeutronNuclearReaction> >& base_reaction_map, std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map ); // Construct a map of photon MT numbers to yield distributions void constructMTPYieldDistributions( const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map, const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_values_map ); // Construct a map of base reaction types to yield distribution arrays void constructMTYieldArrays( const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map, const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map ); private: // Initialize the yield based photon production reactions void initializeYieldBasedPhotonProductionReactions( const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map, const double temperature, const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map, const std::unordered_map<NuclearReactionType,std::shared_ptr<const NeutronNuclearReaction> >& base_reaction_map, const SimulationProperties& properties, PhotonProductionNuclearScatteringDistributionACEFactory& photon_production_dist_factory ); // Initialize the yield based photon production reactions void initializeCrossSectionBasedPhotonProductionReactions( const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map, const double temperature, const std::unordered_map<unsigned,unsigned>& threshold_energy_map, const std::unordered_map<unsigned,std::shared_ptr<std::vector<double> > >& xs_based_map, const std::shared_ptr<const std::vector<double> >& energy_grid, const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >& grid_searcher, const SimulationProperties& properties, PhotonProductionNuclearScatteringDistributionACEFactory& photon_production_dist_factory ); // A map of the photon production reactions std::unordered_map<unsigned,std::shared_ptr<const DecoupledPhotonProductionReaction> > d_photon_production_reactions; // A map of the nuclear reaction type to associated array of TabularDistributions std::unordered_map<NuclearReactionType,std::vector<std::shared_ptr<const Utility::UnivariateDistribution> > > d_mt_yield_distributions; // A map of photon production reaction MT numbers to shared pointers of // Tabular distributions std::unordered_map<unsigned,std::shared_ptr<const Utility::UnivariateDistribution> > d_mtp_yield_distributions_map; // Total reaction std::shared_ptr<const NeutronNuclearReaction> d_total_reaction; }; } // end MonteCarlo namespace #endif // end MONTE_CARLONUCLEAR_REACTION_ACE_FACTORY_HPP //---------------------------------------------------------------------------// // end MonteCarlo_NeutronNuclearReactionACEFactory.hpp //---------------------------------------------------------------------------//
6,801
2,045
#include <GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.hpp> namespace cg { TextureSamplerDescriptor::TextureSamplerDescriptor() noexcept { filter = TextureFilter::point; addressU = TextureAddressMode::clamp; addressV = TextureAddressMode::clamp; addressW = TextureAddressMode::clamp; maxAnisotropy = 0; borderColor = cpp::Vector4D<float>(0.0f, 0.0f, 0.0f, 0.0f); } }
440
166
/* * Copyright (c) 2019, Intel Corporation * 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. */ //! //! \file: RegionData.cpp //! \brief: the class for Region Info //! \detail: it's class to describe region info //! //! Created on May 21, 2020, 1:18 PM //! #include "RegionData.h" #include <string.h> #include "Common.h" VCD_NS_BEGIN RegionData::RegionData(RegionWisePacking* rwpk, uint32_t sourceNumber, SourceResolution* qtyRes) { m_sourceInRegion = sourceNumber; m_regionWisePacking = new RegionWisePacking; *m_regionWisePacking = *rwpk; m_regionWisePacking->rectRegionPacking = new RectangularRegionWisePacking[rwpk->numRegions]; memcpy_s(m_regionWisePacking->rectRegionPacking, rwpk->numRegions * sizeof(RectangularRegionWisePacking), rwpk->rectRegionPacking, rwpk->numRegions * sizeof(RectangularRegionWisePacking)); m_sourceInfo = new SourceResolution[sourceNumber]; for (uint32_t i = 0; i < sourceNumber; i++) { m_sourceInfo[i].qualityRanking = qtyRes[i].qualityRanking; m_sourceInfo[i].left = qtyRes[i].left; m_sourceInfo[i].top = qtyRes[i].top; m_sourceInfo[i].width = qtyRes[i].width; m_sourceInfo[i].height = qtyRes[i].height; } } RegionData::~RegionData() { m_sourceInRegion = 0; if (m_regionWisePacking != NULL) { if (m_regionWisePacking->rectRegionPacking != NULL) { delete[] m_regionWisePacking->rectRegionPacking; m_regionWisePacking->rectRegionPacking = NULL; } delete m_regionWisePacking; m_regionWisePacking = NULL; } if (m_sourceInfo != NULL) { delete[] m_sourceInfo; m_sourceInfo = NULL; } } VCD_NS_END
2,907
1,078
/* * Copyright (C) 2020 Southern Storm Software, Pty Ltd. * * 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 "gen.h" #include <cstring> // Size of the WAGE state in bytes. #define WAGE_STATE_SIZE 37 // Number of rounds for the WAGE permutation. #define WAGE_NUM_ROUNDS 111 // Table numbers. #define WAGE_TABLE_WGP_SBOX 0 #define WAGE_TABLE_RC 1 // RC0 and RC1 round constants for WAGE, interleaved with each other. static unsigned char const wage_rc[WAGE_NUM_ROUNDS * 2] = { 0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x41, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x43, 0x21, 0x50, 0x28, 0x14, 0x0a, 0x45, 0x62, 0x71, 0x78, 0x3c, 0x1e, 0x4f, 0x27, 0x13, 0x09, 0x44, 0x22, 0x51, 0x68, 0x34, 0x1a, 0x4d, 0x66, 0x73, 0x39, 0x5c, 0x2e, 0x57, 0x2b, 0x15, 0x4a, 0x65, 0x72, 0x79, 0x7c, 0x3e, 0x5f, 0x2f, 0x17, 0x0b, 0x05, 0x42, 0x61, 0x70, 0x38, 0x1c, 0x0e, 0x47, 0x23, 0x11, 0x48, 0x24, 0x12, 0x49, 0x64, 0x32, 0x59, 0x6c, 0x36, 0x5b, 0x2d, 0x56, 0x6b, 0x35, 0x5a, 0x6d, 0x76, 0x7b, 0x3d, 0x5e, 0x6f, 0x37, 0x1b, 0x0d, 0x46, 0x63, 0x31, 0x58, 0x2c, 0x16, 0x4b, 0x25, 0x52, 0x69, 0x74, 0x3a, 0x5d, 0x6e, 0x77, 0x3b, 0x1d, 0x4e, 0x67, 0x33, 0x19, 0x4c, 0x26, 0x53, 0x29, 0x54, 0x2a, 0x55, 0x6a, 0x75, 0x7a, 0x7d, 0x7e, 0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x41, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x43, 0x21, 0x50, 0x28, 0x14, 0x0a, 0x45, 0x62, 0x71, 0x78, 0x3c, 0x1e, 0x4f, 0x27, 0x13, 0x09, 0x44, 0x22, 0x51, 0x68, 0x34, 0x1a, 0x4d, 0x66, 0x73, 0x39, 0x5c, 0x2e, 0x57, 0x2b, 0x15, 0x4a, 0x65, 0x72, 0x79, 0x7c, 0x3e, 0x5f, 0x2f, 0x17, 0x0b, 0x05, 0x42, 0x61, 0x70, 0x38, 0x1c, 0x0e, 0x47, 0x23, 0x11, 0x48, 0x24, 0x12, 0x49, 0x64, 0x32, 0x59, 0x6c, 0x36, 0x5b, 0x2d, 0x56, 0x6b, 0x35, 0x5a, 0x6d, 0x76, 0x7b, 0x3d, 0x5e, 0x6f, 0x37, 0x1b, 0x0d, 0x46 }; // WGP and S-box combined into a single 256 byte table. static unsigned char const wage_wgp_sbox[256] = { // S-box 0x2e, 0x1c, 0x6d, 0x2b, 0x35, 0x07, 0x7f, 0x3b, 0x28, 0x08, 0x0b, 0x5f, 0x31, 0x11, 0x1b, 0x4d, 0x6e, 0x54, 0x0d, 0x09, 0x1f, 0x45, 0x75, 0x53, 0x6a, 0x5d, 0x61, 0x00, 0x04, 0x78, 0x06, 0x1e, 0x37, 0x6f, 0x2f, 0x49, 0x64, 0x34, 0x7d, 0x19, 0x39, 0x33, 0x43, 0x57, 0x60, 0x62, 0x13, 0x05, 0x77, 0x47, 0x4f, 0x4b, 0x1d, 0x2d, 0x24, 0x48, 0x74, 0x58, 0x25, 0x5e, 0x5a, 0x76, 0x41, 0x42, 0x27, 0x3e, 0x6c, 0x01, 0x2c, 0x3c, 0x4e, 0x1a, 0x21, 0x2a, 0x0a, 0x55, 0x3a, 0x38, 0x18, 0x7e, 0x0c, 0x63, 0x67, 0x56, 0x50, 0x7c, 0x32, 0x7a, 0x68, 0x02, 0x6b, 0x17, 0x7b, 0x59, 0x71, 0x0f, 0x30, 0x10, 0x22, 0x3d, 0x40, 0x69, 0x52, 0x14, 0x36, 0x44, 0x46, 0x03, 0x16, 0x65, 0x66, 0x72, 0x12, 0x0e, 0x29, 0x4a, 0x4c, 0x70, 0x15, 0x26, 0x79, 0x51, 0x23, 0x3f, 0x73, 0x5b, 0x20, 0x5c, // WGP 0x00, 0x12, 0x0a, 0x4b, 0x66, 0x0c, 0x48, 0x73, 0x79, 0x3e, 0x61, 0x51, 0x01, 0x15, 0x17, 0x0e, 0x7e, 0x33, 0x68, 0x36, 0x42, 0x35, 0x37, 0x5e, 0x53, 0x4c, 0x3f, 0x54, 0x58, 0x6e, 0x56, 0x2a, 0x1d, 0x25, 0x6d, 0x65, 0x5b, 0x71, 0x2f, 0x20, 0x06, 0x18, 0x29, 0x3a, 0x0d, 0x7a, 0x6c, 0x1b, 0x19, 0x43, 0x70, 0x41, 0x49, 0x22, 0x77, 0x60, 0x4f, 0x45, 0x55, 0x02, 0x63, 0x47, 0x75, 0x2d, 0x40, 0x46, 0x7d, 0x5c, 0x7c, 0x59, 0x26, 0x0b, 0x09, 0x03, 0x57, 0x5d, 0x27, 0x78, 0x30, 0x2e, 0x44, 0x52, 0x3b, 0x08, 0x67, 0x2c, 0x05, 0x6b, 0x2b, 0x1a, 0x21, 0x38, 0x07, 0x0f, 0x4a, 0x11, 0x50, 0x6a, 0x28, 0x31, 0x10, 0x4d, 0x5f, 0x72, 0x39, 0x16, 0x5a, 0x13, 0x04, 0x3c, 0x34, 0x1f, 0x76, 0x1e, 0x14, 0x23, 0x1c, 0x32, 0x4e, 0x7b, 0x24, 0x74, 0x7f, 0x3d, 0x69, 0x64, 0x62, 0x6f }; Sbox get_wage_round_constants(int num) { if (num == WAGE_TABLE_RC) return Sbox(wage_rc, sizeof(wage_rc)); else return Sbox(wage_wgp_sbox, sizeof(wage_wgp_sbox)); } struct WageState { Code *code; Reg s[WAGE_STATE_SIZE]; Reg fb[3]; Reg temp; unsigned char modified[WAGE_STATE_SIZE]; int last_used[WAGE_STATE_SIZE]; int time; WageState(Code &c) : code(&c), time(1) { memset(modified, 0, sizeof(modified)); memset(last_used, 0, sizeof(last_used)); temp = code->allocateHighReg(1); } // Load a byte from the state into a register if not already in one. // Return the existing register if the value is still in a register. // If we have run out of registers, spill the oldest one. Reg reg(int num); // Mark a byte as having been used to keep the register fresh. // This will avoid a spill on a value we know we'll need again // soon in the upcoming code. void used(int num); // Mark a byte as dirty. Register contents have been modified. void dirty(int num); // Spill a register back to the stack if the value has been modified. // Then release the register back to the allocation pool. void spill(int num); // Spill the oldest unmodified value that is in a high register. void spillHigh(); // Spill the oldest unmodified value that is in any register. void spillAny(); // Determine if a state byte is active in a register or if it is // still on the stack. bool isActive(int num); // Copy a value into the stack and release the original register. void copy(int to, int from); }; Reg WageState::reg(int num) { if (s[num].size() != 0) { last_used[num] = time++; return s[num]; } s[num] = code->allocateOptionalReg(1); if (s[num].size() == 0) { // We have run out of registers so find the oldest value // that is not modified and reuse that register. We should // be able to find something. int age = 0x7FFFFFFF; int oldest = -1; for (int index = 0; index < WAGE_STATE_SIZE; ++index) { if (s[index].size() != 0 && !modified[index]) { if (last_used[index] < age) { age = last_used[index]; oldest = index; } } } if (oldest == -1) { // Try again but this time find the oldest modified register. int age = 0x7FFFFFFF; int oldest = -1; for (int index = 0; index < WAGE_STATE_SIZE; ++index) { if (s[index].size() != 0 && modified[index]) { if (last_used[index] < age) { age = last_used[index]; oldest = index; } } } if (oldest == -1) throw std::invalid_argument("not enough registers for wage"); } spill(oldest); s[num] = code->allocateReg(1); } code->ldlocal(s[num], num); last_used[num] = time++; modified[num] = 0; return s[num]; } void WageState::used(int num) { last_used[num] = time++; } void WageState::dirty(int num) { modified[num] = 1; last_used[num] = time++; } void WageState::spill(int num) { if (s[num].size() == 0) { // Register not currently in use. return; } if (modified[num]) code->stlocal(s[num], num); code->releaseReg(s[num]); s[num] = Reg(); } void WageState::spillHigh() { int age = 0x7FFFFFFF; int oldest = -1; for (int index = 0; index < WAGE_STATE_SIZE; ++index) { if (s[index].size() != 0 && !modified[index]) { if (s[index].reg(0) >= 16 && last_used[index] < age) { age = last_used[index]; oldest = index; } } } if (oldest == -1) throw std::invalid_argument("cannot find a high register to spill"); spill(oldest); } void WageState::spillAny() { int age = 0x7FFFFFFF; int oldest = -1; for (int index = 0; index < WAGE_STATE_SIZE; ++index) { if (s[index].size() != 0 && !modified[index]) { if (last_used[index] < age) { age = last_used[index]; oldest = index; } } } if (oldest == -1) throw std::invalid_argument("cannot find a register to spill"); spill(oldest); } bool WageState::isActive(int num) { return s[num].size() != 0; } void WageState::copy(int to, int from) { if (s[from].size() != 0) { // The source value is already in a register. code->stlocal(s[from], to); code->releaseReg(s[from]); s[from] = Reg(); } else { // The source value is still on the stack, so copy via a temporary. code->ldlocal(temp, from); code->stlocal(temp, to); } } void gen_wage_permutation(Code &code) { int index; // Set up the function prologue with 37 bytes of local variable storage. // Z points to the permutation state on input and output. code.prologue_permutation("wage_permute", 37); // Allocate temporary registers and the state object. WageState s(code); Reg round = code.allocateHighReg(1); Reg fb = code.allocateReg(3); Reg fb0 = Reg(fb, 0, 1); Reg fb1 = Reg(fb, 1, 1); Reg fb2 = Reg(fb, 2, 1); #define S(num) (s.reg((num))) // Copy the input to local variables because we need Z to point // at the S-box, WGP, and RC tables. for (index = 0; index < 36; index += 3) { code.ldz(fb, index); code.stlocal(fb, index); } code.ldz(fb0, 36); code.stlocal(fb0, 36); // Save Z on the stack and set it up to point at the WGP/S-box table. code.push(Reg::z_ptr()); code.sbox_setup (WAGE_TABLE_WGP_SBOX, get_wage_round_constants(WAGE_TABLE_WGP_SBOX)); // Perform all rounds 3 at a time. unsigned char top_label = 0; code.move(round, 0); code.label(top_label); // Calculate the feedback value for the LFSR. // // fb = omega(s[0]) ^ s[6] ^ s[8] ^ s[12] ^ s[13] ^ s[19] ^ // s[24] ^ s[26] ^ s[30] ^ s[31] ^ WGP(s[36]) ^ RC1[round] // // where omega(x) is (x >> 1) if the low bit of x is zero and // (x >> 1) ^ 0x78 if the low bit of x is one. // // fb0 = (s[0] >> 1) ^ (0x78 & -(s[0] & 0x01)); code.ldlocal(fb0, 0); code.tworeg(Insn::MOV, s.temp.reg(0), ZERO_REG); code.lsr(fb0, 1); code.tworeg(Insn::SBC, s.temp.reg(0), ZERO_REG); code.logand(s.temp, 0x78); code.logxor(fb0, s.temp); // fb0 ^= s[6] ^ s[8] ^ s[12] ^ s[13] ^ s[19] ^ // s[24] ^ s[26] ^ s[30] ^ s[31] ^ rc[1]; code.logxor(fb0, S(6)); code.logxor(fb0, S(8)); code.logxor(fb0, S(12)); code.logxor(fb0, S(13)); code.logxor(fb0, S(19)); code.logxor(fb0, S(24)); code.logxor(fb0, S(26)); code.logxor(fb0, S(30)); code.logxor(fb0, S(31)); // fb1 = (s[1] >> 1) ^ (0x78 & -(s[1] & 0x01)); code.ldlocal(fb1, 1); code.tworeg(Insn::MOV, s.temp.reg(0), ZERO_REG); code.lsr(fb1, 1); code.tworeg(Insn::SBC, s.temp.reg(0), ZERO_REG); code.logand(s.temp, 0x78); code.logxor(fb1, s.temp); // fb1 ^= s[7] ^ s[9] ^ s[13] ^ s[14] ^ s[20] ^ // s[25] ^ s[27] ^ s[31] ^ s[32] ^ rc[3]; code.logxor(fb1, S(7)); code.logxor(fb1, S(9)); code.logxor(fb1, S(13)); code.logxor(fb1, S(14)); code.logxor(fb1, S(20)); code.logxor(fb1, S(25)); code.logxor(fb1, S(27)); code.logxor(fb1, S(31)); code.logxor(fb1, S(32)); // fb2 = (s[2] >> 1) ^ (0x78 & -(s[2] & 0x01)); code.ldlocal(fb2, 2); code.tworeg(Insn::MOV, s.temp.reg(0), ZERO_REG); code.lsr(fb2, 1); code.tworeg(Insn::SBC, s.temp.reg(0), ZERO_REG); code.logand(s.temp, 0x78); code.logxor(fb2, s.temp); // fb2 ^= s[8] ^ s[10] ^ s[14] ^ s[15] ^ s[21] ^ // s[26] ^ s[28] ^ s[32] ^ s[33] ^ rc[5]; code.logxor(fb2, S(8)); code.logxor(fb2, S(10)); code.logxor(fb2, S(14)); code.logxor(fb2, S(15)); code.logxor(fb2, S(21)); code.logxor(fb2, S(26)); code.logxor(fb2, S(28)); code.logxor(fb2, S(32)); code.logxor(fb2, S(33)); // Apply the S-box and WGP permutation to certain components. // s[5] ^= wage_sbox[s[8]]; code.sbox_lookup(s.temp, S(8)); code.logxor(S(5), s.temp); s.dirty(5); // s[6] ^= wage_sbox[s[9]]; code.sbox_lookup(s.temp, S(9)); code.logxor(S(6), s.temp); s.dirty(6); // s[7] ^= wage_sbox[s[10]]; code.sbox_lookup(s.temp, S(10)); code.logxor(S(7), s.temp); s.dirty(7); // s[11] ^= wage_sbox[s[15]]; code.sbox_lookup(s.temp, S(15)); code.logxor(S(11), s.temp); s.dirty(11); // s[12] ^= wage_sbox[s[16]]; code.sbox_lookup(s.temp, S(16)); code.logxor(S(12), s.temp); s.dirty(12); // s[13] ^= wage_sbox[s[17]]; code.sbox_lookup(s.temp, S(17)); code.logxor(S(13), s.temp); s.dirty(13); // s[24] ^= wage_sbox[s[27]]; code.sbox_lookup(s.temp, S(27)); code.logxor(S(24), s.temp); s.dirty(24); // s[25] ^= wage_sbox[s[28]]; code.sbox_lookup(s.temp, S(28)); code.logxor(S(25), s.temp); s.dirty(25); // s[26] ^= wage_sbox[s[29]]; code.sbox_lookup(s.temp, S(29)); code.logxor(S(26), s.temp); s.dirty(26); // s[30] ^= wage_sbox[s[34]]; code.sbox_lookup(s.temp, S(34)); code.logxor(S(30), s.temp); s.dirty(30); // s[31] ^= wage_sbox[s[35]]; code.sbox_lookup(s.temp, S(35)); code.logxor(S(31), s.temp); s.dirty(31); // s[32] ^= wage_sbox[s[36]]; code.sbox_lookup(s.temp, S(36)); code.logxor(S(32), s.temp); s.dirty(32); // Prepare to load round constants rc[0], rc[2], rc[4] for later. s.spillHigh(); // Need a spare high register for sbox_switch(). s.spillAny(); // Need some other spare registers for the round constants. s.spillAny(); code.sbox_switch(WAGE_TABLE_RC, get_wage_round_constants(WAGE_TABLE_RC)); Reg rc0 = code.allocateReg(1); Reg rc2 = code.allocateReg(1); Reg rc4 = code.allocateReg(1); // Load rc[0]; code.sbox_lookup(rc0, round); code.inc(round); // fb0 ^= rc[1]; code.sbox_lookup(s.temp, round); code.logxor(fb0, s.temp); code.inc(round); // Load rc[2]; code.sbox_lookup(rc2, round); code.inc(round); // fb1 ^= rc[3]; code.sbox_lookup(s.temp, round); code.logxor(fb1, s.temp); code.inc(round); // Load rc[4]; code.sbox_lookup(rc4, round); code.inc(round); // fb2 ^= rc[5]; code.sbox_lookup(s.temp, round); code.logxor(fb2, s.temp); code.inc(round); // s[19] ^= wage_wgp[s[18]] ^ rc[0]; Reg zlow = Reg(Reg::z_ptr(), 0, 1); s.spillHigh(); // Need a spare high register for sbox_switch(). code.sbox_switch (WAGE_TABLE_WGP_SBOX, get_wage_round_constants(WAGE_TABLE_WGP_SBOX)); code.move(zlow, S(18)); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(S(19), s.temp); code.logxor(S(19), rc0); code.releaseReg(rc0); s.dirty(19); // s[20] ^= wage_wgp[s[19]] ^ rc[2]; code.move(zlow, S(19)); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(S(20), s.temp); code.logxor(S(20), rc2); code.releaseReg(rc2); s.dirty(20); // s[21] ^= wage_wgp[s[20]] ^ rc[4]; code.move(zlow, S(20)); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(S(21), s.temp); code.logxor(S(21), rc4); code.releaseReg(rc4); s.dirty(21); // fb0 ^= wage_wgp[s[36]]; code.move(zlow, S(36)); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(fb0, s.temp); // fb1 ^= wage_wgp[fb0]; code.move(zlow, fb0); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(fb1, s.temp); // fb2 ^= wage_wgp[fb1]; code.move(zlow, fb1); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(fb2, s.temp); // Rotate the components of the state by 3 positions. for (index = 0; index < 34; ++index) s.copy(index, index + 3); code.stlocal(fb0, 34); code.stlocal(fb1, 35); code.stlocal(fb2, 36); // Bottom of the round loop. code.compare_and_loop(round, WAGE_NUM_ROUNDS * 2, top_label); // Restore Z and copy the local variables back to the state. code.sbox_cleanup(); code.pop(Reg::z_ptr()); for (index = 0; index < 36; index += 3) { code.ldlocal(fb, index); code.stz(fb, index); } code.ldlocal(fb0, 36); code.stz(fb0, 36); } // 7-bit components for the rate. static unsigned char wage_rate_bytes[10] = { 8, 9, 15, 16, 18, 27, 28, 34, 35, 36 }; void gen_wage_absorb(Code &code) { // Set up the function prologue with 0 bytes of local variable storage. code.prologue_setup_key("wage_absorb", 0); code.setFlag(Code::NoLocals); // Load the first 32 bits of the block to be absorbed. Reg temp = code.allocateReg(5); code.ldx(Reg(temp, 1, 4).reversed(), POST_INC); code.move(Reg(temp, 0, 1), 0); // Absorb the first 32-bits into the state pointed to by Z, // after breaking it up into 7-bit components. code.lsr(temp, 1); code.ldz_xor_in(Reg(temp, 4, 1), wage_rate_bytes[0]); Reg tnext = Reg(temp, 0, 4); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 3, 1), wage_rate_bytes[1]); tnext = Reg(temp, 0, 3); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 2, 1), wage_rate_bytes[2]); tnext = Reg(temp, 0, 2); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 1, 1), wage_rate_bytes[3]); tnext = Reg(temp, 0, 1); code.lsr(tnext, 1); code.ldz_xor_in(tnext, wage_rate_bytes[4]); // Load the next 32 bits of the block to be absorbed. code.releaseReg(temp); temp = code.allocateReg(6); code.ldx(Reg(temp, 1, 4).reversed(), POST_INC); code.move(Reg(temp, 5, 1), 0); code.move(Reg(temp, 0, 1), 0); // Absorb the next 32-bits into the state pointed to by Z, // after breaking it up into 7-bit components. code.lsl(Reg(temp, 1, 5), 3); code.ldz_xor_in(Reg(temp, 5, 1), wage_rate_bytes[4]); tnext = Reg(temp, 1, 4); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 3, 1), wage_rate_bytes[5]); tnext = Reg(temp, 1, 3); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 2, 1), wage_rate_bytes[6]); tnext = Reg(temp, 1, 2); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 1, 1), wage_rate_bytes[7]); tnext = Reg(temp, 0, 2); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 1, 1), wage_rate_bytes[8]); tnext = Reg(temp, 0, 1); code.lsr(tnext, 1); code.ldz_xor_in(tnext, wage_rate_bytes[9]); } void gen_wage_get_rate(Code &code) { // Set up the function prologue with 0 bytes of local variable storage. code.prologue_setup_key("wage_get_rate", 0); code.setFlag(Code::NoLocals); // Combine the components for the first 32-bit word. Reg temp = code.allocateReg(4); code.ldz(Reg(temp, 3, 1), wage_rate_bytes[0]); code.ldz(Reg(temp, 2, 1), wage_rate_bytes[1]); code.ldz(Reg(temp, 1, 1), wage_rate_bytes[2]); code.ldz(Reg(temp, 0, 1), wage_rate_bytes[3]); code.lsl(Reg(temp, 0, 1), 1); code.lsl(Reg(temp, 0, 2), 1); code.lsl(Reg(temp, 0, 3), 1); code.lsl(Reg(temp, 0, 4), 1); Reg temp2 = code.allocateReg(1); code.ldz(temp2, wage_rate_bytes[4]); code.lsr(temp2, 3); code.logor(Reg(temp, 0, 1), temp2); code.stx(temp.reversed(), POST_INC); // Combine the components for the second 32-bit word. code.ldz(Reg(temp, 3, 1), wage_rate_bytes[4]); code.ldz(Reg(temp, 2, 1), wage_rate_bytes[5]); code.ldz(Reg(temp, 1, 1), wage_rate_bytes[6]); code.ldz(Reg(temp, 0, 1), wage_rate_bytes[7]); code.lsl(Reg(temp, 0, 1), 1); code.lsl(Reg(temp, 0, 2), 1); code.lsl(Reg(temp, 0, 3), 1); code.lsr(Reg(temp, 0, 4), 3); code.stx(Reg(temp, 0, 3).reversed(), POST_INC); code.ldz(Reg(temp, 1, 1), wage_rate_bytes[8]); code.ldz(Reg(temp, 0, 1), wage_rate_bytes[9]); code.lsl(Reg(temp, 0, 1), 1); code.lsl(Reg(temp, 0, 2), 1); code.stx(Reg(temp, 1, 1), POST_INC); } void gen_wage_set_rate(Code &code) { // Set up the function prologue with 0 bytes of local variable storage. code.prologue_setup_key("wage_set_rate", 0); code.setFlag(Code::NoLocals); // Load the first 32 bits of the block to be set. Reg temp = code.allocateReg(5); code.ldx(Reg(temp, 1, 4).reversed(), POST_INC); code.move(Reg(temp, 0, 1), 0); // Set the first 32-bits into the state pointed to by Z, // after breaking it up into 7-bit components. code.lsr(temp, 1); code.stz(Reg(temp, 4, 1), wage_rate_bytes[0]); Reg tnext = Reg(temp, 0, 4); code.lsr(tnext, 1); code.stz(Reg(tnext, 3, 1), wage_rate_bytes[1]); tnext = Reg(temp, 0, 3); code.lsr(tnext, 1); code.stz(Reg(tnext, 2, 1), wage_rate_bytes[2]); tnext = Reg(temp, 0, 2); code.lsr(tnext, 1); code.stz(Reg(tnext, 1, 1), wage_rate_bytes[3]); tnext = Reg(temp, 0, 1); code.lsr(tnext, 1); code.stz(tnext, wage_rate_bytes[4]); // Load the next 32 bits of the block to be set. code.releaseReg(temp); temp = code.allocateReg(6); code.ldx(Reg(temp, 1, 4).reversed(), POST_INC); code.move(Reg(temp, 5, 1), 0); code.move(Reg(temp, 0, 1), 0); // Set the next 32-bits into the state pointed to by Z, // after breaking it up into 7-bit components. code.lsl(Reg(temp, 1, 5), 3); code.ldz_xor_in(Reg(temp, 5, 1), wage_rate_bytes[4]); tnext = Reg(temp, 1, 4); code.lsr(tnext, 1); code.stz(Reg(tnext, 3, 1), wage_rate_bytes[5]); tnext = Reg(temp, 1, 3); code.lsr(tnext, 1); code.stz(Reg(tnext, 2, 1), wage_rate_bytes[6]); tnext = Reg(temp, 1, 2); code.lsr(tnext, 1); code.stz(Reg(tnext, 1, 1), wage_rate_bytes[7]); tnext = Reg(temp, 0, 2); code.lsr(tnext, 1); code.stz(Reg(tnext, 1, 1), wage_rate_bytes[8]); tnext = Reg(temp, 0, 1); code.lsr(tnext, 1); Reg tprev = code.allocateHighReg(1); code.ldz(tprev, wage_rate_bytes[9]); code.logand(tprev, 0x3F); code.logxor(tprev, tnext); code.stz(tprev, wage_rate_bytes[9]); } bool test_wage_permutation(Code &code) { static unsigned char const wage_input[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24 }; static unsigned char const wage_output[] = { 0x44, 0x78, 0x43, 0x21, 0x25, 0x6f, 0x30, 0x64, 0x00, 0x27, 0x00, 0x76, 0x27, 0x4b, 0x73, 0x25, 0x33, 0x43, 0x6c, 0x0e, 0x76, 0x17, 0x35, 0x49, 0x0a, 0x16, 0x69, 0x23, 0x1d, 0x39, 0x64, 0x36, 0x5f, 0x72, 0x18, 0x61, 0x01 }; unsigned char state[37]; memcpy(state, wage_input, 37); code.exec_permutation(state, 37); return !memcmp(wage_output, state, 37); }
23,958
12,186
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; ULONGLONG TraceKeywords::ParseTestKeyword(wstring const& testKeyword) { if (Common::StringUtility::AreEqualCaseInsensitive(testKeyword, L"Test0")) { return TraceKeywords::Test0; } if (Common::StringUtility::AreEqualCaseInsensitive(testKeyword, L"Test1")) { return TraceKeywords::Test1; } if (Common::StringUtility::AreEqualCaseInsensitive(testKeyword, L"Test2")) { return TraceKeywords::Test2; } if (Common::StringUtility::AreEqualCaseInsensitive(testKeyword, L"Test3")) { return TraceKeywords::Test3; } else return 0; }
966
284
// // @Author: Zhiquan Wang // @Date: 2/29/20. // Copyright (c) 2020 Zhiquan Wang. All rights reserved. // #include <Surface.h> #include "Surface.h" #include <iostream> GLuint Surface::counter = 0; Surface::Surface():id(counter++) { } Surface::Surface(glm::vec4 ids):id(counter++),indices(ids){ } bool Surface::is_contain_point(GLuint pid) { for(int i =0 ;i < 4;++ i){ if(pid == this->indices[i]){ return true; } } return false; } void Surface::set_center_pt(glm::vec3 c){ this->center_pt = c; } glm::vec2 Surface::get_edges_by_p(GLuint in_id){ GLuint tmp_id = -1; for(int i =0 ;i < 4;++ i){ if(in_id == this->indices[i]){ tmp_id = i; break; } } return glm::vec2(this->indices[(tmp_id+1)%4],this->indices[(tmp_id+3)%4]); } bool Surface::contain_edge(std::vector<GLuint> edge){ bool b0 = false; bool b1 = false; for(int i =0 ;i < 4;++ i){ if(float(edge[0]) ==indices[i]){ b0 = true; }else if(float(edge[1])==indices[i]){ b1 = true; } } return b0 && b1; }
1,131
475
#include <sigpack.h> using namespace arma; using namespace sp; int main() { int r=480, c=640; mat x(r,c); cx_mat X(r,c); clock_t tic; FFTW X_2d(r,c, FFTW_MEASURE); x.randn(); #if 1 // X_2d.export_wisdom_fft("wisd_fft.txt"); // X_2d.import_wisdom_file("wisd_fft.txt"); std::string str_fft = "\ (fftw-3.3.5 fftw_wisdom #x4be12fff #x7b2df9b2 #xa5975329 #x385b0041 \ (fftw_codelet_hc2cf_32 0 #x11048 #x11048 #x0 #x882273a3 #x56a533d6 #xc6c3347e #xd190e241) \ (fftw_dft_vrank_geq1_register 0 #x10048 #x10048 #x0 #x099817e7 #xc596b28c #xe506412c #x581cf2d0) \ (fftw_rdft2_rank_geq2_register 0 #x11048 #x11048 #x0 #xed40bad3 #x93c23437 #xaf3711ed #x603ee510) \ (fftw_rdft2_vrank_geq1_register 0 #x11048 #x11048 #x0 #x1a6357c6 #x413f903b #x74fe70f1 #xfccb5c54) \ (fftw_rdft_rank0_register 3 #x11048 #x11048 #x0 #x02d4eca5 #x884a04c6 #x3f0ad214 #xda717200) \ (fftw_dft_buffered_register 0 #x11048 #x11048 #x0 #x6196ea82 #x099f9b85 #x08198834 #xe7593275) \ (fftw_codelet_t1_10 0 #x10048 #x10048 #x0 #xba1708ce #x154e0e87 #x86aebd39 #xcb9e43fe) \ (fftw_rdft_vrank_geq1_register 1 #x11048 #x11048 #x0 #x081f12db #xc5b1275f #x5907e52d #x646a8914) \ (fftw_dft_r2hc_register 0 #x11048 #x11048 #x0 #x514942d9 #xe0534dce #x7d1dcd63 #xde881c5a) \ (fftw_codelet_n1_64 0 #x10048 #x10048 #x0 #x9dcd7b03 #xdf2d4251 #x0230d342 #xde1fe96d) \ (fftw_dft_r2hc_register 0 #x11048 #x11048 #x0 #x43917e3e #x5c1ab09e #xdc26854f #x352833a8) \ (fftw_codelet_r2cf_15 0 #x11048 #x11048 #x0 #x251274f4 #x219f0dbb #x0c38f4e4 #xf19e1c79) \ (fftw_dft_nop_register 0 #x11048 #x11048 #x0 #xc1cc28d6 #x5c67e01b #x280816eb #x7ee0ce02) \ (fftw_codelet_r2cf_32 2 #x11048 #x11048 #x0 #xc267a0b3 #xc28de71d #x550f0573 #x959c40e7) \ (fftw_codelet_n1_64 0 #x10048 #x10048 #x0 #x101f223c #xcff4353b #xd4a553bb #xe3ff9319) \ (fftw_dft_buffered_register 0 #x11048 #x11048 #x0 #x9973ff81 #x0b0fdaf1 #xfd5496b5 #xfe9c4fba) \ (fftw_codelet_t1_10 0 #x10048 #x10048 #x0 #x47334bf5 #x898f072c #x86c99502 #xe82acf7f) \ (fftw_rdft_rank0_register 2 #x11048 #x11048 #x0 #x5c2cc86a #x3d86b0c3 #xe3aeadc0 #xdc7e28da) \ (fftw_rdft2_nop_register 0 #x11048 #x11048 #x0 #xf80d9535 #x1b15b669 #x8ee1f97f #x42fa82cd))"; X_2d.import_wisdom_string(str_fft); tic = clock(); X = fft2(x); cout << "FFT Time using arma::fft2()= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl; tic = clock(); X = X_2d.fft2(x); cout << "FFTW Time using Wisdom= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl; #else tic = clock(); X = fft2(x); cout << "FFT Time using arma::fft2()= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl; tic = clock(); X = X_2d.fft2(x); cout << "FFTW Time without Wisdom= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl; #endif return 0; }
2,948
1,913
#include "dpf.h" #include "hashdatastore.h" #include <chrono> #include <iostream> void benchEvalFull(size_t N, size_t iter) { std::chrono::duration<double> buildT, evalT, answerT; buildT = evalT = answerT = std::chrono::duration<double>::zero(); std::cout << "EvalFull, " << iter << " iterations" << std::endl; auto time1 = std::chrono::high_resolution_clock::now(); auto keys = DPF::Gen(0, N); auto a = keys.first; auto time2 = std::chrono::high_resolution_clock::now(); for(size_t i = 0; i < iter; i++) { std::vector<uint8_t> aaaa = DPF::EvalFull(a, N); } auto time3 = std::chrono::high_resolution_clock::now(); buildT += time2 - time1; evalT += time3 - time2; std::cout << buildT.count() << "sec" << std::endl; std::cout << evalT.count() << "sec" << std::endl; } void benchEvalFull8(size_t N, size_t iter) { std::chrono::duration<double> buildT, evalT, answerT; buildT = evalT = answerT = std::chrono::duration<double>::zero(); std::cout << "EvalFull8, " << iter << " iterations" << std::endl; auto time1 = std::chrono::high_resolution_clock::now(); auto keys = DPF::Gen(0, N); auto a = keys.first; auto time2 = std::chrono::high_resolution_clock::now(); for(size_t i = 0; i < iter; i++) { std::vector<uint8_t> aaaa = DPF::EvalFull8(a, N); } auto time3 = std::chrono::high_resolution_clock::now(); buildT += time2 - time1; evalT += time3 - time2; std::cout << buildT.count() << "sec" << std::endl; std::cout << evalT.count() << "sec" << std::endl; } void benchAnswerPIR(size_t N, size_t iter) { std::array<std::chrono::duration<double>,6> answerT = {std::chrono::duration<double>::zero(), }; std::cout << "AnswerPIR, " << iter << " iterations" << std::endl; auto keys = DPF::Gen(0, N); auto a = keys.first; hashdatastore store; store.reserve(1ULL << N); for (size_t i = 0; i < (1ULL << N); i++) { store.push_back(_mm256_set_epi64x(i, i, i, i)); } std::vector<uint8_t> aaaa = DPF::EvalFull8(a, N); for(size_t i = 0; i < iter; i++) { auto time0 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer0 = store.answer_pir_idea_speed_comparison(aaaa); auto time1 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer1 = store.answer_pir1(aaaa); auto time2 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer2 = store.answer_pir2(aaaa); auto time3 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer3 = store.answer_pir3(aaaa); auto time4 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer4 = store.answer_pir4(aaaa); auto time5 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer5 = store.answer_pir5(aaaa); auto time6 = std::chrono::high_resolution_clock::now(); answerT[0] += time1-time0; answerT[1] += time2-time1; answerT[2] += time3-time2; answerT[3] += time4-time3; answerT[4] += time5-time4; answerT[5] += time6-time5; } std::cout << "AnswerPIR ideal " << answerT[0].count() << "sec" << std::endl; std::cout << "AnswerPIR1 " << answerT[1].count() << "sec" << std::endl; std::cout << "AnswerPIR2 " << answerT[2].count() << "sec" << std::endl; std::cout << "AnswerPIR3 " << answerT[3].count() << "sec" << std::endl; std::cout << "AnswerPIR4 " << answerT[4].count() << "sec" << std::endl; std::cout << "AnswerPIR5 " << answerT[5].count() << "sec" << std::endl; } int main(int argc, char** argv) { size_t N = 27; size_t iter = 100; benchEvalFull(N, iter); benchEvalFull8(N, iter); //benchAnswerPIR(25,100); return 0; }
3,883
1,464
#include <ros/ros.h> #include <std_msgs/Bool.h> #include <std_msgs/Byte.h> #include <std_msgs/Char.h> #include <std_msgs/Duration.h> #include <std_msgs/Time.h> #include <std_msgs/Int16.h> #include <std_msgs/Int32.h> #include <std_msgs/Int64.h> #include <std_msgs/Int8.h> #include <std_msgs/Header.h> #include <std_msgs/UInt16.h> #include <std_msgs/UInt32.h> #include <std_msgs/UInt64.h> #include <std_msgs/UInt8.h> #include <std_msgs/Float32.h> #include <std_msgs/Float64.h> void chatter1(const std_msgs::Bool::ConstPtr& msg) { ROS_INFO("I heard: [%s]", msg->data ? "true" : "false"); } void chatter2(const std_msgs::Byte::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter3(const std_msgs::Char::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter4(const std_msgs::Duration::ConstPtr& msg) { ROS_INFO("I heard: sec=[%i] nsec=[%i]", msg->data.sec, msg->data.nsec); } void chatter5(const std_msgs::Header::ConstPtr& msg) { ROS_INFO("I heard: seq = [%i], time = [%i, %i], frame_id = [%s]", msg->seq, msg->stamp.sec, msg->stamp.nsec, msg->frame_id.c_str()); } void chatter6(const std_msgs::Int16::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter7(const std_msgs::Int32::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter8(const std_msgs::Int64::ConstPtr& msg) { ROS_INFO("I heard: [%lli]", msg->data); } void chatter9(const std_msgs::Int8::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter10(const std_msgs::Time::ConstPtr& msg) { ROS_INFO("I heard: sec=[%i] nsec=[%i]", msg->data.sec, msg->data.nsec); } void chatter11(const std_msgs::UInt16::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter12(const std_msgs::UInt32::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter13(const std_msgs::UInt64::ConstPtr& msg) { ROS_INFO("I heard: [%lli]", msg->data); } void chatter14(const std_msgs::UInt8::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter15(const std_msgs::Float32::ConstPtr& msg) { ROS_INFO("I heard: [%f]", msg->data); } void chatter16(const std_msgs::Float64::ConstPtr& msg) { ROS_INFO("I heard: [%f]", msg->data); } int main(int argc, char **argv) { ros::init(argc, argv, "std_msgs_listener"); ros::NodeHandle n; ros::Subscriber sub1 = n.subscribe("bool", 1000, chatter1); ros::Subscriber sub2 = n.subscribe("byte", 1000, chatter2); ros::Subscriber sub3 = n.subscribe("char", 1000, chatter3); ros::Subscriber sub4 = n.subscribe("duration", 1000, chatter4); ros::Subscriber sub5 = n.subscribe("header", 1000, chatter5); ros::Subscriber sub6 = n.subscribe("/int16", 1000, chatter6); ros::Subscriber sub7 = n.subscribe("/int32", 1000, chatter7); ros::Subscriber sub8 = n.subscribe("/int64", 1000, chatter8); ros::Subscriber sub9 = n.subscribe("/int8", 1000, chatter9); ros::Subscriber sub10 = n.subscribe("/time", 1000, chatter10); ros::Subscriber sub11 = n.subscribe("/uint16", 1000, chatter11); ros::Subscriber sub12 = n.subscribe("/uint32", 1000, chatter12); ros::Subscriber sub13 = n.subscribe("/uint64", 1000, chatter13); ros::Subscriber sub14 = n.subscribe("/uint8", 1000, chatter14); ros::Subscriber sub15 = n.subscribe("/float32", 1000, chatter15); ros::Subscriber sub16 = n.subscribe("/float64", 1000, chatter16); ros::spin(); return 0; }
3,400
1,553
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/passwords/manage_passwords_state.h" #include <iterator> #include <memory> #include <utility> #include <vector> #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/mock_callback.h" #include "components/password_manager/core/browser/mock_password_form_manager_for_ui.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/common/password_manager_ui.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" using autofill::PasswordForm; using base::ASCIIToUTF16; using password_manager::MockPasswordFormManagerForUI; using password_manager::PasswordStoreChange; using password_manager::PasswordStoreChangeList; using ::testing::_; using ::testing::Contains; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::Mock; using ::testing::Not; using ::testing::Pointee; using ::testing::Return; using ::testing::UnorderedElementsAre; namespace { constexpr char kTestOrigin[] = "http://example.com/"; constexpr char kTestPSLOrigin[] = "http://1.example.com/"; std::vector<const PasswordForm*> GetRawPointers( const std::vector<std::unique_ptr<PasswordForm>>& forms) { std::vector<const PasswordForm*> result; std::transform( forms.begin(), forms.end(), std::back_inserter(result), [](const std::unique_ptr<PasswordForm>& form) { return form.get(); }); return result; } class MockPasswordManagerClient : public password_manager::StubPasswordManagerClient { public: MOCK_METHOD0(UpdateFormManagers, void()); }; class ManagePasswordsStateTest : public testing::Test { public: void SetUp() override { saved_match_.url = GURL(kTestOrigin); saved_match_.signon_realm = kTestOrigin; saved_match_.username_value = base::ASCIIToUTF16("username"); saved_match_.username_element = base::ASCIIToUTF16("username_element"); saved_match_.password_value = base::ASCIIToUTF16("12345"); saved_match_.password_element = base::ASCIIToUTF16("password_element"); psl_match_ = saved_match_; psl_match_.url = GURL(kTestPSLOrigin); psl_match_.signon_realm = kTestPSLOrigin; psl_match_.username_value = base::ASCIIToUTF16("username_psl"); psl_match_.is_public_suffix_match = true; local_federated_form_ = saved_match_; local_federated_form_.federation_origin = url::Origin::Create(GURL("https://idp.com")); local_federated_form_.password_value.clear(); local_federated_form_.signon_realm = "federation://example.com/accounts.com"; passwords_data_.set_client(&mock_client_); } PasswordForm& saved_match() { return saved_match_; } PasswordForm& psl_match() { return psl_match_; } PasswordForm& local_federated_form() { return local_federated_form_; } ManagePasswordsState& passwords_data() { return passwords_data_; } // Returns a mock PasswordFormManager containing |best_matches| and // |federated_matches|. std::unique_ptr<MockPasswordFormManagerForUI> CreateFormManager( std::vector<const PasswordForm*>* best_matches, const std::vector<const PasswordForm*>& federated_matches); // Pushes irrelevant updates to |passwords_data_| and checks that they don't // affect the state. void TestNoisyUpdates(); // Pushes both relevant and irrelevant updates to |passwords_data_|. void TestAllUpdates(); // Pushes a blocklisted form and checks that it doesn't affect the state. void TestBlocklistedUpdates(); private: MockPasswordManagerClient mock_client_; ManagePasswordsState passwords_data_; PasswordForm saved_match_; PasswordForm psl_match_; PasswordForm local_federated_form_; }; std::unique_ptr<MockPasswordFormManagerForUI> ManagePasswordsStateTest::CreateFormManager( std::vector<const PasswordForm*>* best_matches, const std::vector<const PasswordForm*>& federated_matches) { auto form_manager = std::make_unique<MockPasswordFormManagerForUI>(); EXPECT_CALL(*form_manager, GetBestMatches()) .WillOnce(testing::ReturnRef(*best_matches)); EXPECT_CALL(*form_manager, GetFederatedMatches()) .WillOnce(Return(federated_matches)); EXPECT_CALL(*form_manager, GetURL()) .WillOnce(testing::ReturnRef(saved_match_.url)); return form_manager; } void ManagePasswordsStateTest::TestNoisyUpdates() { const std::vector<const PasswordForm*> forms = GetRawPointers(passwords_data_.GetCurrentForms()); const password_manager::ui::State state = passwords_data_.state(); const url::Origin origin = passwords_data_.origin(); // Push "Add". PasswordForm form; form.url = GURL("http://3rdparty.com"); form.username_value = base::ASCIIToUTF16("username"); form.password_value = base::ASCIIToUTF16("12345"); PasswordStoreChange change(PasswordStoreChange::ADD, form); PasswordStoreChangeList list(1, change); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); // Update the form. form.password_value = base::ASCIIToUTF16("password"); list[0] = PasswordStoreChange(PasswordStoreChange::UPDATE, form); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); // Delete the form. list[0] = PasswordStoreChange(PasswordStoreChange::REMOVE, form); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); } void ManagePasswordsStateTest::TestAllUpdates() { const std::vector<const PasswordForm*> forms = GetRawPointers(passwords_data_.GetCurrentForms()); const password_manager::ui::State state = passwords_data_.state(); const url::Origin origin = passwords_data_.origin(); EXPECT_NE(url::Origin(), origin); // Push "Add". PasswordForm form; GURL::Replacements replace_path; replace_path.SetPathStr("absolutely_different_path"); form.url = origin.GetURL().ReplaceComponents(replace_path); form.signon_realm = form.url.GetOrigin().spec(); form.username_value = base::ASCIIToUTF16("user15"); form.password_value = base::ASCIIToUTF16("12345"); PasswordStoreChange change(PasswordStoreChange::ADD, form); PasswordStoreChangeList list(1, change); EXPECT_CALL(mock_client_, UpdateFormManagers()).Times(0); passwords_data().ProcessLoginsChanged(list); EXPECT_THAT(passwords_data().GetCurrentForms(), Contains(Pointee(form))); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); Mock::VerifyAndClearExpectations(&mock_client_); // Remove and Add form. list[0] = PasswordStoreChange(PasswordStoreChange::REMOVE, form); form.username_value = base::ASCIIToUTF16("user15"); list.push_back(PasswordStoreChange(PasswordStoreChange::ADD, form)); EXPECT_CALL(mock_client_, UpdateFormManagers()).Times(0); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); Mock::VerifyAndClearExpectations(&mock_client_); list.erase(++list.begin()); // Update the form. form.password_value = base::ASCIIToUTF16("password"); list[0] = PasswordStoreChange(PasswordStoreChange::UPDATE, form); EXPECT_CALL(mock_client_, UpdateFormManagers()).Times(0); passwords_data().ProcessLoginsChanged(list); EXPECT_THAT(passwords_data().GetCurrentForms(), Contains(Pointee(form))); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); Mock::VerifyAndClearExpectations(&mock_client_); // Delete the form. list[0] = PasswordStoreChange(PasswordStoreChange::REMOVE, form); EXPECT_CALL(mock_client_, UpdateFormManagers()); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); Mock::VerifyAndClearExpectations(&mock_client_); TestNoisyUpdates(); } void ManagePasswordsStateTest::TestBlocklistedUpdates() { const std::vector<const PasswordForm*> forms = GetRawPointers(passwords_data_.GetCurrentForms()); const password_manager::ui::State state = passwords_data_.state(); const url::Origin origin = passwords_data_.origin(); EXPECT_FALSE(origin.opaque()); // Process the blocked form. PasswordForm blocked_form; blocked_form.blocked_by_user = true; blocked_form.url = origin.GetURL(); PasswordStoreChangeList list; list.push_back(PasswordStoreChange(PasswordStoreChange::ADD, blocked_form)); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); // Delete the blocked form. list[0] = PasswordStoreChange(PasswordStoreChange::REMOVE, blocked_form); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); } TEST_F(ManagePasswordsStateTest, DefaultState) { EXPECT_THAT(passwords_data().GetCurrentForms(), IsEmpty()); EXPECT_EQ(password_manager::ui::INACTIVE_STATE, passwords_data().state()); EXPECT_TRUE(passwords_data().origin().opaque()); EXPECT_FALSE(passwords_data().form_manager()); TestNoisyUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordSubmitted) { std::vector<const PasswordForm*> best_matches = {&saved_match(), &psl_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); ASSERT_TRUE(passwords_data().form_manager()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordSaved) { std::vector<const PasswordForm*> best_matches = {&saved_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE, passwords_data().state()); passwords_data().TransitionToState(password_manager::ui::MANAGE_STATE); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordSubmittedFederationsPresent) { std::vector<const PasswordForm*> best_matches; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {&local_federated_form()})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(local_federated_form()))); } TEST_F(ManagePasswordsStateTest, OnRequestCredentials) { std::vector<std::unique_ptr<PasswordForm>> local_credentials; local_credentials.emplace_back(new PasswordForm(saved_match())); const url::Origin origin = url::Origin::Create(saved_match().url); passwords_data().OnRequestCredentials(std::move(local_credentials), origin); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::CREDENTIAL_REQUEST_STATE, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); TestAllUpdates(); EXPECT_CALL(callback, Run(nullptr)); passwords_data().TransitionToState(password_manager::ui::MANAGE_STATE); EXPECT_TRUE(passwords_data().credentials_callback().is_null()); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, AutoSignin) { std::vector<std::unique_ptr<PasswordForm>> local_credentials; local_credentials.emplace_back(new PasswordForm(saved_match())); passwords_data().OnAutoSignin(std::move(local_credentials), url::Origin::Create(saved_match().url)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::AUTO_SIGNIN_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(saved_match().url), passwords_data().origin()); TestAllUpdates(); passwords_data().TransitionToState(password_manager::ui::MANAGE_STATE); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(saved_match().url), passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, AutomaticPasswordSave) { std::vector<const PasswordForm*> best_matches = {&saved_match(), &psl_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnAutomaticPasswordSave(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::CONFIRMATION_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); ASSERT_TRUE(passwords_data().form_manager()); TestAllUpdates(); passwords_data().TransitionToState(password_manager::ui::MANAGE_STATE); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, AutomaticPasswordSaveWithFederations) { std::vector<const PasswordForm*> best_matches = {&saved_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {&local_federated_form()})); passwords_data().OnAutomaticPasswordSave(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), UnorderedElementsAre(Pointee(saved_match()), Pointee(local_federated_form()))); } TEST_F(ManagePasswordsStateTest, PasswordAutofilled) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&saved_match()); const url::Origin origin = url::Origin::Create(GURL(kTestOrigin)); passwords_data().OnPasswordAutofilled(password_forms, origin, nullptr); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordAutofillWithSavedFederations) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&saved_match()); const url::Origin origin = url::Origin::Create(GURL(kTestOrigin)); std::vector<const PasswordForm*> federated; federated.push_back(&local_federated_form()); passwords_data().OnPasswordAutofilled(password_forms, origin, &federated); // |federated| represents the locally saved federations. These are bundled in // the "current forms". EXPECT_THAT(passwords_data().GetCurrentForms(), UnorderedElementsAre(Pointee(saved_match()), Pointee(local_federated_form()))); // |federated_credentials_forms()| do not refer to the saved federations. EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); } TEST_F(ManagePasswordsStateTest, PasswordAutofillWithOnlyFederations) { std::vector<const PasswordForm*> password_forms; const url::Origin origin = url::Origin::Create(GURL(kTestOrigin)); std::vector<const PasswordForm*> federated; federated.push_back(&local_federated_form()); passwords_data().OnPasswordAutofilled(password_forms, origin, &federated); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(local_federated_form()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); } TEST_F(ManagePasswordsStateTest, ActiveOnMixedPSLAndNonPSLMatched) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&saved_match()); password_forms.push_back(&psl_match()); const url::Origin origin = url::Origin::Create(GURL(kTestOrigin)); passwords_data().OnPasswordAutofilled(password_forms, origin, nullptr); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, InactiveOnPSLMatched) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&psl_match()); passwords_data().OnPasswordAutofilled( password_forms, url::Origin::Create(GURL(kTestOrigin)), nullptr); EXPECT_THAT(passwords_data().GetCurrentForms(), IsEmpty()); EXPECT_EQ(password_manager::ui::INACTIVE_STATE, passwords_data().state()); EXPECT_TRUE(passwords_data().origin().opaque()); EXPECT_FALSE(passwords_data().form_manager()); } TEST_F(ManagePasswordsStateTest, OnInactive) { std::vector<const PasswordForm*> best_matches; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE, passwords_data().state()); passwords_data().OnInactive(); EXPECT_THAT(passwords_data().GetCurrentForms(), IsEmpty()); EXPECT_EQ(password_manager::ui::INACTIVE_STATE, passwords_data().state()); EXPECT_TRUE(passwords_data().origin().opaque()); EXPECT_FALSE(passwords_data().form_manager()); TestNoisyUpdates(); } TEST_F(ManagePasswordsStateTest, PendingPasswordAddBlacklisted) { std::vector<const PasswordForm*> best_matches; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, RequestCredentialsAddBlacklisted) { std::vector<std::unique_ptr<PasswordForm>> local_credentials; local_credentials.emplace_back(new PasswordForm(saved_match())); const url::Origin origin = url::Origin::Create(saved_match().url); passwords_data().OnRequestCredentials(std::move(local_credentials), origin); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_EQ(password_manager::ui::CREDENTIAL_REQUEST_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, AutoSigninAddBlacklisted) { std::vector<std::unique_ptr<PasswordForm>> local_credentials; local_credentials.emplace_back(new PasswordForm(saved_match())); passwords_data().OnAutoSignin(std::move(local_credentials), url::Origin::Create(saved_match().url)); EXPECT_EQ(password_manager::ui::AUTO_SIGNIN_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, AutomaticPasswordSaveAddBlacklisted) { std::vector<const PasswordForm*> best_matches; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnAutomaticPasswordSave(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::CONFIRMATION_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, BackgroundAutofilledAddBlacklisted) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&saved_match()); passwords_data().OnPasswordAutofilled( password_forms, url::Origin::Create(password_forms.front()->url), nullptr); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordUpdateAddBlacklisted) { std::vector<const PasswordForm*> best_matches = {&saved_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnUpdatePassword(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordUpdateSubmitted) { std::vector<const PasswordForm*> best_matches = {&saved_match(), &psl_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnUpdatePassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); ASSERT_TRUE(passwords_data().form_manager()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, AndroidPasswordUpdateSubmitted) { PasswordForm android_form; android_form.signon_realm = "android://dHJhc2g=@com.example.android/"; android_form.url = GURL(android_form.signon_realm); android_form.username_value = base::ASCIIToUTF16("username"); android_form.password_value = base::ASCIIToUTF16("old pass"); std::vector<const PasswordForm*> best_matches = {&android_form}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnUpdatePassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(android_form))); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); ASSERT_TRUE(passwords_data().form_manager()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordUpdateSubmittedWithFederations) { std::vector<const PasswordForm*> best_matches = {&saved_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {&local_federated_form()})); passwords_data().OnUpdatePassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), UnorderedElementsAre(Pointee(saved_match()), Pointee(local_federated_form()))); } TEST_F(ManagePasswordsStateTest, ChooseCredentialLocal) { passwords_data().OnRequestCredentials( std::vector<std::unique_ptr<PasswordForm>>(), url::Origin::Create(saved_match().url)); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_CALL(callback, Run(&saved_match())); passwords_data().ChooseCredential(&saved_match()); } TEST_F(ManagePasswordsStateTest, ChooseCredentialEmpty) { passwords_data().OnRequestCredentials( std::vector<std::unique_ptr<PasswordForm>>(), url::Origin::Create(saved_match().url)); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_CALL(callback, Run(nullptr)); passwords_data().ChooseCredential(nullptr); } TEST_F(ManagePasswordsStateTest, ChooseCredentialLocalWithNonEmptyFederation) { passwords_data().OnRequestCredentials( std::vector<std::unique_ptr<PasswordForm>>(), url::Origin::Create(saved_match().url)); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_CALL(callback, Run(&local_federated_form())); passwords_data().ChooseCredential(&local_federated_form()); } TEST_F(ManagePasswordsStateTest, AutofillCausedByInternalFormManager) { struct OwningPasswordFormManagerForUI : public MockPasswordFormManagerForUI { GURL url; std::vector<const autofill::PasswordForm*> best_matches; std::vector<const autofill::PasswordForm*> federated_matches; const GURL& GetURL() const override { return url; } const std::vector<const autofill::PasswordForm*>& GetBestMatches() const override { return best_matches; } std::vector<const autofill::PasswordForm*> GetFederatedMatches() const override { return federated_matches; } }; auto test_form_manager = std::make_unique<OwningPasswordFormManagerForUI>(); auto* weak_manager = test_form_manager.get(); test_form_manager->url = saved_match().url; test_form_manager->best_matches = {&saved_match()}; test_form_manager->federated_matches = {&local_federated_form()}; passwords_data().OnPendingPassword(std::move(test_form_manager)); // Force autofill with the parameters coming from the object to be destroyed. passwords_data().OnPasswordAutofilled(weak_manager->best_matches, url::Origin::Create(weak_manager->url), &weak_manager->federated_matches); EXPECT_THAT(passwords_data().GetCurrentForms(), UnorderedElementsAre(Pointee(local_federated_form()), Pointee(saved_match()))); EXPECT_EQ(url::Origin::Create(saved_match().url), passwords_data().origin()); } TEST_F(ManagePasswordsStateTest, ProcessUnsyncedCredentialsWillBeDeleted) { std::vector<PasswordForm> unsynced_credentials(1); unsynced_credentials[0].username_value = ASCIIToUTF16("user"); unsynced_credentials[0].password_value = ASCIIToUTF16("password"); passwords_data().ProcessUnsyncedCredentialsWillBeDeleted( unsynced_credentials); EXPECT_EQ(passwords_data().state(), password_manager::ui::WILL_DELETE_UNSYNCED_ACCOUNT_PASSWORDS_STATE); EXPECT_EQ(passwords_data().unsynced_credentials(), unsynced_credentials); } TEST_F(ManagePasswordsStateTest, OnMovablePasswordSubmitted) { std::vector<const PasswordForm*> password_forms = {&saved_match()}; std::vector<const PasswordForm*> federated_matches = { &local_federated_form()}; passwords_data().OnPasswordMovable( CreateFormManager(&password_forms, federated_matches)); EXPECT_THAT( passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()), Pointee(local_federated_form()))); EXPECT_EQ(passwords_data().state(), password_manager::ui::CAN_MOVE_PASSWORD_TO_ACCOUNT_STATE); EXPECT_EQ(passwords_data().origin(), url::Origin::Create(GURL(kTestOrigin))); TestAllUpdates(); } } // namespace
28,271
9,011
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_TRIANGLEITERATOR_HPP #define NAZARA_TRIANGLEITERATOR_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Utility/Enums.hpp> #include <Nazara/Utility/IndexMapper.hpp> namespace Nz { class SubMesh; class NAZARA_UTILITY_API TriangleIterator { public: TriangleIterator(PrimitiveMode primitiveMode, const IndexBuffer& indexBuffer); TriangleIterator(const SubMesh& subMesh); ~TriangleIterator() = default; bool Advance(); UInt32 operator[](std::size_t i) const; void Unmap(); private: PrimitiveMode m_primitiveMode; UInt32 m_triangleIndices[3]; IndexMapper m_indexMapper; std::size_t m_currentIndex; std::size_t m_indexCount; }; } #endif // NAZARA_TRIANGLEITERATOR_HPP
924
378
/*---------------------------------------------------------------------------------- Tines - Time Integrator, Newton and Eigen Solver - version 1.0 Copyright (2021) NTESS https://github.com/sandialabs/Tines Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. This file is part of Tines. Tines is open-source software: you can redistribute it and/or modify it under the terms of BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause). A copy of the license is also provided under the main directory Questions? Kyungjoo Kim <kyukim@sandia.gov>, or Oscar Diaz-Ibarra at <odiazib@sandia.gov>, or Cosmin Safta at <csafta@sandia.gov>, or Habib Najm at <hnnajm@sandia.gov> Sandia National Laboratories, New Mexico, USA ----------------------------------------------------------------------------------*/ #include "Tines.hpp" #include "Tines_TestUtils.hpp" int main(int argc, char **argv) { Kokkos::initialize(argc, argv); { printTestInfo info("EigenvalueSchur"); using ats = Tines::ats<real_type>; using Side = Tines::Side; using Trans = Tines::Trans; using Uplo = Tines::Uplo; using Diag = Tines::Diag; std::string filename; ordinal_type m = 12; Kokkos::View<real_type **, Kokkos::LayoutRight, host_device_type> A("A", m, m); if (argc == 2) { filename = argv[1]; Tines::readMatrix(filename, A); m = A.extent(0); } Kokkos::View<real_type **, Kokkos::LayoutRight, host_device_type> B("B", m, m); Kokkos::View<real_type **, Kokkos::LayoutRight, host_device_type> Q("Q", m, m); Kokkos::View<real_type **, Kokkos::LayoutRight, host_device_type> eig("eig", m, 2); Kokkos::View<ordinal_type *, Kokkos::LayoutRight, host_device_type> b("b", m); Kokkos::View<real_type *, Kokkos::LayoutRight, host_device_type> t("t", m); Kokkos::View<real_type *, Kokkos::LayoutRight, host_device_type> w("w", m); const real_type /* one(1), */ zero(0); const auto member = Tines::HostSerialTeamMember(); if (filename.empty()) { Kokkos::Random_XorShift64_Pool<host_device_type> random(13718); Kokkos::fill_random(A, random, real_type(1.0)); } bool is_valid(false); Tines::CheckNanInf::invoke(member, A, is_valid); std::cout << "Random matrix created " << (is_valid ? "is valid" : "is NOT valid") << "\n\n"; Tines::showMatrix("A (original)", A); Tines::Copy::invoke(member, A, B); Tines::Hessenberg::invoke(member, A, t, w); Tines::SetTriangularMatrix<Uplo::Lower>::invoke(member, 2, zero, A); Tines::showMatrix("A (after Hess)", A); /// A = Q T Q^H auto er = Kokkos::subview(eig, Kokkos::ALL(), 0); auto ei = Kokkos::subview(eig, Kokkos::ALL(), 1); const ordinal_type r_val = Tines::Schur::invoke(member, A, Q, er, ei, b); if (r_val == 0) { Tines::showMatrix("A (after Schur)", A); /// Compute Eigenvalues from Schur Tines::showMatrix("eig", eig); if (!filename.empty()) { std::string filenameEig = filename + ".eig"; printf("save file %s \n", filenameEig.c_str()); Tines::writeMatrix(filenameEig, eig); } } else { printf("Schur decomposition does not converge at a row %d\n", -r_val); } } Kokkos::finalize(); return 0; }
3,728
1,286
#include <iostream> #include <cstdio> #include <cmath> #include <string> #include <deque> using namespace std; int main() { int n_cases; cin >> n_cases; for (int i_case = 0; i_case < n_cases; i_case++) { string s; cin >> s; deque<char> d; d.push_front(s[0]); for (int i = 1; i < s.size(); i++) { // Compare the two deques deque<char> front(d); front.push_front(s[i]); deque<char> back(d); back.push_back(s[i]); bool yay_front = true; for (int j = 0; j < front.size(); j++) { if ((int)back[j] > (int)front[j]) { yay_front = false; break; } else if ((int)back[j] < (int)front[j]) { yay_front = true; break; } } if (yay_front) { d.push_front(s[i]); } else { d.push_back(s[i]); } } printf("Case #%d: ", i_case + 1); for (int i = 0; i < d.size(); i++) { cout << d[i]; } cout << endl; } return 0; }
979
400
# include <bits/stdc++.h> # define ll long long # define all(x) x.begin(), x.end() # define fastio ios_base::sync_with_stdio(false); cin.tie(NULL) # define ten6 (1e6+1.5) using namespace std; ll dp [(int)ten6]{0}; vector <int> c; ll solve (int x){ if (x==0) return 0; if (dp[x]) return dp[x]; ll re=ten6; for (auto v:c) { if (v>x) continue; re=min(re,1+solve(x-v)); } return dp[x]=re; } int main() { fastio; int n,x; cin>>n>>x; c.assign(n,0); for (auto &v:c){ cin>>v; dp[v]=1; } ll re=solve(x); if (re<(ll)(ten6)) cout<<solve(x)<<'\n'; else cout<<-1<<'\n'; return 0; }
709
321
/** * @file softmax_regression_impl.hpp * @author Siddharth Agrawal * * Implementation of softmax regression. */ #ifndef __MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_IMPL_HPP #define __MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_IMPL_HPP // In case it hasn't been included yet. #include "softmax_regression.hpp" namespace mlpack { namespace regression { template<template<typename> class OptimizerType> SoftmaxRegression<OptimizerType>:: SoftmaxRegression(const size_t inputSize, const size_t numClasses, const bool fitIntercept) : numClasses(numClasses), lambda(0.0001), fitIntercept(fitIntercept) { SoftmaxRegressionFunction::InitializeWeights(parameters, inputSize, numClasses, fitIntercept); } template<template<typename> class OptimizerType> SoftmaxRegression<OptimizerType>::SoftmaxRegression(const arma::mat& data, const arma::Row<size_t>& labels, const size_t numClasses, const double lambda, const bool fitIntercept) : numClasses(numClasses), lambda(lambda), fitIntercept(fitIntercept) { SoftmaxRegressionFunction regressor(data, labels, numClasses, lambda, fitIntercept); OptimizerType<SoftmaxRegressionFunction> optimizer(regressor); parameters = regressor.GetInitialPoint(); Train(optimizer); } template<template<typename> class OptimizerType> SoftmaxRegression<OptimizerType>::SoftmaxRegression( OptimizerType<SoftmaxRegressionFunction>& optimizer) : parameters(optimizer.Function().GetInitialPoint()), numClasses(optimizer.Function().NumClasses()), lambda(optimizer.Function().Lambda()), fitIntercept(optimizer.Function().FitIntercept()) { Train(optimizer); } template<template<typename> class OptimizerType> void SoftmaxRegression<OptimizerType>::Predict(const arma::mat& testData, arma::vec& predictions) { // Calculate the probabilities for each test input. arma::mat hypothesis, probabilities; if (fitIntercept) { // In order to add the intercept term, we should compute following matrix: // [1; data] = arma::join_cols(ones(1, data.n_cols), data) // hypothesis = arma::exp(parameters * [1; data]). // // Since the cost of join maybe high due to the copy of original data, // split the hypothesis computation to two components. hypothesis = arma::exp( arma::repmat(parameters.col(0), 1, testData.n_cols) + parameters.cols(1, parameters.n_cols - 1) * testData); } else { hypothesis = arma::exp(parameters * testData); } probabilities = hypothesis / arma::repmat(arma::sum(hypothesis, 0), numClasses, 1); // Prepare necessary data. predictions.zeros(testData.n_cols); double maxProbability = 0; // For each test input. for(size_t i = 0; i < testData.n_cols; i++) { // For each class. for(size_t j = 0; j < numClasses; j++) { // If a higher class probability is encountered, change prediction. if(probabilities(j, i) > maxProbability) { maxProbability = probabilities(j, i); predictions(i) = static_cast<double>(j); } } // Set maximum probability to zero for the next input. maxProbability = 0; } } template<template<typename> class OptimizerType> double SoftmaxRegression<OptimizerType>::ComputeAccuracy( const arma::mat& testData, const arma::Row<size_t>& labels) { arma::vec predictions; // Get predictions for the provided data. Predict(testData, predictions); // Increment count for every correctly predicted label. size_t count = 0; for (size_t i = 0; i < predictions.n_elem; i++) if (predictions(i) == labels(i)) count++; // Return percentage accuracy. return (count * 100.0) / predictions.n_elem; } template<template<typename> class OptimizerType> double SoftmaxRegression<OptimizerType>::Train( OptimizerType<SoftmaxRegressionFunction>& optimizer) { // Train the model. Timer::Start("softmax_regression_optimization"); const double out = optimizer.Optimize(parameters); Timer::Stop("softmax_regression_optimization"); Log::Info << "SoftmaxRegression::SoftmaxRegression(): final objective of " << "trained model is " << out << "." << std::endl; return out; } template<template<typename> class OptimizerType> double SoftmaxRegression<OptimizerType>::Train(const arma::mat& data, const arma::Row<size_t>& labels, const size_t numClasses) { SoftmaxRegressionFunction regressor(data, labels, numClasses, lambda, fitIntercept); OptimizerType<SoftmaxRegressionFunction> optimizer(regressor); return Train(optimizer); } } // namespace regression } // namespace mlpack #endif
5,225
1,557
#include "InstanceView.h" namespace instreclib { namespace reconstruction {} // namespace reconstruction } // namespace instreclib
136
38
// 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/sync/base/invalidation_helper.h" #include <string> namespace syncer { TopicSet ModelTypeSetToTopicSet(ModelTypeSet model_types) { TopicSet topics; for (ModelType type : model_types) { Topic topic; if (!RealModelTypeToNotificationType(type, &topic)) { DLOG(WARNING) << "Invalid model type " << type; continue; } topics.insert(topic); } return topics; } } // namespace syncer
602
197
#include "Visualization.h" #include <SFML/Graphics/CircleShape.hpp> #include <SFML/Window/Event.hpp> #include <memory> #include <thread> #define GREEN sf::Color(0,200,0,255); Visualization::Visualization(const sf::Vector2f & preferedWindowSize, const sf::Vector2f & minCoord, const sf::Vector2f & maxCoord, const std::vector<sf::Vector2f>& vectorData, const float & pointSize, const long long& millisecondPause) : m_vectors(vectorData), m_pointSize(pointSize), m_millisecondPause(millisecondPause) { //get the adjusted windowsize sf::Vector2i windowSize = calculateWindowSize(preferedWindowSize, minCoord, maxCoord, .2f); m_renderWindow = new sf::RenderWindow(sf::VideoMode(windowSize.x,windowSize.y), "Convex Hull Comparison"); //add lines for the axis sf::VertexArray* horizontalAxis = new sf::VertexArray(sf::LinesStrip, 2); (*horizontalAxis)[0].position = sf::Vector2f(0, m_origin.y); (*horizontalAxis)[0].color = sf::Color(0, 0, 0, 100); (*horizontalAxis)[1].position = sf::Vector2f(static_cast<float>(windowSize.x), m_origin.y); (*horizontalAxis)[1].color = sf::Color(0, 0, 0, 100); sf::VertexArray* verticalAxis = new sf::VertexArray(*horizontalAxis); (*verticalAxis)[0].position = sf::Vector2f(m_origin.x, 0); (*verticalAxis)[1].position = sf::Vector2f(m_origin.x, static_cast<float>(windowSize.y)); m_drawableVectors.push_back(horizontalAxis); m_drawableVectors.push_back(verticalAxis); for (auto& pos : m_vectors) { //create a new circle for every point sf::CircleShape* shape = new sf::CircleShape(m_pointSize); //configure circle shape->setOrigin(shape->getRadius(), shape->getRadius()); shape->setPosition(pos*m_zoomFactor + m_origin); //setup circle visuals shape->setFillColor(sf::Color::Transparent); shape->setOutlineColor(sf::Color::Black); shape->setOutlineThickness(2.f); //store the circles in a list m_drawableVectors.push_back(shape); } //create and configure lines m_checkline = new sf::VertexArray(sf::LinesStrip, 2); (*m_checkline)[0].color = GREEN; (*m_checkline)[1].color = GREEN; m_candidateLine = new sf::VertexArray(sf::LinesStrip, 2); (*m_candidateLine)[0].color = sf::Color::Black; (*m_candidateLine)[1].color = sf::Color::Black; } Visualization::~Visualization() { for (int i = 0; i < m_drawableVectors.size(); ++i) { delete m_drawableVectors[i]; } delete m_renderWindow; delete m_candidateLine; delete m_checkline; delete m_currentAnchor; delete m_hull; } // Renders the hull with a red line from hullpoints[0], hullpoints[1] .. hullpoints[n] // and renders the last point of the hull with a blue circle void Visualization::RenderPartialHull(const std::vector<sf::Vector2f>& hullPoints) { //override the existing hull m_hull = new sf::VertexArray(sf::LinesStrip, hullPoints.size()); //save all positions for (unsigned int i = 0; i < hullPoints.size(); ++i) { (*m_hull)[i].position = hullPoints[i] * m_zoomFactor + m_origin; (*m_hull)[i].color = sf::Color::Red; } if (m_currentAnchor == nullptr) { //create new circle for the current anchor m_currentAnchor = new sf::CircleShape(m_pointSize); m_currentAnchor->setOrigin(m_currentAnchor->getRadius(), m_currentAnchor->getRadius()); m_currentAnchor->setFillColor(sf::Color::Blue); } //set the current anchor to the position of the last point m_currentAnchor->setPosition(*(hullPoints.end() - 1)*m_zoomFactor + m_origin); //reset the check- and candidate line (*m_checkline)[0].position = m_currentAnchor->getPosition(); (*m_checkline)[1].position = m_currentAnchor->getPosition(); (*m_candidateLine)[0].position = m_currentAnchor->getPosition(); (*m_candidateLine)[1].position = m_currentAnchor->getPosition(); draw(); } void Visualization::RenderCompleteHull(const std::vector<sf::Vector2f>& hullPoints) { //override the current hull m_hull = new sf::VertexArray(sf::LinesStrip, hullPoints.size()+1); //save all positions for (unsigned int i = 0; i < hullPoints.size(); ++i) { (*m_hull)[i].position = hullPoints[i] * m_zoomFactor + m_origin; (*m_hull)[i].color = sf::Color::Red; } //set last point to be connected to the first one (*m_hull)[hullPoints.size()].position = hullPoints[0] * m_zoomFactor + m_origin; (*m_hull)[hullPoints.size()].color = sf::Color::Red; //delete shapes and explicitly set them to nullpointer delete m_currentAnchor; m_currentAnchor = nullptr; delete m_checkline; m_checkline = nullptr; delete m_candidateLine; m_candidateLine = nullptr; draw(); } // Renders a green line between the current anchor and the checkPoint void Visualization::RenderCheckLine(const sf::Vector2f & checkPoint) { (*m_checkline)[0].position = m_currentAnchor->getPosition(); (*m_checkline)[1].position = checkPoint * m_zoomFactor + m_origin; draw(); } // Renders a black line between the current anchor and the candidatePoint void Visualization::RenderHullCandidateLine(const sf::Vector2f & candidatePoint) { (*m_checkline)[0].position = m_currentAnchor->getPosition(); (*m_checkline)[1].position = candidatePoint * m_zoomFactor + m_origin; (*m_candidateLine)[0].position = m_currentAnchor->getPosition(); (*m_candidateLine)[1].position = candidatePoint * m_zoomFactor + m_origin; draw(); } bool Visualization::ShouldClose() { handleEvents(); return !m_renderWindow->isOpen(); } // Calculates a proper windowsize to fit all the points into the prefered window size. // The window size will not exceed the prefered window size. // The border percent determins the distance to the outer edge of the window sf::Vector2i Visualization::calculateWindowSize(const sf::Vector2f & preferedWindowSize, const sf::Vector2f & minCoord, const sf::Vector2f & maxCoord, const float& borderPercent) { //create a vector2 that defines the whole area sf::Vector2f extends = maxCoord - minCoord; //calculate the aspectratio float aspectRatio = extends.x / extends.y; if (aspectRatio > 1) //take the wide side to calculate the necessary zoom m_zoomFactor = (preferedWindowSize.x) / extends.x; else //take the tall side... m_zoomFactor = (preferedWindowSize.y) / extends.y; //calculate the actual windowsize sf::Vector2i windowSize(static_cast<int>(extends.x*m_zoomFactor), static_cast<int>(extends.y*m_zoomFactor)); //add a border float borderFactor = 1 + borderPercent; sf::Vector2f border = extends*m_zoomFactor / borderFactor - extends*m_zoomFactor; //zoom a away to make room for the border m_zoomFactor /= borderFactor; //create a vector that defines the origin m_origin = -minCoord * m_zoomFactor; //move the origin half of the border size away m_origin -= border*0.5f; return windowSize; } // Renders all the points and lines void Visualization::draw() const { if (m_renderWindow->isOpen()) { handleEvents(); m_renderWindow->clear(sf::Color::White); for(int i = 0; i < m_drawableVectors.size(); ++i) m_renderWindow->draw(*m_drawableVectors[i]); if (m_currentAnchor != nullptr) m_renderWindow->draw(*m_currentAnchor); if (m_hull != nullptr) m_renderWindow->draw(*m_hull); if (m_checkline != nullptr) m_renderWindow->draw(*m_checkline); if (m_candidateLine != nullptr) m_renderWindow->draw(*m_candidateLine); m_renderWindow->display(); if(m_millisecondPause > 0) std::this_thread::sleep_for(std::chrono::milliseconds(m_millisecondPause)); } } // Handles the SFML Events void Visualization::handleEvents() const { sf::Event event; while (m_renderWindow->pollEvent(event)) { if (event.type == sf::Event::Closed) m_renderWindow->close(); } }
7,546
2,729
#include <experimental/filesystem> #include "SCAlgorithm.hpp" #include "simulation.hpp" #include "timing.hpp" #include "commonFunctions.hpp" using fmt::format; using fmt::print; namespace fs = std::experimental::filesystem; fs::path getOutputPath() { return fs::path("..") / "output" / Model::getModelName(); } /** * @brief Simulates a trajectory with the SC controller. * * */ int main() { auto model = std::make_shared<Model>(); model->loadParameters(); scpp::SCAlgorithm solver(model); solver.initialize(); const double time_step = 0.05; const size_t max_steps = 100; trajectory_data_t td; Model::state_vector_v_t X_sim; Model::input_vector_v_t U_sim; Model::state_vector_t &x = model->p.x_init; double timer_run = tic(); size_t sim_step = 0; while (sim_step < max_steps) { print("\n{:*^{}}\n\n", format("<SIMULATION STEP {}>", sim_step), 60); const bool warm_start = sim_step > 0; solver.solve(warm_start); solver.getSolution(td); const Model::input_vector_t u0 = td.U.at(0); const bool first_order_hold = td.interpolatedInput(); const Model::input_vector_t u1 = scpp::interpolatedInput(td.U, time_step, td.t, first_order_hold); scpp::simulate(model, time_step, u0, u1, x); X_sim.push_back(x); U_sim.push_back(u0); bool reached_end = (x - model->p.x_final).norm() < 0.02 or td.t < 0.25; if (reached_end) { break; } sim_step++; } print("\n"); print("{:<{}}{:.2f}ms\n", fmt::format("Time, {} steps:", sim_step), 50, toc(timer_run)); const double freq = double(sim_step) / (0.001 * toc(timer_run)); print("{:<{}}{:.2f}Hz\n", "Average frequency:", 50, freq); print("\n"); // write solution to files double timer = tic(); fs::path outputPath = getOutputPath() / "SC_sim" / scpp::getTimeString() / std::to_string(0); if (not fs::exists(outputPath) and not fs::create_directories(outputPath)) { throw std::runtime_error("Could not create output directory!"); } const Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, ", ", "\n"); { std::ofstream f(outputPath / "X.txt"); for (auto &state : X_sim) { f << state.transpose().format(CSVFormat) << "\n"; } } { std::ofstream f(outputPath / "U.txt"); for (auto &input : U_sim) { f << input.transpose().format(CSVFormat) << "\n"; } } { std::ofstream f(outputPath / "t.txt"); f << sim_step * time_step; } print("{:<{}}{:.2f}ms\n", "Time, solution files:", 50, toc(timer)); }
2,813
1,015
#include "example.hpp" #include <tinyrefl/api.hpp> #include "example.hpp.tinyrefl" namespace my_namespace { std::ostream& operator<<(std::ostream& os, const MyClass::Enum value) { switch(value) { case MyClass::Enum::A: return os << "A"; case MyClass::Enum::B: return os << "B"; case MyClass::Enum::C: return os << "C"; case MyClass::Enum::D: return os << "D"; } return os << "WTF"; } bool operator==(const MyClass& lhs, const MyClass& rhs) { return tinyrefl::memberwise_equal(lhs, rhs); } } // namespace my_namespace
589
201
/*========================================================================= Program: Visualization Toolkit Module: vtkAngleRepresentation.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAngleRepresentation.h" #include "vtkHandleRepresentation.h" #include "vtkActor2D.h" #include "vtkPolyDataMapper2D.h" #include "vtkProperty2D.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkTextProperty.h" #include "vtkWindow.h" vtkCxxRevisionMacro(vtkAngleRepresentation, "1.7"); vtkCxxSetObjectMacro(vtkAngleRepresentation,HandleRepresentation,vtkHandleRepresentation); //---------------------------------------------------------------------- vtkAngleRepresentation::vtkAngleRepresentation() { this->HandleRepresentation = NULL; this->Point1Representation = NULL; this->CenterRepresentation = NULL; this->Point2Representation = NULL; this->Tolerance = 5; this->Placed = 0; this->Ray1Visibility = 1; this->Ray2Visibility = 1; this->ArcVisibility = 1; this->LabelFormat = new char[8]; sprintf(this->LabelFormat,"%s","%-#6.3g"); } //---------------------------------------------------------------------- vtkAngleRepresentation::~vtkAngleRepresentation() { if ( this->HandleRepresentation ) { this->HandleRepresentation->Delete(); } if ( this->Point1Representation ) { this->Point1Representation->Delete(); } if ( this->CenterRepresentation ) { this->CenterRepresentation->Delete(); } if ( this->Point2Representation ) { this->Point2Representation->Delete(); } if (this->LabelFormat) { delete [] this->LabelFormat; this->LabelFormat = NULL; } } //---------------------------------------------------------------------- void vtkAngleRepresentation::InstantiateHandleRepresentation() { if ( ! this->Point1Representation ) { this->Point1Representation = this->HandleRepresentation->NewInstance(); this->Point1Representation->ShallowCopy(this->HandleRepresentation); } if ( ! this->CenterRepresentation ) { this->CenterRepresentation = this->HandleRepresentation->NewInstance(); this->CenterRepresentation->ShallowCopy(this->HandleRepresentation); } if ( ! this->Point2Representation ) { this->Point2Representation = this->HandleRepresentation->NewInstance(); this->Point2Representation->ShallowCopy(this->HandleRepresentation); } } //---------------------------------------------------------------------- int vtkAngleRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { // See if we are near one of the end points or outside double pos1[3], pos2[3], center[3]; this->GetPoint1DisplayPosition(pos1); this->GetCenterDisplayPosition(center); this->GetPoint2DisplayPosition(pos2); double p1[3], p2[3], c[3], xyz[3]; xyz[0] = static_cast<double>(X); xyz[1] = static_cast<double>(Y); p1[0] = static_cast<double>(pos1[0]); p1[1] = static_cast<double>(pos1[1]); c[0] = static_cast<double>(center[0]); c[1] = static_cast<double>(center[1]); p2[0] = static_cast<double>(pos2[0]); p2[1] = static_cast<double>(pos2[1]); xyz[2] = p1[2] = p2[2] = c[2] = 0.0; double tol2 = this->Tolerance*this->Tolerance; if ( vtkMath::Distance2BetweenPoints(xyz,p1) <= tol2 ) { this->InteractionState = vtkAngleRepresentation::NearP1; } else if ( vtkMath::Distance2BetweenPoints(xyz,c) <= tol2 ) { this->InteractionState = vtkAngleRepresentation::NearCenter; } else if ( vtkMath::Distance2BetweenPoints(xyz,p2) <= tol2 ) { this->InteractionState = vtkAngleRepresentation::NearP2; } else { this->InteractionState = vtkAngleRepresentation::Outside; } return this->InteractionState; } //---------------------------------------------------------------------- void vtkAngleRepresentation::StartWidgetInteraction(double e[2]) { double pos[3]; pos[0] = e[0]; pos[1] = e[1]; pos[2] = 0.0; this->SetPoint1DisplayPosition(pos); this->SetCenterDisplayPosition(pos); this->SetPoint2DisplayPosition(pos); } //---------------------------------------------------------------------- void vtkAngleRepresentation::CenterWidgetInteraction(double e[2]) { double pos[3]; pos[0] = e[0]; pos[1] = e[1]; pos[2] = 0.0; this->SetCenterDisplayPosition(pos); this->SetPoint2DisplayPosition(pos); } //---------------------------------------------------------------------- void vtkAngleRepresentation::WidgetInteraction(double e[2]) { double pos[3]; pos[0] = e[0]; pos[1] = e[1]; pos[2] = 0.0; this->SetPoint2DisplayPosition(pos); } //---------------------------------------------------------------------- void vtkAngleRepresentation::BuildRepresentation() { // We don't worry about mtime 'cause the subclass deals with that // Make sure the handles are up to date this->Point1Representation->BuildRepresentation(); this->CenterRepresentation->BuildRepresentation(); this->Point2Representation->BuildRepresentation(); } //---------------------------------------------------------------------- void vtkAngleRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); os << indent << "Angle: " << this->GetAngle() << "\n"; os << indent << "Tolerance: " << this->Tolerance <<"\n"; os << indent << "Ray1 Visibility: " << (this->Ray1Visibility ? "On\n" : "Off\n"); os << indent << "Ray2 Visibility: " << (this->Ray2Visibility ? "On\n" : "Off\n"); os << indent << "Arc Visibility: " << (this->ArcVisibility ? "On\n" : "Off\n"); os << indent << "Handle Representation: " << this->HandleRepresentation << "\n"; os << indent << "Label Format: "; if ( this->LabelFormat ) { os << this->LabelFormat << "\n"; } else { os << "(none)\n"; } os << indent << "Point1 Representation: "; if ( this->Point1Representation ) { this->Point1Representation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } os << indent << "Center Representation: "; if ( this->CenterRepresentation ) { this->CenterRepresentation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } os << indent << "Point2 Representation: "; if ( this->Point2Representation ) { this->Point2Representation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } }
7,001
2,268
#include <iostream> #include <list> #include <fstream> using namespace std; class Stavka { private: char naziv[30]; int kolicina; public: void ispis(); Stavka unos(); void promjeni(string, list<Stavka> &); }; void Stavka::ispis() { cout << "\nNaziv proizvoda: " << naziv << "\nKolicina proizvoda: " << kolicina << endl; } Stavka Stavka::unos() { Stavka s; cin.ignore(); cout << "\nNaziv proizvoda: "; cin.getline(s.naziv, 30); cout << "Kolicina proizvoda: "; cin >> s.kolicina; return s; } void Stavka::promjeni(string naziv, list<Stavka> &stavke) { for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++) { if (naziv == it->naziv) { cin.ignore(); cout << "\nNovi naziv proizvoda: "; cin.getline(it->naziv, 32); cout << "Nova kolicina proizvoda: "; cin >> it->kolicina; break; } } } void spremi_datoteku(ofstream &outfile, list<Stavka> &stavke) { outfile.open("stavke.dat", ios::binary | ios::out | ios::app); if (!outfile) return; for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++) { outfile.write((char *)&*it, sizeof(*it)); } outfile.close(); cout << "\nSpremljeno u datoteku!" << endl; } list<Stavka> ucitaj_datoteku(ifstream &infile) { infile.open("stavke.dat", ios::binary | ios::in); if (!infile) return list<Stavka>(); list<Stavka> stavke; while (true) { Stavka s; infile.read((char *)&s, sizeof(s)); if (infile.eof()) break; stavke.push_back(s); } infile.close(); cout << "\nUcitano iz datoteke!" << endl; return stavke; } int main() { int izbor; list<Stavka> stavke; Stavka s; ofstream outfile; ifstream infile; do { cout << "1. Ispis svih stavki\n2. Dodavanje nove stavke\n3. Promjena stavke\n4. Spremanje liste u datoteku\n5. Upis liste iz datoteke\n6. Izlaz" << endl; cout << "\nVas izbor: "; cin >> izbor; switch (izbor) { case 1: { for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++) { it->ispis(); } break; } case 2: { stavke.push_back(s.unos()); break; } case 3: { string naziv; cout << "\nNaziv proizvoda za promjenu: "; cin >> naziv; s.promjeni(naziv, stavke); break; } case 4: { spremi_datoteku(outfile, stavke); break; } case 5: { stavke = ucitaj_datoteku(infile); break; } case 6: { cout << "\nIzlaz iz programa" << endl; break; } default: { cout << "\nKrivi unos!\n" << endl; break; } } cout << endl; } while (izbor != 6); return 0; }
3,152
1,156
//misaka and rin will carry me to cm #include <iostream> #include <cstdio> #include <cstring> #include <utility> #include <cassert> #include <algorithm> #include <vector> #include <array> #include <tuple> #define ll long long #define lb long double #define sz(vec) ((int)(vec.size())) #define all(x) x.begin(), x.end() const lb eps = 1e-9; const ll mod = 1e9 + 7, ll_max = 1e18; //const ll mod = (1 << (23)) * 119 +1; const int MX = 2e5 +10, int_max = 0x3f3f3f3f; using namespace std; int pad[MX], happy[MX], sad[MX], par[MX], b1[MX], b2[MX], sub[MX], wp[MX]; int cnt[MX][30]; vector<pair<int, int>> adj[MX]; void dfs(int u, int p){ par[u] = p; sub[u] = 1; for(auto &e : adj[u]){ if(e.first != p){ wp[e.first] = e.second; dfs(e.first, u); sub[u] += sub[e.first]; } } } void gans(int u, int p){ int tsad = 0; for(auto &e : adj[u]){ int v = e.first; if(v == p) continue; gans(v, u); tsad += (sad[v] > 0); } //int ans = 0; for(auto& e : adj[u]){ int v = e.first, w = e.second; if(v == p) continue; //under what conditions do we ignore the subtree of v? //tsad == 1 && sad[v] == 0 //b1, b2 are defined and v != b1, v != b2 //tsad > 1 sad[u] += sad[v]; if(tsad > 0 && sad[v] == 0){ //someone else is sad }else if(b2[u] != 0 && v != b1[u] && v != b2[u]){ //u itself just screwed v over }else{ happy[u] += happy[v]; } } if(tsad == 0 && b2[u] == 0) happy[u]++; //counting node u if(tsad > 1) happy[u] = 0; //sad[u] += (b2[u] > 0); } void cl(int n){ for(int i = 0; i<=n; i++){ adj[i].clear(); b1[i] = b2[i] = par[i] = happy[i] = sad[i] = sub[i] = wp[i] = 0; for(int j = 0; j<26; j++) cnt[i][j] = 0; } } int solve(){ //yes int n; cin >> n; cl(n); for(int i = 0; i<n-1; i++){ int a, b; char c; cin >> a >> b >> c; int d = c - 'a'; adj[a].push_back(make_pair(b, d)); b[adj].push_back(make_pair(a, d)); cnt[a][d]++; cnt[b][d]++; } dfs(1, 0); for(int u = 1; u<=n; u++){ int th = 0, tw = 0; for(int c = 0; c<26; c++){ th += (cnt[u][c] >= 3); tw += (cnt[u][c] >= 2); } if(th >= 1) return 0; //everyone is sad if(tw >= 2) return 0; } //if(tw >=2) return 0; for(int u = 1; u<=n; u++){ for(int c = 0; c<26; c++){ int t = cnt[u][c]; if(t >=2){ //cout << u << "\n"; for(auto& e : adj[u]){ if(e.second == c){ if(b1[u]) b2[u] = e.first; else b1[u] = e.first; } } if(!(b1[u] == par[u] || b2[u] == par[u])) sad[u]++; } } } //for(int i = 1; i<=n; i++){ //cout << i << " " << sad[i] << " " << b1[i] << " " << b2[i] << "\n"; //} gans(1, 0); //for(int i = 1; i<=n; i++){ //cout << i << " " << sad[i] << " " << happy[i] << "\n"; //} return happy[1]; } int main(){ cin.tie(0) -> sync_with_stdio(0); int T; cin >> T; while(T--){ cout << solve() << "\n"; } return 0; }
2,841
1,551