text
stringlengths
500
20k
source
stringclasses
27 values
lang
stringclasses
3 values
char_count
int64
500
20k
word_count
int64
4
19.8k
// This file is part of the LITIV framework; visit the original repository at // https://github.com/plstcharles/litiv for more information. // // Copyright 2016 Pierre-Luc St-Charles; pierre-luc.st-charles<at>polymtl.ca // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <opencv2/imgcodecs.hpp> #include "litiv/utils.hpp" #include "litiv/datasets.hpp" #define BORDER_EXPAND_TYPE cv::BORDER_REPLICATE namespace lv { static const DatasetList Dataset_CosegmTests = DatasetList(Dataset_Custom+1337); // cheat; might cause problems if exposed in multiple external/custom specializations struct ICosegmTestDataset { virtual bool isEvaluatingDisparities() const = 0; virtual bool isLoadingFrameSubset() const = 0; virtual int isLoadingInputMasks() const = 0; }; template<DatasetTaskList eDatasetTask, lv::ParallelAlgoType eEvalImpl> struct Dataset_<eDatasetTask,Dataset_CosegmTests,eEvalImpl> : public ICosegmTestDataset, public IDataset_<eDatasetTask,DatasetSource_VideoArray,Dataset_CosegmTests,DatasetEval_BinaryClassifierArray,eEvalImpl> { protected: Dataset_( const std::string& sOutputDirName, ///< output directory name for debug logs, evaluation reports and results archiving bool bSaveOutput=false, ///< defines whether results should be archived or not bool bUseEvaluator=true, ///< defines whether results should be fully evaluated, or simply acknowledged bool bEvalDisparities=false, ///< defines whether we should evaluate fg/bg segmentation or stereo disparities bool bLoadFrameSubset=false, ///< defines whether only a subset of the dataset's frames will be loaded or not int nLoadInputMasks=0, ///< defines whether the input stream should be interlaced with fg/bg masks (0=no interlacing masks, -1=all gt masks, 1=all approx masks, (1<<(X+1))=gt mask for stream 'X') double dScaleFactor=1.0 ///< defines the scale factor to use to resize/rescale read packets ) : IDataset_<eDatasetTask,DatasetSource_VideoArray,Dataset_CosegmTests,DatasetEval_BinaryClassifierArray,eEvalImpl>( "cosegm_tests", lv::datasets::getRootPath()+"litiv/cosegm_tests/", DataHandler::createOutputDir(lv::datasets::getRootPath()+"litiv/cosegm_tests/results/",sOutputDirName), std::vector<std::string>{"test01"}, //std::vector<std::string>{"art"}, //std::vector<std::string>{"art_mini"}, //std::vector<std::string>{"noiseless"}, //std::vector<std::string>{"noiseless_mini"}, std::vector<std::string>(), bSaveOutput, bUseEvaluator, false, dScaleFactor ), m_bEvalDisparities(bEvalDisparities), m_bLoadFrameSubset(bLoadFrameSubset), m_nLoadInputMasks(nLoadInputMasks) {} virtual bool isEvaluatingDisparities() const override final {return m_bEvalDisparities;} virtual bool isLoadingFrameSubset() const override {return m_bLoadFrameSubset;} virtual int isLoadingInputMasks() const override final {return m_nLoadInputMasks;} protected: const bool m_bEvalDisparities; const bool m_bLoadFrameSubset; const int m_nLoadInputMasks; }; template<DatasetTaskList eDatasetTask> struct DataGroupHandler_<eDatasetTask,DatasetSource_VideoArray,Dataset_CosegmTests> : public DataGroupHandler { protected: virtual void parseData() override { this->m_vpBatches.clear(); this->m_bIsBare = true; if(!lv::string_contains_token(this->getName(),this->getSkipTokens())) this->m_vpBatches.push_back(this->createWorkBatch(this->getName(),this->getRelativePath())); } }; template<DatasetTaskList eDatasetTask> struct DataProducer_<eDatasetTask,DatasetSource_VideoArray,Dataset_CosegmTests> : public IDataProducerWrapper_<eDatasetTask,DatasetSource_VideoArray,Dataset_CosegmTests> { virtual size_t getInputStreamCount() const override final { return size_t(2*(this->isLoadingInputMasks()?2:1)); // 2x input images (+ 2x approx fg masks) } virtual size_t getGTStreamCount() const override final { return 2; // 2x fg masks or disp maps } bool isEvaluatingDisparities() const { return dynamic_cast<const ICosegmTestDataset&>(*this->getRoot()).isEvaluatingDisparities(); } bool isLoadingFrameSubset() const { return dynamic_cast<const ICosegmTestDataset&>(*this->getRoot()).isLoadingFrameSubset(); } int isLoadingInputMasks() const { return dynamic_cast<const ICosegmTestDataset&>(*this->getRoot()).isLoadingInputMasks(); } std::string getFeaturesDirName() const { return this->m_sFeaturesDirName; } void setFeaturesDirName(const std::string& sDirName) { this->m_sFeaturesDirName = sDirName; lv::createDirIfNotExist(this->getFeaturesPath()+sDirName); } virtual std::string getFeaturesName(size_t nPacketIdx) const override final { std::array<char,32> acBuffer; snprintf(acBuffer.data(),acBuffer.size(),nPacketIdx<size_t(1e7)?"%06zu":"%09zu",nPacketIdx); return lv::addDirSlashIfMissing(this->m_sFeaturesDirName)+std::string(acBuffer.data()); } size_t getMinDisparity() const { return this->m_nMinDisp; } size_t getMaxDisparity() const { return this->m_nMaxDisp; } protected: virtual void parseData() override final { lvDbgExceptionWatch; const int nLoadInputMasks = this->isLoadingInputMasks(); const bool bLoadFrameSubset = this->isLoadingFrameSubset(); const bool bUseInterlacedMasks = nLoadInputMasks!=0; const bool bUseApproxMask0 = (nLoadInputMasks&2)==0; const bool bUseApproxMask1 = (nLoadInputMasks&4)==0; const size_t nInputStreamCount = this->getInputStreamCount(); const size_t nGTStreamCount = this->getGTStreamCount(); constexpr size_t nInputStreamIdx0 = 0; const size_t nInputStreamIdx1 = bUseInterlacedMasks?2:1; constexpr size_t nInputMaskStreamIdx0 = 1; constexpr size_t nInputMaskStreamIdx1 = 3; this->m_vvsInputPaths.clear(); this->m_vvsGTPaths.clear(); this->m_vInputInfos.resize(getInputStreamCount()); this->m_vGTInfos.resize(getGTStreamCount()); const double dScale = this->getScaleFactor(); int nCurrIdx = 0; while(true) { std::vector<std::string> vCurrInputPaths(nInputStreamCount); vCurrInputPaths[nInputStreamIdx0] = cv::format("%simg%05da.png",this->getDataPath().c_str(),nCurrIdx); vCurrInputPaths[nInputStreamIdx1] = cv::format("%simg%05db.png",this->getDataPath().c_str(),nCurrIdx); cv::Mat oInput0 = cv::imread(vCurrInputPaths[nInputStreamIdx0],cv::IMREAD_UNCHANGED); cv::Mat oInput1 = cv::imread(vCurrInputPaths[nInputStreamIdx1],cv::IMREAD_UNCHANGED); if(oInput0.empty() || oInput1.empty()) break; lvAssert(oInput0.size()==oInput1.size()); cv::Mat oMask0,oMask1; if(bUseInterlacedMasks) { vCurrInputPaths[nInputMaskStreamIdx0] = cv::format(((!bUseApproxMask0)?"%sgtmask%05da.png":"%smask%05da.png"),this->getDataPath().c_str(),nCurrIdx); vCurrInputPaths[nInputMaskStreamIdx1] = cv::format(((!bUseApproxMask1)?"%sgtmask%05db.png":"%smask%05db.png"),this->getDataPath().c_str(),nCurrIdx); oMask0 = cv::imread(vCurrInputPaths[nInputMaskStreamIdx0],cv::IMREAD_GRAYSCALE); oMask1 = cv::imread(vCurrInputPaths[nInputMaskStreamIdx1],cv::IMREAD_GRAYSCALE); lvAssert(!oMask0.empty() && !oMask1.empty()); lvAssert(oMask0.size()==oMask1.size()); lvAssert(oInput0.size()==oMask0.size()); } /*const std::vector<std::string> in = { cv::format("%simg%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%simg%05db.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smask%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smask%05db.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%sgtmask%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%sgtmask%05db.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%sgtdisp%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%sgtdisp%05db.png",this->getDataPath().c_str(),nCurrIdx), }; const std::vector<std::string> out = { cv::format("%smini/img%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smini/img%05db.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smini/mask%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smini/mask%05db.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smini/gtmask%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smini/gtmask%05db.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smini/gtdisp%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format("%smini/gtdisp%05db.png",this->getDataPath().c_str(),nCurrIdx), }; cv::Rect croproi(13,132,340,200); for(size_t i=0; i<in.size(); ++i) { cv::Mat img = cv::imread(in[i],cv::IMREAD_UNCHANGED); if(!img.empty()) cv::imwrite(out[i],img(croproi)); }*/ //cv::imwrite(cv::format("%stmp/img%05da.png",this->getDataPath().c_str(),nCurrIdx),oInput0); //cv::imwrite(cv::format(((this->isUsingGTMaskAsInput()&2)?"%stmp/gtmask%05da.png":"%stmp/mask%05da.png"),this->getDataPath().c_str(),nCurrIdx),oMask0); //cv::imwrite(cv::format("%stmp/img%05db.png",this->getDataPath().c_str(),nCurrIdx),oInput1); //cv::imwrite(cv::format(((this->isUsingGTMaskAsInput()&1)?"%stmp/gtmask%05db.png":"%stmp/mask%05db.png"),this->getDataPath().c_str(),nCurrIdx),oMask1); this->m_vvsInputPaths.push_back(vCurrInputPaths); if(this->m_vvsInputPaths.size()==size_t(1)) { this->m_vInputInfos[nInputStreamIdx0] = lv::MatInfo(oInput0); this->m_vInputInfos[nInputStreamIdx1] = lv::MatInfo(oInput1); if(bUseInterlacedMasks) { this->m_vInputInfos[nInputMaskStreamIdx0] = lv::MatInfo(oMask0); this->m_vInputInfos[nInputMaskStreamIdx1] = lv::MatInfo(oMask1); } } else { lvAssert(lv::MatInfo(oInput0)==this->m_vInputInfos[nInputStreamIdx0]); lvAssert(lv::MatInfo(oInput1)==this->m_vInputInfos[nInputStreamIdx1]); if(bUseInterlacedMasks) { lvAssert(lv::MatInfo(oMask0)==this->m_vInputInfos[nInputMaskStreamIdx0]); lvAssert(lv::MatInfo(oMask1)==this->m_vInputInfos[nInputMaskStreamIdx1]); } } if(this->isEvaluating()) { const std::vector<std::string> vCurrGTPaths = { cv::format(this->isEvaluatingDisparities()?"%sgtdisp%05da.png":"%sgtmask%05da.png",this->getDataPath().c_str(),nCurrIdx), cv::format(this->isEvaluatingDisparities()?"%sgtdisp%05db.png":"%sgtmask%05db.png",this->getDataPath().c_str(),nCurrIdx), }; cv::Mat oGT0 = cv::imread(vCurrGTPaths[0],cv::IMREAD_GRAYSCALE); cv::Mat oGT1 = cv::imread(vCurrGTPaths[1],cv::IMREAD_GRAYSCALE); lvAssert(!oGT0.empty() && !oGT1.empty() && oGT0.size()==oGT1.size() && oInput0.size()==oGT0.size()); this->m_vvsGTPaths.push_back(vCurrGTPaths); if(this->m_vvsGTPaths.size()==size_t(1)) { this->m_vGTInfos[0] = lv::MatInfo(oGT0); this->m_vGTInfos[1] = lv::MatInfo(oGT1); } else { lvAssert(lv::MatInfo(oGT0)==this->m_vGTInfos[0]); lvAssert(lv::MatInfo(oGT1)==this->m_vGTInfos[1]); } this->m_mGTIndexLUT[nCurrIdx] = nCurrIdx; } ++nCurrIdx; } lvAssert(this->m_vvsInputPaths.size()>0 && this->m_vvsInputPaths[0].size()>0); const cv::Size oOrigSize = this->m_vInputInfos[0].size(); lvAssert(oOrigSize.area()>0); this->m_vInputROIs.resize(nInputStreamCount); if(this->isEvaluating()) this->m_vGTROIs.resize(nGTStreamCount); std::array<cv::Mat,2> aROIs = { cv::imread(this->getDataPath()+"roi0.png",cv::IMREAD_GRAYSCALE), cv::imread(this->getDataPath()+"roi1.png",cv::IMREAD_GRAYSCALE) }; for(size_t a=0; a<2; ++a) { if(aROIs[a].empty()) aROIs[a] = cv::Mat(oOrigSize,CV_8UC1,cv::Scalar_<uchar>(255)); else lvAssert(aROIs[a].size()==oOrigSize); if(dScale!=1.0) cv::resize(aROIs[a],aROIs[a],cv::Size(),dScale,dScale,cv::INTER_NEAREST); if(bUseInterlacedMasks) { this->m_vInputROIs[2*a] = aROIs[a].clone(); this->m_vInputROIs[2*a+1] = aROIs[a].clone(); } else this->m_vInputROIs[a] = aROIs[a].clone(); if(this->isEvaluating()) this->m_vGTROIs[a] = aROIs[a].clone(); } this->m_vInputInfos[nInputStreamIdx0] = lv::MatInfo(aROIs[0].size(),this->m_vInputInfos[nInputStreamIdx0].type); this->m_vInputInfos[nInputStreamIdx1] = lv::MatInfo(aROIs[1].size(),this->m_vInputInfos[nInputStreamIdx1].type); if(bUseInterlacedMasks) { this->m_vInputInfos[nInputMaskStreamIdx0] = lv::MatInfo(aROIs[0].size(),this->m_vInputInfos[nInputMaskStreamIdx0].type); this->m_vInputInfos[nInputMaskStreamIdx1] = lv::MatInfo(aROIs[1].size(),this->m_vInputInfos[nInputMaskStreamIdx1].type); } if(this->isEvaluating()) { this->m_vGTInfos[0] = lv::MatInfo(aROIs[0].size(),this->m_vGTInfos[0].type); this->m_vGTInfos[1] = lv::MatInfo(aROIs[1].size(),this->m_vGTInfos[1].type); } this->m_nMinDisp = size_t(0); this->m_nMaxDisp = size_t(100); std::ifstream oDispRangeFile(this->getDataPath()+"drange.txt"); if(oDispRangeFile.is_open() && !oDispRangeFile.eof()) { oDispRangeFile >> this->m_nMinDisp; if(!oDispRangeFile.eof()) oDispRangeFile >> this->m_nMaxDisp; } this->m_nMinDisp *= dScale; this->m_nMaxDisp *= dScale; lvAssert(this->m_nMaxDisp>this->m_nMinDisp); } virtual std::vector<cv::Mat> getRawGTArray(size_t nPacketIdx) override final { lvAssert(this->isEvaluating()); std::vector<cv::Mat> vGTs = IDataProducer_<DatasetSource_VideoArray>::getRawGTArray(nPacketIdx); for(size_t nStreamIdx=0; nStreamIdx<vGTs.size(); ++nStreamIdx) { if(!vGTs[nStreamIdx].empty()) { if(this->isEvaluatingDisparities() && this->getScaleFactor()!=0) vGTs[nStreamIdx] *= this->getScaleFactor(); } } return vGTs; } size_t m_nMinDisp,m_nMaxDisp; std::string m_sFeaturesDirName; }; } // namespace lv
c++
code
17,234
3,534
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkColor.h" #include "SkColorMatrixFilter.h" #include "SkPaint.h" #include <stdlib.h> static inline void assert_color(skiatest::Reporter* reporter, SkColor expected, SkColor actual, int tolerance) { REPORTER_ASSERT(reporter, abs((int)(SkColorGetA(expected) - SkColorGetA(actual))) <= tolerance); REPORTER_ASSERT(reporter, abs((int)(SkColorGetR(expected) - SkColorGetR(actual))) <= tolerance); REPORTER_ASSERT(reporter, abs((int)(SkColorGetG(expected) - SkColorGetG(actual))) <= tolerance); REPORTER_ASSERT(reporter, abs((int)(SkColorGetB(expected) - SkColorGetB(actual))) <= tolerance); } static inline void assert_color(skiatest::Reporter* reporter, SkColor expected, SkColor actual) { const int TOLERANCE = 1; assert_color(reporter, expected, actual, TOLERANCE); } /** * This test case is a mirror of the Android CTS tests for MatrixColorFilter * found in the android.graphics.ColorMatrixColorFilterTest class. */ static inline void test_colorMatrixCTS(skiatest::Reporter* reporter) { SkBitmap bitmap; bitmap.allocN32Pixels(1,1); SkCanvas canvas(bitmap); SkPaint paint; SkScalar blueToCyan[20] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }; paint.setColorFilter(SkColorFilter::MakeMatrixFilterRowMajor255(blueToCyan)); paint.setColor(SK_ColorBLUE); canvas.drawPoint(0, 0, paint); assert_color(reporter, SK_ColorCYAN, bitmap.getColor(0, 0)); paint.setColor(SK_ColorGREEN); canvas.drawPoint(0, 0, paint); assert_color(reporter, SK_ColorGREEN, bitmap.getColor(0, 0)); paint.setColor(SK_ColorRED); canvas.drawPoint(0, 0, paint); assert_color(reporter, SK_ColorRED, bitmap.getColor(0, 0)); // color components are clipped, not scaled paint.setColor(SK_ColorMAGENTA); canvas.drawPoint(0, 0, paint); assert_color(reporter, SK_ColorWHITE, bitmap.getColor(0, 0)); SkScalar transparentRedAddBlue[20] = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 64.0f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f }; paint.setColorFilter(SkColorFilter::MakeMatrixFilterRowMajor255(transparentRedAddBlue)); bitmap.eraseColor(SK_ColorTRANSPARENT); paint.setColor(SK_ColorRED); canvas.drawPoint(0, 0, paint); assert_color(reporter, SkColorSetARGB(128, 255, 0, 64), bitmap.getColor(0, 0), 2); paint.setColor(SK_ColorCYAN); canvas.drawPoint(0, 0, paint); // blue gets clipped assert_color(reporter, SK_ColorCYAN, bitmap.getColor(0, 0)); // change array to filter out green REPORTER_ASSERT(reporter, 1.0f == transparentRedAddBlue[6]); transparentRedAddBlue[6] = 0.0f; // check that changing the array has no effect canvas.drawPoint(0, 0, paint); assert_color(reporter, SK_ColorCYAN, bitmap.getColor(0, 0)); // create a new filter with the changed matrix paint.setColorFilter(SkColorFilter::MakeMatrixFilterRowMajor255(transparentRedAddBlue)); canvas.drawPoint(0, 0, paint); assert_color(reporter, SK_ColorBLUE, bitmap.getColor(0, 0)); } DEF_TEST(ColorMatrix, reporter) { test_colorMatrixCTS(reporter); }
c++
code
3,532
773
#include "net_mock.h" #include <gflags/gflags.h> #include <ncode/free_list.h> #include <ncode/logging.h> #include <ncode/map_util.h> #include <limits> #include <numeric> #include <set> #include <tuple> #include "common.h" #include "metrics/metrics.h" #include "routing_system.h" namespace ctr { DEFINE_bool(mean_hints, false, "If true each aggregate mean level will be set to the ideal one " "for the next history."); DEFINE_bool( triggered_optimization, true, "If true will convolve aggregates to trigger optimization if needed at the " "end of each period."); static auto* link_utilization_metric = nc::metrics::DefaultMetricManager() -> GetUnsafeMetric<double, std::string, std::string>( "link_utilization", "Records per-link utilization (bytes per bin)", "Link source", "Link destination"); static auto* queue_size_metric = nc::metrics::DefaultMetricManager() -> GetUnsafeMetric<double, std::string, std::string>( "queue_size", "Records per-link queue size (in bytes)", "Link source", "Link destination"); static auto* link_rate_metric = nc::metrics::DefaultMetricManager() -> GetUnsafeMetric<double, std::string, std::string>( "link_rate_Mbps", "Records per-link rate, only contains one value", "Link source", "Link destination"); static auto* bin_size_metric = nc::metrics::DefaultMetricManager() -> GetUnsafeMetric<uint64_t>( "bin_size_ms", "Records how long (in milliseconds) is each bin"); static auto* route_add_metric = nc::metrics::DefaultMetricManager() -> GetUnsafeMetric<uint64_t>( "route_add", "Records how many routes need to be added per optimization"); static auto* route_update_metric = nc::metrics::DefaultMetricManager() -> GetUnsafeMetric<uint64_t>( "route_update", "Records how many routes need to be updated per optimization"); static auto* route_remove_metric = nc::metrics::DefaultMetricManager() -> GetUnsafeMetric<uint64_t>( "route_remove", "Records how many routes need to be removed per optimization"); static auto* prop_delay_per_aggregate = nc::metrics::DefaultMetricManager() -> GetUnsafeMetric<nc::DiscreteDistribution<uint64_t>>( "prop_delay_per_packet", "Records propagation delay per packet"); void MockSimDevice::HandleStateUpdate( const nc::htsim::SSCPAddOrUpdate& update) { nc::htsim::MatchRule* rule = update.MutableRule(); std::vector<const nc::htsim::MatchRuleAction*> rule_actions = rule->actions(); const nc::htsim::MatchRuleKey& key = rule->key(); AggregateState* state = nc::FindOrNull(states_, key); if (state == nullptr) { return; } state->rule = rule; double total_weight = 0; for (const nc::htsim::MatchRuleAction* action : rule_actions) { total_weight += action->weight(); } std::vector<double> fractions; for (const nc::htsim::MatchRuleAction* action : rule_actions) { double fraction = action->weight() / total_weight; fractions.emplace_back(fraction); } std::vector<std::unique_ptr<BinSequence>> sub_sequences; sub_sequences = state->initial_bin_sequence->PreciseSplitOrDie(fractions); CHECK(sub_sequences.size() == fractions.size()); // Each action in the rule is a separate path. std::set<nc::htsim::PacketTag> tags_in_actions; for (size_t i = 0; i < rule_actions.size(); ++i) { const nc::htsim::MatchRuleAction* action = rule_actions[i]; nc::htsim::PacketTag tag = action->tag(); CHECK(tag.IsNotZero()); tags_in_actions.emplace(tag); PathState& path_state = state->paths[tag]; path_state.bin_sequence = std::move(sub_sequences[i]); path_state.bins.clear(); } // There should be no paths removed. for (const auto& tag_and_path_state : state->paths) { CHECK(nc::ContainsKey(tags_in_actions, tag_and_path_state.first)); } } static nc::htsim::ActionStats* FindStatsForTagOrDie( std::vector<nc::htsim::ActionStats>* stats, nc::htsim::PacketTag tag) { for (auto& action_stats : *stats) { if (action_stats.tag == tag) { return &action_stats; } } LOG(FATAL) << "Could not find action stats"; return nullptr; } void MockSimDevice::PostProcessStats(const nc::htsim::SSCPStatsRequest& request, nc::htsim::SSCPStatsReply* reply) { for (auto& key_and_state : states_) { const nc::htsim::MatchRuleKey& key = key_and_state.first; AggregateState& state = key_and_state.second; std::vector<nc::htsim::ActionStats>& stats_in_reply = nc::FindOrDie(reply->stats_mutable(), key); for (auto& tag_and_path : state.paths) { PathState& path_state = tag_and_path.second; if (request.include_flow_counts()) { nc::htsim::ActionStats* action_stats = FindStatsForTagOrDie(&stats_in_reply, tag_and_path.first); action_stats->flow_count = GetFlowCountFromSyns(path_state.syns.GetValues()); } } } } void MockSimDevice::HandlePacket(nc::htsim::PacketPtr pkt) { using namespace nc::htsim; if (pkt->size_bytes() == 0) { // The packet is an SSCP message. uint8_t type = pkt->five_tuple().ip_proto().Raw(); if (type == SSCPAddOrUpdate::kSSCPAddOrUpdateType) { SSCPAddOrUpdate* add_or_update_message = static_cast<SSCPAddOrUpdate*>(pkt.get()); HandleStateUpdate(*add_or_update_message); } } Device::HandlePacket(std::move(pkt)); } std::chrono::microseconds MockSimNetwork::GetBinSize() { // Will assume that all bin sizes are the same. for (const MockSimDevice* device : devices_) { if (device->states_.empty()) { continue; } const MockSimDevice::AggregateState& aggregate_state = device->states_.begin()->second; return aggregate_state.initial_bin_sequence->bin_size(); } LOG(FATAL) << "No devices with aggregate state"; return std::chrono::microseconds(0); } void MockSimNetwork::PrefetchBins(MockSimDevice::PathState* path_state) { CHECK(path_state->bin_sequence); const BinSequence& bin_sequence = *path_state->bin_sequence; std::unique_ptr<BinSequence> to_end = bin_sequence.CutFromStart(last_bin_count_ + kPrefetchSize); std::unique_ptr<BinSequence> period_sequence = to_end->Offset(last_bin_count_); std::vector<TrimmedPcapDataTraceBin> bins = period_sequence->AccumulateBins(GetBinSize(), &bin_cache_); CHECK(bins.size() == kPrefetchSize) << bins.size() << " vs " << kPrefetchSize; path_state->bins = std::move(bins); path_state->bins_cached_from = last_bin_count_; } void MockSimNetwork::AdvanceTimeToNextBin() { using namespace std::chrono; for (MockSimDevice* device : devices_) { for (auto& key_and_state : device->states_) { MockSimDevice::AggregateState& aggregate_state = key_and_state.second; size_t i = -1; for (auto& tag_and_path_state : aggregate_state.paths) { MockSimDevice::PathState& path_state = tag_and_path_state.second; if (!path_state.bin_sequence) { ++i; continue; } const std::vector<TrimmedPcapDataTraceBin>& bins = path_state.bins; size_t bin_index = last_bin_count_ + 1 - path_state.bins_cached_from; if (bin_index >= bins.size()) { PrefetchBins(&path_state); bin_index = last_bin_count_ + 1 - path_state.bins_cached_from; CHECK(bin_index < bins.size()); } const TrimmedPcapDataTraceBin& bin = bins[bin_index]; if (bin.bytes == 0) { continue; } path_state.syns.AddValue(bin.flows_enter); nc::htsim::PacketPtr pkt = GetDummyPacket(bin.bytes); const nc::htsim::MatchRuleAction* action = aggregate_state.rule->ExplicitChooseOrDie(*pkt, ++i); CHECK(action->weight() > 0) << "Action with zero weight chosen " << action->ToString() << " rule " << action->parent_rule()->ToString(); nc::htsim::Port* port = device->FindOrCreatePort(default_enter_port_); device->HandlePacketWithAction(port, std::move(pkt), action); } } } ++last_bin_count_; } nc::htsim::PacketPtr MockSimNetwork::GetDummyPacket(uint32_t size) { nc::net::FiveTuple five_tuple( nc::net::IPAddress(9919), nc::net::IPAddress(9929), nc::net::kProtoUDP, nc::net::AccessLayerPort(9919), nc::net::AccessLayerPort(9929)); return nc::GetFreeList<nc::htsim::UDPPacket>().New( five_tuple, size, event_queue_->CurrentTime()); } uint64_t GetFlowCountFromSyns(const std::vector<uint64_t>& syns) { uint64_t total = std::accumulate(syns.begin(), syns.end(), 0ul); if (total == 0) { return 1ul; } return std::max(static_cast<uint64_t>(1), total / syns.size()); } NetMock::NetMock(std::map<AggregateId, BinSequence>&& initial_sequences, std::chrono::milliseconds period_duration, std::chrono::milliseconds history_bin_size, std::chrono::milliseconds total_duration, size_t periods_in_history, RoutingSystem* routing_system) : periods_in_history_(periods_in_history), history_bin_size_(history_bin_size), initial_sequences_(std::move(initial_sequences)), routing_system_(routing_system), graph_(routing_system_->graph()) { CHECK(!initial_sequences_.empty()); size_t min_bin_count = std::numeric_limits<size_t>::max(); std::chrono::milliseconds bin_size = std::chrono::milliseconds::zero(); for (const auto& id_and_bin_sequence : initial_sequences_) { const BinSequence& bin_sequence = id_and_bin_sequence.second; if (bin_size == std::chrono::milliseconds::zero()) { bin_size = std::chrono::duration_cast<std::chrono::milliseconds>( bin_sequence.bin_size()); } else { CHECK(bin_size == bin_sequence.bin_size()); } size_t count = bin_sequence.bin_count(); min_bin_count = std::min(min_bin_count, count); } period_duration_bins_ = period_duration.count() / bin_size.count(); bins_in_history_ = period_duration_bins_ * periods_in_history; CHECK(period_duration_bins_ > 0); period_count_ = min_bin_count / period_duration_bins_; period_count_ = std::min( period_count_, static_cast<size_t>(total_duration.count() / period_duration.count())); bin_size_metric->GetHandle()->AddValue(bin_size.count()); for (nc::net::GraphLinkIndex link : graph_->AllLinks()) { const nc::net::GraphLink* link_ptr = graph_->GetLink(link); link_rate_metric->GetHandle(link_ptr->src_id(), link_ptr->dst_id()) ->AddValue(link_ptr->bandwidth().Mbps()); } } // Generates the input to the system. std::map<AggregateId, AggregateHistory> NetMock::GenerateInput( const std::map<AggregateId, BinSequence>& period_sequences, PcapDataBinCache* cache) const { using namespace std::chrono; std::map<AggregateId, AggregateHistory> input; for (const auto& aggregate_and_bins : period_sequences) { const AggregateId& aggregate = aggregate_and_bins.first; const BinSequence& bins = aggregate_and_bins.second; input.emplace(std::piecewise_construct, std::forward_as_tuple(aggregate), std::forward_as_tuple( bins.GenerateHistory(history_bin_size_, 1000, cache))); } return input; } static constexpr double kAggregateWeight = 1000; nc::net::GraphLinkMap<std::vector<std::pair<double, double>>> NetMock::CheckOutput(const std::map<AggregateId, BinSequence>& period_sequences, const RoutingConfiguration& configuration, PcapDataBinCache* cache) { using namespace std::chrono; nc::net::GraphLinkMap<std::unique_ptr<BinSequence>> link_to_bins; // First need to figure out which paths cross each link. Will also build a // map from paths to aggregates and path indices. for (const auto& aggregate_and_routes : configuration.routes()) { const AggregateId& aggregate = aggregate_and_routes.first; const std::vector<RouteAndFraction>& routes = aggregate_and_routes.second; std::vector<double> fractions; for (const auto& route_and_fraction : routes) { fractions.emplace_back(route_and_fraction.second); } // For each of the aggregate's paths, the bins that go on that path. std::vector<std::unique_ptr<BinSequence>> aggregate_split = nc::FindOrDieNoPrint(period_sequences, aggregate) .PreciseSplitOrDie(fractions); for (size_t i = 0; i < routes.size(); ++i) { const nc::net::Walk* path = routes[i].first; double fraction = fractions[i]; uint64_t delay_ms = duration_cast<milliseconds>(path->delay()).count(); size_t path_weight = kAggregateWeight * fraction; delays_seen_.Add(delay_ms, path_weight); for (nc::net::GraphLinkIndex link : path->links()) { std::unique_ptr<BinSequence>& bin_sequence_ptr = link_to_bins[link]; if (!bin_sequence_ptr) { bin_sequence_ptr = aggregate_split[i]->Duplicate(); } else { bin_sequence_ptr->Combine(*aggregate_split[i]); } } } } nc::net::GraphLinkMap<std::vector<std::pair<double, double>>> out; for (const auto& link_and_bins : link_to_bins) { nc::net::GraphLinkIndex link = link_and_bins.first; nc::net::Bandwidth rate = graph_->GetLink(link)->bandwidth(); out[link] = (*link_and_bins.second)->Residuals(rate, cache); } return out; } std::map<AggregateId, BinSequence> NetMock::GetNthPeriod( size_t n, size_t bin_count) const { size_t period_start_bin = n * period_duration_bins_; size_t period_end_bin = period_start_bin + bin_count; std::map<AggregateId, BinSequence> out; for (const auto& aggregate_and_bins : initial_sequences_) { const AggregateId& aggregate = aggregate_and_bins.first; const BinSequence& bins = aggregate_and_bins.second; std::unique_ptr<BinSequence> to_end = bins.CutFromStart(period_end_bin); std::unique_ptr<BinSequence> period_sequence = to_end->Offset(period_start_bin); out.emplace(std::piecewise_construct, std::forward_as_tuple(aggregate), std::forward_as_tuple(period_sequence->traces())); } return out; } std::unique_ptr<RoutingConfiguration> NetMock::InitialOutput( PcapDataBinCache* cache) const { std::map<AggregateId, BinSequence> zero_period = GetNthPeriod(0, bins_in_history_); std::map<AggregateId, AggregateHistory> input = GenerateInput(zero_period, cache); return routing_system_->Update(input).routing; } static size_t CheckSameSize(const nc::net::GraphLinkMap< std::vector<std::pair<double, double>>>& values) { size_t i = 0; for (const auto& link_and_values : values) { const auto& v = *link_and_values.second; CHECK(v.size() > 0); if (i == 0) { i = v.size(); } else { CHECK(i == v.size()); } } return i; } std::map<AggregateId, nc::net::Bandwidth> NetMock::GetMeansForNthPeriod( size_t n, PcapDataBinCache* cache) const { std::map<AggregateId, BinSequence> period_sequences = GetNthPeriod(n, bins_in_history_); std::map<AggregateId, nc::net::Bandwidth> out; for (const auto& id_and_sequence : period_sequences) { const AggregateId& id = id_and_sequence.first; nc::net::Bandwidth mean_level = id_and_sequence.second.MeanRate(cache); if (mean_level == nc::net::Bandwidth::Zero()) { mean_level = nc::net::Bandwidth::FromBitsPerSecond(10); } out[id] = mean_level; } return out; } static void RecordDelta(uint64_t at, const RoutingConfiguration& from, const RoutingConfiguration& to) { RoutingConfigurationDelta delta = from.GetDifference(to); uint64_t total_add = 0; uint64_t total_update = 0; uint64_t total_remove = 0; for (const auto& aggregate_and_delta : delta.aggregates) { const AggregateDelta& delta = aggregate_and_delta.second; total_add += delta.routes_added; total_update += delta.routes_updated; total_remove += delta.routes_removed; } route_add_metric->GetHandle()->AddValueWithTimestamp(at, total_add); route_update_metric->GetHandle()->AddValueWithTimestamp(at, total_update); route_remove_metric->GetHandle()->AddValueWithTimestamp(at, total_remove); } void NetMock::Run(PcapDataBinCache* cache) { std::unique_ptr<RoutingConfiguration> output = InitialOutput(cache); size_t timestamp = 0; for (size_t i = 0; i < period_count_; ++i) { LOG(ERROR) << "Period " << i; std::map<AggregateId, BinSequence> period_sequences = GetNthPeriod(i, period_duration_bins_); nc::net::GraphLinkMap<std::vector<std::pair<double, double>>> per_link_residuals = CheckOutput(period_sequences, *output, cache); size_t num_residuals = CheckSameSize(per_link_residuals); for (const auto& link_and_residuals : per_link_residuals) { nc::net::GraphLinkIndex link = link_and_residuals.first; const std::vector<std::pair<double, double>>& bins_and_residuals = *link_and_residuals.second; const nc::net::GraphLink* link_ptr = graph_->GetLink(link); auto* link_utilization_handle = link_utilization_metric->GetHandle( link_ptr->src_id(), link_ptr->dst_id()); auto* link_queue_size_handle = queue_size_metric->GetHandle(link_ptr->src_id(), link_ptr->dst_id()); size_t t = timestamp; for (size_t i = 0; i < bins_and_residuals.size(); ++i) { link_utilization_handle->AddValueWithTimestamp( t, bins_and_residuals[i].first); link_queue_size_handle->AddValueWithTimestamp( t++, bins_and_residuals[i].second); } } timestamp += num_residuals; // At the end of the period, will run the optimization or will check to see // if we need to trigger an optimization. size_t next_period = i + 1; if (next_period < periods_in_history_) { // Skip history for the first period. continue; } std::map<AggregateId, BinSequence> sequences_for_last_history = GetNthPeriod(next_period - periods_in_history_, bins_in_history_); std::map<AggregateId, AggregateHistory> input = GenerateInput(sequences_for_last_history, cache); bool need_update = false; if (next_period % periods_in_history_ == 0) { LOG(INFO) << "Will force update"; need_update = true; } else if (FLAGS_triggered_optimization) { std::set<AggregateId> aggregates_no_fit; std::tie(aggregates_no_fit, std::ignore) = routing_system_->CheckWithProbModel(*output, input); if (!aggregates_no_fit.empty()) { LOG(INFO) << "Will trigger update"; need_update = true; } } if (!need_update) { continue; } RoutingSystemUpdateResult result; if (FLAGS_mean_hints) { std::map<AggregateId, nc::net::Bandwidth> next_period_means = GetMeansForNthPeriod(next_period, cache); result = routing_system_->Update(input, next_period_means); } else { result = routing_system_->Update(input); } RecordDelta(timestamp, *output, *result.routing); output = std::move(result.routing); } prop_delay_per_aggregate->GetHandle()->AddValue(delays_seen_); } } // namespace ctr
c++
code
19,348
4,169
// // Copyright Aliaksei Levin ([email protected]), Arseny Smirnov ([email protected]) 2014-2021 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include "td/telegram/AnimationsManager.h" #include "td/telegram/BackgroundManager.h" #include "td/telegram/ChannelId.h" #include "td/telegram/ChatId.h" #include "td/telegram/ContactsManager.h" #include "td/telegram/FileReferenceManager.h" #include "td/telegram/files/FileSourceId.h" #include "td/telegram/FullMessageId.h" #include "td/telegram/MessagesManager.h" #include "td/telegram/StickersManager.h" #include "td/telegram/Td.h" #include "td/telegram/UserId.h" #include "td/telegram/WebPagesManager.h" #include "td/utils/common.h" #include "td/utils/overloaded.h" #include "td/utils/tl_helpers.h" namespace td { template <class StorerT> void FileReferenceManager::store_file_source(FileSourceId file_source_id, StorerT &storer) const { auto index = static_cast<size_t>(file_source_id.get()) - 1; CHECK(index < file_sources_.size()); auto &source = file_sources_[index]; td::store(source.get_offset(), storer); source.visit(overloaded([&](const FileSourceMessage &source) { td::store(source.full_message_id, storer); }, [&](const FileSourceUserPhoto &source) { td::store(source.user_id, storer); td::store(source.photo_id, storer); }, [&](const FileSourceChatPhoto &source) { td::store(source.chat_id, storer); }, [&](const FileSourceChannelPhoto &source) { td::store(source.channel_id, storer); }, [&](const FileSourceWallpapers &source) {}, [&](const FileSourceWebPage &source) { td::store(source.url, storer); }, [&](const FileSourceSavedAnimations &source) {}, [&](const FileSourceRecentStickers &source) { td::store(source.is_attached, storer); }, [&](const FileSourceFavoriteStickers &source) {}, [&](const FileSourceBackground &source) { td::store(source.background_id, storer); td::store(source.access_hash, storer); }, [&](const FileSourceChatFull &source) { td::store(source.chat_id, storer); }, [&](const FileSourceChannelFull &source) { td::store(source.channel_id, storer); })); } template <class ParserT> FileSourceId FileReferenceManager::parse_file_source(Td *td, ParserT &parser) { auto type = parser.fetch_int(); switch (type) { case 0: { FullMessageId full_message_id; td::parse(full_message_id, parser); return td->messages_manager_->get_message_file_source_id(full_message_id); } case 1: { UserId user_id; int64 photo_id; td::parse(user_id, parser); td::parse(photo_id, parser); return td->contacts_manager_->get_user_profile_photo_file_source_id(user_id, photo_id); } case 2: { ChatId chat_id; td::parse(chat_id, parser); return FileSourceId(); // there is no need to repair chat photos } case 3: { ChannelId channel_id; td::parse(channel_id, parser); return FileSourceId(); // there is no need to repair channel photos } case 4: return FileSourceId(); // there is no way to repair old wallpapers case 5: { string url; td::parse(url, parser); return td->web_pages_manager_->get_url_file_source_id(url); } case 6: return td->animations_manager_->get_saved_animations_file_source_id(); case 7: { bool is_attached; td::parse(is_attached, parser); return td->stickers_manager_->get_recent_stickers_file_source_id(is_attached); } case 8: return td->stickers_manager_->get_favorite_stickers_file_source_id(); case 9: { BackgroundId background_id; int64 access_hash; td::parse(background_id, parser); td::parse(access_hash, parser); return td->background_manager_->get_background_file_source_id(background_id, access_hash); } case 10: { ChatId chat_id; td::parse(chat_id, parser); return td->contacts_manager_->get_chat_full_file_source_id(chat_id); } case 11: { ChannelId channel_id; td::parse(channel_id, parser); return td->contacts_manager_->get_channel_full_file_source_id(channel_id); } default: parser.set_error("Invalid type in FileSource"); return FileSourceId(); } } } // namespace td
c++
code
4,764
895
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: [email protected] * * original model: https://github.com/dog-qiuqiu/Yolo-Fastest/tree/master/ModelZoo/yolo-fastest-1.1_coco */ #include <iostream> #include <iomanip> #include <vector> #ifdef _MSC_VER #define NOMINMAX #endif #include <algorithm> #include <cstdlib> #include <cmath> #include "common.h" #include "tengine/c_api.h" #include "tengine_operations.h" #define DEFAULT_REPEAT_COUNT 1 #define DEFAULT_THREAD_COUNT 1 enum { YOLOV3 = 0, YOLO_FASTEST = 1, YOLO_FASTEST_XL = 2 }; using namespace std; struct BBoxRect { float score; float xmin; float ymin; float xmax; float ymax; float area; int label; }; struct TMat { operator const float*() const { return (const float*)data; } float *row(int row) const { return (float *)data + w * row; } TMat channel_range(int start, int chn_num) const { TMat mat = { 0 }; mat.batch = 1; mat.c = chn_num; mat.h = h; mat.w = w; mat.data = (float *)data + start * h * w; return mat; } TMat channel(int channel) const { return channel_range(channel, 1); } int batch, c, h, w; void *data; }; class Yolov3DetectionOutput { public: int init(int version); int forward(const std::vector<TMat>& bottom_blobs, std::vector<TMat>& top_blobs); private: int m_num_box; int m_num_class; float m_anchors_scale[32]; float m_biases[32]; int m_mask[32]; float m_confidence_threshold; float m_nms_threshold; }; static const char* class_names[] = { "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush" }; int Yolov3DetectionOutput::init(int version) { memset(this, 0, sizeof(*this)); m_num_box = 3; m_num_class = 80; fprintf(stderr, "Yolov3DetectionOutput init param[%d]\n", version); if (version == YOLOV3) { m_anchors_scale[0] = 32; m_anchors_scale[1] = 16; m_anchors_scale[2] = 8; float bias[] = { 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 }; memcpy(m_biases, bias, sizeof(bias)); m_mask[0] = 6; m_mask[1] = 7; m_mask[2] = 8; m_mask[3] = 3; m_mask[4] = 4; m_mask[5] = 5; m_mask[6] = 0; m_mask[7] = 1; m_mask[8] = 2; } else if (version == YOLO_FASTEST || version == YOLO_FASTEST_XL) { m_anchors_scale[0] = 32; m_anchors_scale[1] = 16; float bias[] = { 12, 18, 37, 49, 52,132, 115, 73, 119,199, 242,238 }; memcpy(m_biases, bias, sizeof(bias)); m_mask[0] = 3; m_mask[1] = 4; m_mask[2] = 5; m_mask[3] = 0; m_mask[4] = 1; m_mask[5] = 2; } m_confidence_threshold = 0.48f; m_nms_threshold = 0.45f; return 0; } static inline float intersection_area(const BBoxRect& a, const BBoxRect& b) { if (a.xmin > b.xmax || a.xmax < b.xmin || a.ymin > b.ymax || a.ymax < b.ymin) { // no intersection return 0.f; } float inter_width = std::min(a.xmax, b.xmax) - std::max(a.xmin, b.xmin); float inter_height = std::min(a.ymax, b.ymax) - std::max(a.ymin, b.ymin); return inter_width * inter_height; } static void qsort_descent_inplace(std::vector<BBoxRect>& datas, int left, int right) { int i = left; int j = right; float p = datas[(left + right) / 2].score; while (i <= j) { while (datas[i].score > p) i++; while (datas[j].score < p) j--; if (i <= j) { // swap std::swap(datas[i], datas[j]); i++; j--; } } if (left < j) qsort_descent_inplace(datas, left, j); if (i < right) qsort_descent_inplace(datas, i, right); } static void qsort_descent_inplace(std::vector<BBoxRect>& datas) { if (datas.empty()) return; qsort_descent_inplace(datas, 0, (int)(datas.size() - 1)); } static void nms_sorted_bboxes(std::vector<BBoxRect>& bboxes, std::vector<size_t>& picked, float nms_threshold) { picked.clear(); const size_t n = bboxes.size(); for (size_t i = 0; i < n; i++) { const BBoxRect& a = bboxes[i]; int keep = 1; for (int j = 0; j < (int)picked.size(); j++) { const BBoxRect& b = bboxes[picked[j]]; // intersection over union float inter_area = intersection_area(a, b); float union_area = a.area + b.area - inter_area; // float IoU = inter_area / union_area if (inter_area > nms_threshold * union_area) { keep = 0; break; } } if (keep) picked.push_back(i); } } static inline float sigmoid(float x) { return (float)(1.f / (1.f + exp(-x))); } int Yolov3DetectionOutput::forward(const std::vector<TMat>& bottom_blobs, std::vector<TMat>& top_blobs) { // gather all box std::vector<BBoxRect> all_bbox_rects; for (size_t b = 0; b < bottom_blobs.size(); b++) { std::vector<std::vector<BBoxRect> > all_box_bbox_rects; all_box_bbox_rects.resize(m_num_box); const TMat& bottom_top_blobs = bottom_blobs[b]; int w = bottom_top_blobs.w; int h = bottom_top_blobs.h; int channels = bottom_top_blobs.c; //printf("%d %d %d\n", w, h, channels); const int channels_per_box = channels / m_num_box; // anchor coord + box score + num_class if (channels_per_box != 4 + 1 + m_num_class) return -1; size_t mask_offset = b * m_num_box; int net_w = (int)(m_anchors_scale[b] * w); int net_h = (int)(m_anchors_scale[b] * h); //printf("%d %d\n", net_w, net_h); //printf("%d %d %d\n", w, h, channels); for (int pp = 0; pp < m_num_box; pp++) { int p = pp * channels_per_box; int biases_index = (int)(m_mask[pp + mask_offset]); //printf("%d\n", biases_index); const float bias_w = m_biases[biases_index * 2]; const float bias_h = m_biases[biases_index * 2 + 1]; //printf("%f %f\n", bias_w, bias_h); const float* xptr = bottom_top_blobs.channel(p); const float* yptr = bottom_top_blobs.channel(p + 1); const float* wptr = bottom_top_blobs.channel(p + 2); const float* hptr = bottom_top_blobs.channel(p + 3); const float* box_score_ptr = bottom_top_blobs.channel(p + 4); // softmax class scores TMat scores = bottom_top_blobs.channel_range(p + 5, m_num_class); //softmax->forward_inplace(scores, opt); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { // find class index with max class score int class_index = 0; float class_score = -FLT_MAX; for (int q = 0; q < m_num_class; q++) { float score = scores.channel(q).row(i)[j]; if (score > class_score) { class_index = q; class_score = score; } } //sigmoid(box_score) * sigmoid(class_score) float confidence = 1.f / ((1.f + exp(-box_score_ptr[0]) * (1.f + exp(-class_score)))); if (confidence >= m_confidence_threshold) { // region box float bbox_cx = (j + sigmoid(xptr[0])) / w; float bbox_cy = (i + sigmoid(yptr[0])) / h; float bbox_w = (float)(exp(wptr[0]) * bias_w / net_w); float bbox_h = (float)(exp(hptr[0]) * bias_h / net_h); float bbox_xmin = bbox_cx - bbox_w * 0.5f; float bbox_ymin = bbox_cy - bbox_h * 0.5f; float bbox_xmax = bbox_cx + bbox_w * 0.5f; float bbox_ymax = bbox_cy + bbox_h * 0.5f; float area = bbox_w * bbox_h; BBoxRect c = { confidence, bbox_xmin, bbox_ymin, bbox_xmax, bbox_ymax, area, class_index }; all_box_bbox_rects[pp].push_back(c); } xptr++; yptr++; wptr++; hptr++; box_score_ptr++; } } } for (int i = 0; i < m_num_box; i++) { const std::vector<BBoxRect>& box_bbox_rects = all_box_bbox_rects[i]; all_bbox_rects.insert(all_bbox_rects.end(), box_bbox_rects.begin(), box_bbox_rects.end()); } } // global sort inplace qsort_descent_inplace(all_bbox_rects); // apply nms std::vector<size_t> picked; nms_sorted_bboxes(all_bbox_rects, picked, m_nms_threshold); // select std::vector<BBoxRect> bbox_rects; for (size_t i = 0; i < picked.size(); i++) { size_t z = picked[i]; bbox_rects.push_back(all_bbox_rects[z]); } // fill result int num_detected = (int)(bbox_rects.size()); if (num_detected == 0) return 0; TMat& top_blob = top_blobs[0]; for (int i = 0; i < num_detected; i++) { const BBoxRect& r = bbox_rects[i]; float score = r.score; float* outptr = top_blob.row(i); outptr[0] = (float)(r.label + 1); // +1 for prepend background class outptr[1] = score; outptr[2] = r.xmin; outptr[3] = r.ymin; outptr[4] = r.xmax; outptr[5] = r.ymax; } top_blob.h = num_detected; return 0; } static void get_input_data_darknet(const char* image_file, float* input_data, int net_h, int net_w) { float mean[3] = { 0.f, 0.f, 0.f }; float scale[3] = { 1.0f / 255, 1.0f / 255, 1.0f / 255 }; //no letter box by default get_input_data(image_file, input_data, net_h, net_w, mean, scale); // input rgb image swaprgb_img = { 0 }; swaprgb_img.c = 3; swaprgb_img.w = net_w; swaprgb_img.h = net_h; swaprgb_img.data = input_data; rgb2bgr_premute(swaprgb_img); } static void show_usage() { fprintf(stderr, "[Usage]: [-h]\n [-m model_file] [-i image_file] [-r repeat_count] [-t thread_count]\n"); } static void run_yolo(graph_t graph, std::vector<BBoxRect> &boxes, int img_width, int img_height) { Yolov3DetectionOutput yolo; std::vector<TMat> yolo_inputs, yolo_outputs; yolo.init(YOLO_FASTEST); int output_node_num = get_graph_output_node_number(graph); yolo_inputs.resize(output_node_num); yolo_outputs.resize(1); for (int i = 0; i < output_node_num; ++i) { tensor_t out_tensor = get_graph_output_tensor(graph, i, 0); //"detection_out" int out_dim[4] = { 0 }; get_tensor_shape(out_tensor, out_dim, 4); yolo_inputs[i].batch = out_dim[0]; yolo_inputs[i].c = out_dim[1]; yolo_inputs[i].h = out_dim[2]; yolo_inputs[i].w = out_dim[3]; yolo_inputs[i].data = get_tensor_buffer(out_tensor); } std::vector<float> output_buf; output_buf.resize(1000 * 6, 0); yolo_outputs[0].batch = 1; yolo_outputs[0].c = 1; yolo_outputs[0].h = 1000; yolo_outputs[0].w = 6; yolo_outputs[0].data = output_buf.data(); yolo.forward(yolo_inputs, yolo_outputs); //image roi on net input bool letterbox = false; float roi_left = 0.f, roi_top = 0.f, roi_width = 1.f, roi_height = 1.f; if (letterbox) { if (img_width > img_height) { roi_height = img_height / (float)img_width; roi_top = (1 - roi_height) / 2; } else { roi_width = img_width / (float)img_height; roi_left = (1 - roi_width) / 2; } } //rect correct for (int i = 0; i < yolo_outputs[0].h; i++) { float *data_row = yolo_outputs[0].row(i); BBoxRect box = { 0 }; box.score = data_row[1]; box.label = data_row[0]; box.xmin = (data_row[2] - roi_left) / roi_width * img_width; box.ymin = (data_row[3] - roi_top) / roi_height * img_height; box.xmax = (data_row[4] - roi_left) / roi_width * img_width; box.ymax = (data_row[5] - roi_top) / roi_height * img_height; boxes.push_back(box); } //release for (int i = 0; i < output_node_num; ++i) { tensor_t out_tensor = get_graph_output_tensor(graph, i, 0); release_graph_tensor(out_tensor); } } int main(int argc, char* argv[]) { int repeat_count = DEFAULT_REPEAT_COUNT; int num_thread = DEFAULT_THREAD_COUNT; char* model_file = nullptr; char* image_file = nullptr; int net_w = 320; int net_h = 320; int res; while ((res = getopt(argc, argv, "m:i:r:t:h:")) != -1) { switch (res) { case 'm': model_file = optarg; break; case 'i': image_file = optarg; break; case 'r': repeat_count = std::strtoul(optarg, nullptr, 10); break; case 't': num_thread = std::strtoul(optarg, nullptr, 10); break; case 'h': show_usage(); return 0; default: break; } } /* check files */ if (nullptr == model_file) { fprintf(stderr, "Error: Tengine model file not specified!\n"); show_usage(); return -1; } if (nullptr == image_file) { fprintf(stderr, "Error: Image file not specified!\n"); show_usage(); return -1; } if (!check_file_exist(model_file) || !check_file_exist(image_file)) return -1; /* set runtime options */ struct options opt; opt.num_thread = num_thread; opt.cluster = TENGINE_CLUSTER_ALL; opt.precision = TENGINE_MODE_FP32; opt.affinity = 0; /* inital tengine */ if (init_tengine() != 0) { fprintf(stderr, "Initial tengine failed.\n"); return -1; } fprintf(stderr, "tengine-lite library version: %s\n", get_tengine_version()); /* create graph, load tengine model xxx.tmfile */ graph_t graph = create_graph(nullptr, "tengine", model_file); if (graph == nullptr) { fprintf(stderr, "Create graph failed.\n"); return -1; } /* set the input shape to initial the graph, and prerun graph to infer shape */ int img_size = net_h * net_w * 3; int dims[] = { 1, 3, net_h, net_w }; // nchw std::vector<float> input_data(img_size); tensor_t input_tensor = get_graph_input_tensor(graph, 0, 0); if (input_tensor == nullptr) { fprintf(stderr, "Get input tensor failed\n"); return -1; } if (set_tensor_shape(input_tensor, dims, 4) < 0) { fprintf(stderr, "Set input tensor shape failed\n"); return -1; } if (set_tensor_buffer(input_tensor, input_data.data(), img_size * 4) < 0) { fprintf(stderr, "Set input tensor buffer failed\n"); return -1; } /* prerun graph, set work options(num_thread, cluster, precision) */ if (prerun_graph_multithread(graph, opt) < 0) { fprintf(stderr, "Prerun multithread graph failed.\n"); return -1; } /* prepare process input data, set the data mem to input tensor */ get_input_data_darknet(image_file, input_data.data(), net_h, net_w); /* run graph */ double min_time = DBL_MAX; double max_time = DBL_MIN; double total_time = 0.; for (int i = 0; i < repeat_count; i++) { double start = get_current_time(); if (run_graph(graph, 1) < 0) { fprintf(stderr, "Run graph failed\n"); return -1; } double end = get_current_time(); double cur = end - start; total_time += cur; min_time = std::min(min_time, cur); max_time = std::max(max_time, cur); } fprintf(stderr, "Repeat %d times, thread %d, avg time %.2f ms, max_time %.2f ms, min_time %.2f ms\n", repeat_count, num_thread, total_time / repeat_count, max_time, min_time); fprintf(stderr, "--------------------------------------\n"); /* process the detection result */ image img = imread(image_file); std::vector<BBoxRect> boxes; run_yolo(graph, boxes, img.w, img.h); for (int i = 0; i < (int)boxes.size(); ++i) { BBoxRect b = boxes[i]; draw_box(img, b.xmin, b.ymin, b.xmax, b.ymax, 2, 125, 0, 125); fprintf(stderr, "class=%2d score=%.2f left = %.2f,right = %.2f,top = %.2f,bot = %.2f, name = %s\n", b.label, b.score, b.xmin, b.xmax, b.ymin, b.ymax, class_names[b.label]); } save_image(img, "yolofastest_out"); /* release tengine */ free_image(img); release_graph_tensor(input_tensor); postrun_graph(graph); destroy_graph(graph); release_tengine(); return 0; }
c++
code
18,965
4,411
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // This file was modified by Oracle on 2014, 2015. // Modifications copyright (c) 2014-2015 Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_IO_WKT_READ_HPP #define BOOST_GEOMETRY_IO_WKT_READ_HPP #include <cstddef> #include <string> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> #include <boost/mpl/if.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/range/size.hpp> #include <boost/range/value_type.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/geometry/algorithms/assign.hpp> #include <boost/geometry/algorithms/append.hpp> #include <boost/geometry/algorithms/clear.hpp> #include <boost/geometry/algorithms/detail/equals/point_point.hpp> #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/coordinate_dimension.hpp> #include <boost/geometry/core/exception.hpp> #include <boost/geometry/core/exterior_ring.hpp> #include <boost/geometry/core/geometry_id.hpp> #include <boost/geometry/core/interior_rings.hpp> #include <boost/geometry/core/mutable_range.hpp> #include <boost/geometry/core/point_type.hpp> #include <boost/geometry/core/tag_cast.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/util/coordinate_cast.hpp> #include <boost/geometry/io/wkt/detail/prefix.hpp> namespace boost { namespace geometry { /*! \brief Exception showing things wrong with WKT parsing \ingroup wkt */ struct read_wkt_exception : public geometry::exception { template <typename Iterator> read_wkt_exception(std::string const& msg, Iterator const& it, Iterator const& end, std::string const& wkt) : message(msg) , wkt(wkt) { if (it != end) { source = " at '"; source += it->c_str(); source += "'"; } complete = message + source + " in '" + wkt.substr(0, 100) + "'"; } read_wkt_exception(std::string const& msg, std::string const& wkt) : message(msg) , wkt(wkt) { complete = message + "' in (" + wkt.substr(0, 100) + ")"; } virtual ~read_wkt_exception() throw() {} virtual const char* what() const throw() { return complete.c_str(); } private : std::string source; std::string message; std::string wkt; std::string complete; }; #ifndef DOXYGEN_NO_DETAIL // (wkt: Well Known Text, defined by OGC for all geometries and implemented by e.g. databases (MySQL, PostGIS)) namespace detail { namespace wkt { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; template <typename Point, std::size_t Dimension = 0, std::size_t DimensionCount = geometry::dimension<Point>::value> struct parsing_assigner { static inline void apply(tokenizer::iterator& it, tokenizer::iterator const& end, Point& point, std::string const& wkt) { typedef typename coordinate_type<Point>::type coordinate_type; // Stop at end of tokens, or at "," ot ")" bool finished = (it == end || *it == "," || *it == ")"); try { // Initialize missing coordinates to default constructor (zero) // OR // Use lexical_cast for conversion to double/int // Note that it is much slower than atof. However, it is more standard // and in parsing the change in performance falls probably away against // the tokenizing set<Dimension>(point, finished ? coordinate_type() : coordinate_cast<coordinate_type>::apply(*it)); } catch(boost::bad_lexical_cast const& blc) { throw read_wkt_exception(blc.what(), it, end, wkt); } catch(std::exception const& e) { throw read_wkt_exception(e.what(), it, end, wkt); } catch(...) { throw read_wkt_exception("", it, end, wkt); } parsing_assigner<Point, Dimension + 1, DimensionCount>::apply( (finished ? it : ++it), end, point, wkt); } }; template <typename Point, std::size_t DimensionCount> struct parsing_assigner<Point, DimensionCount, DimensionCount> { static inline void apply(tokenizer::iterator&, tokenizer::iterator const&, Point&, std::string const&) { } }; template <typename Iterator> inline void handle_open_parenthesis(Iterator& it, Iterator const& end, std::string const& wkt) { if (it == end || *it != "(") { throw read_wkt_exception("Expected '('", it, end, wkt); } ++it; } template <typename Iterator> inline void handle_close_parenthesis(Iterator& it, Iterator const& end, std::string const& wkt) { if (it != end && *it == ")") { ++it; } else { throw read_wkt_exception("Expected ')'", it, end, wkt); } } template <typename Iterator> inline void check_end(Iterator& it, Iterator const& end, std::string const& wkt) { if (it != end) { throw read_wkt_exception("Too much tokens", it, end, wkt); } } /*! \brief Internal, parses coordinate sequences, strings are formated like "(1 2,3 4,...)" \param it token-iterator, should be pre-positioned at "(", is post-positions after last ")" \param end end-token-iterator \param out Output itererator receiving coordinates */ template <typename Point> struct container_inserter { // Version with output iterator template <typename OutputIterator> static inline void apply(tokenizer::iterator& it, tokenizer::iterator const& end, std::string const& wkt, OutputIterator out) { handle_open_parenthesis(it, end, wkt); Point point; // Parse points until closing parenthesis while (it != end && *it != ")") { parsing_assigner<Point>::apply(it, end, point, wkt); out = point; ++out; if (it != end && *it == ",") { ++it; } } handle_close_parenthesis(it, end, wkt); } }; template <typename Geometry, closure_selector Closure = closure<Geometry>::value> struct stateful_range_appender { typedef typename geometry::point_type<Geometry>::type point_type; // NOTE: Geometry is a reference inline void append(Geometry geom, point_type const& point, bool) { geometry::append(geom, point); } }; template <typename Geometry> struct stateful_range_appender<Geometry, open> { typedef typename geometry::point_type<Geometry>::type point_type; typedef typename boost::range_size < typename util::bare_type<Geometry>::type >::type size_type; BOOST_STATIC_ASSERT(( boost::is_same < typename tag<Geometry>::type, ring_tag >::value )); inline stateful_range_appender() : pt_index(0) {} // NOTE: Geometry is a reference inline void append(Geometry geom, point_type const& point, bool is_next_expected) { bool should_append = true; if (pt_index == 0) { first_point = point; //should_append = true; } else { // NOTE: if there is not enough Points, they're always appended should_append = is_next_expected || pt_index < core_detail::closure::minimum_ring_size<open>::value || !detail::equals::equals_point_point(point, first_point); } ++pt_index; if (should_append) { geometry::append(geom, point); } } private: size_type pt_index; point_type first_point; }; // Geometry is a value-type or reference-type template <typename Geometry> struct container_appender { typedef typename geometry::point_type<Geometry>::type point_type; static inline void apply(tokenizer::iterator& it, tokenizer::iterator const& end, std::string const& wkt, Geometry out) { handle_open_parenthesis(it, end, wkt); stateful_range_appender<Geometry> appender; // Parse points until closing parenthesis while (it != end && *it != ")") { point_type point; parsing_assigner<point_type>::apply(it, end, point, wkt); bool const is_next_expected = it != end && *it == ","; appender.append(out, point, is_next_expected); if (is_next_expected) { ++it; } } handle_close_parenthesis(it, end, wkt); } }; /*! \brief Internal, parses a point from a string like this "(x y)" \note used for parsing points and multi-points */ template <typename P> struct point_parser { static inline void apply(tokenizer::iterator& it, tokenizer::iterator const& end, std::string const& wkt, P& point) { handle_open_parenthesis(it, end, wkt); parsing_assigner<P>::apply(it, end, point, wkt); handle_close_parenthesis(it, end, wkt); } }; template <typename Geometry> struct linestring_parser { static inline void apply(tokenizer::iterator& it, tokenizer::iterator const& end, std::string const& wkt, Geometry& geometry) { container_appender<Geometry&>::apply(it, end, wkt, geometry); } }; template <typename Ring> struct ring_parser { static inline void apply(tokenizer::iterator& it, tokenizer::iterator const& end, std::string const& wkt, Ring& ring) { // A ring should look like polygon((x y,x y,x y...)) // So handle the extra opening/closing parentheses // and in between parse using the container-inserter handle_open_parenthesis(it, end, wkt); container_appender<Ring&>::apply(it, end, wkt, ring); handle_close_parenthesis(it, end, wkt); } }; /*! \brief Internal, parses a polygon from a string like this "((x y,x y),(x y,x y))" \note used for parsing polygons and multi-polygons */ template <typename Polygon> struct polygon_parser { typedef typename ring_return_type<Polygon>::type ring_return_type; typedef container_appender<ring_return_type> appender; static inline void apply(tokenizer::iterator& it, tokenizer::iterator const& end, std::string const& wkt, Polygon& poly) { handle_open_parenthesis(it, end, wkt); int n = -1; // Stop at ")" while (it != end && *it != ")") { // Parse ring if (++n == 0) { appender::apply(it, end, wkt, exterior_ring(poly)); } else { typename ring_type<Polygon>::type ring; appender::apply(it, end, wkt, ring); traits::push_back < typename boost::remove_reference < typename traits::interior_mutable_type<Polygon>::type >::type >::apply(interior_rings(poly), ring); } if (it != end && *it == ",") { // Skip "," after ring is parsed ++it; } } handle_close_parenthesis(it, end, wkt); } }; inline bool one_of(tokenizer::iterator const& it, std::string const& value, bool& is_present) { if (boost::iequals(*it, value)) { is_present = true; return true; } return false; } inline bool one_of(tokenizer::iterator const& it, std::string const& value, bool& present1, bool& present2) { if (boost::iequals(*it, value)) { present1 = true; present2 = true; return true; } return false; } inline void handle_empty_z_m(tokenizer::iterator& it, tokenizer::iterator const& end, bool& has_empty, bool& has_z, bool& has_m) { has_empty = false; has_z = false; has_m = false; // WKT can optionally have Z and M (measured) values as in // POINT ZM (1 1 5 60), POINT M (1 1 80), POINT Z (1 1 5) // GGL supports any of them as coordinate values, but is not aware // of any Measured value. while (it != end && (one_of(it, "M", has_m) || one_of(it, "Z", has_z) || one_of(it, "EMPTY", has_empty) || one_of(it, "MZ", has_m, has_z) || one_of(it, "ZM", has_z, has_m) ) ) { ++it; } } /*! \brief Internal, starts parsing \param tokens boost tokens, parsed with separator " " and keeping separator "()" \param geometry string to compare with first token */ template <typename Geometry> inline bool initialize(tokenizer const& tokens, std::string const& geometry_name, std::string const& wkt, tokenizer::iterator& it, tokenizer::iterator& end) { it = tokens.begin(); end = tokens.end(); if (it != end && boost::iequals(*it++, geometry_name)) { bool has_empty, has_z, has_m; handle_empty_z_m(it, end, has_empty, has_z, has_m); // Silence warning C4127: conditional expression is constant #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4127) #endif if (has_z && dimension<Geometry>::type::value < 3) { throw read_wkt_exception("Z only allowed for 3 or more dimensions", wkt); } #if defined(_MSC_VER) #pragma warning(pop) #endif if (has_empty) { check_end(it, end, wkt); return false; } // M is ignored at all. return true; } throw read_wkt_exception(std::string("Should start with '") + geometry_name + "'", wkt); } template <typename Geometry, template<typename> class Parser, typename PrefixPolicy> struct geometry_parser { static inline void apply(std::string const& wkt, Geometry& geometry) { geometry::clear(geometry); tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()")); tokenizer::iterator it, end; if (initialize<Geometry>(tokens, PrefixPolicy::apply(), wkt, it, end)) { Parser<Geometry>::apply(it, end, wkt, geometry); check_end(it, end, wkt); } } }; template <typename MultiGeometry, template<typename> class Parser, typename PrefixPolicy> struct multi_parser { static inline void apply(std::string const& wkt, MultiGeometry& geometry) { traits::clear<MultiGeometry>::apply(geometry); tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()")); tokenizer::iterator it, end; if (initialize<MultiGeometry>(tokens, PrefixPolicy::apply(), wkt, it, end)) { handle_open_parenthesis(it, end, wkt); // Parse sub-geometries while(it != end && *it != ")") { traits::resize<MultiGeometry>::apply(geometry, boost::size(geometry) + 1); Parser < typename boost::range_value<MultiGeometry>::type >::apply(it, end, wkt, *(boost::end(geometry) - 1)); if (it != end && *it == ",") { // Skip "," after multi-element is parsed ++it; } } handle_close_parenthesis(it, end, wkt); } check_end(it, end, wkt); } }; template <typename P> struct noparenthesis_point_parser { static inline void apply(tokenizer::iterator& it, tokenizer::iterator const& end, std::string const& wkt, P& point) { parsing_assigner<P>::apply(it, end, point, wkt); } }; template <typename MultiGeometry, typename PrefixPolicy> struct multi_point_parser { static inline void apply(std::string const& wkt, MultiGeometry& geometry) { traits::clear<MultiGeometry>::apply(geometry); tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()")); tokenizer::iterator it, end; if (initialize<MultiGeometry>(tokens, PrefixPolicy::apply(), wkt, it, end)) { handle_open_parenthesis(it, end, wkt); // If first point definition starts with "(" then parse points as (x y) // otherwise as "x y" bool using_brackets = (it != end && *it == "("); while(it != end && *it != ")") { traits::resize<MultiGeometry>::apply(geometry, boost::size(geometry) + 1); if (using_brackets) { point_parser < typename boost::range_value<MultiGeometry>::type >::apply(it, end, wkt, *(boost::end(geometry) - 1)); } else { noparenthesis_point_parser < typename boost::range_value<MultiGeometry>::type >::apply(it, end, wkt, *(boost::end(geometry) - 1)); } if (it != end && *it == ",") { // Skip "," after point is parsed ++it; } } handle_close_parenthesis(it, end, wkt); } check_end(it, end, wkt); } }; /*! \brief Supports box parsing \note OGC does not define the box geometry, and WKT does not support boxes. However, to be generic GGL supports reading and writing from and to boxes. Boxes are outputted as a standard POLYGON. GGL can read boxes from a standard POLYGON, from a POLYGON with 2 points of from a BOX \tparam Box the box */ template <typename Box> struct box_parser { static inline void apply(std::string const& wkt, Box& box) { bool should_close = false; tokenizer tokens(wkt, boost::char_separator
c++
code
20,000
3,814
#include <iostream> #include <cstdio> using namespace std; int datas[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31}, {31,29,31,30,31,30,31,31,30,31,30,31}}; int isLeapYear(int year){ return (year%4==0&&year%100!=0)||year%400==0; } // 日期类,加一天操作; int main(){ int n; scanf("%d",&n); while(n>0){ n--; int year,month,day; scanf("%d%d%d",&year,&month,&day); day++; if(day>datas[isLeapYear(year)][month-1]){ day=1; month++; if(month>12){ month=1; year++; } } printf("%04d-%02d-%02d\n",year,month,day); } return 0; }
c++
code
644
241
// Copyright (C) 2018 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <gmock/gmock-spec-builders.h> #include <thread> #include <ie_common.h> #include <details/ie_exception.hpp> #include <cpp_interfaces/ie_task.hpp> #include <cpp_interfaces/ie_task_synchronizer.hpp> #include "task_tests_utils.hpp" using namespace ::testing; using namespace std; using namespace InferenceEngine; using namespace InferenceEngine::details; class TaskTests : public ::testing::Test { protected: Task::Ptr _task = std::make_shared<Task>(); }; TEST_F(TaskTests, canRunWithTaskSync) { TaskSynchronizer::Ptr taskSynchronizer = std::make_shared<TaskSynchronizer>(); ASSERT_NO_THROW(_task->runWithSynchronizer(taskSynchronizer)); ASSERT_EQ(_task->getStatus(), Task::TS_DONE); } TEST_F(TaskTests, canRunWithTaskSyncAndWait) { TaskSynchronizer::Ptr taskSynchronizer = std::make_shared<TaskSynchronizer>(); ASSERT_NO_THROW(_task->runWithSynchronizer(taskSynchronizer)); Task::Status status = _task->wait(-1); ASSERT_EQ(status, Task::TS_DONE); } // TODO: CVS-11695 TEST_F(TaskTests, DISABLED_returnBusyStatusWhenStartTaskWhichIsRunning) { TaskSynchronizer::Ptr taskSynchronizer = std::make_shared<TaskSynchronizer>(); std::vector<Task::Status> statuses; std::vector<MetaThread::Ptr> metaThreads; // otherwise push_back to the vector won't be thread-safe statuses.reserve(MAX_NUMBER_OF_TASKS_IN_QUEUE); _task->occupy(); for (int i = 0; i < MAX_NUMBER_OF_TASKS_IN_QUEUE; i++) { metaThreads.push_back(make_shared<MetaThread>([&]() { statuses.push_back(_task->runWithSynchronizer(taskSynchronizer)); })); } for (auto &metaThread : metaThreads) metaThread->join(); for (auto &status : statuses) ASSERT_EQ(Task::Status::TS_BUSY, status) << "Start task never return busy status"; } TEST_F(TaskTests, canSyncNThreadsUsingTaskSync) { TaskSynchronizer::Ptr taskSynchronizer = std::make_shared<TaskSynchronizer>(); int sharedVar = 0; size_t THREAD_NUMBER = MAX_NUMBER_OF_TASKS_IN_QUEUE; size_t NUM_INTERNAL_ITERATIONS = 5000; std::vector<Task::Status> statuses; std::vector<MetaThread::Ptr> metaThreads; // otherwise push_back to the vector won't be thread-safe statuses.reserve(THREAD_NUMBER); for (int i = 0; i < THREAD_NUMBER; i++) { metaThreads.push_back(make_shared<MetaThread>([&]() { auto status = Task([&]() { for (int k = 0; k < NUM_INTERNAL_ITERATIONS; k++) sharedVar++; }).runWithSynchronizer(taskSynchronizer); statuses.push_back(status); })); } for (auto &metaThread : metaThreads) metaThread->join(); for (auto &status : statuses) ASSERT_NE(Task::Status::TS_BUSY, status); ASSERT_EQ(sharedVar, THREAD_NUMBER * NUM_INTERNAL_ITERATIONS); }
c++
code
2,890
591
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "atom/browser/atom_download_manager_delegate.h" #include <string> #include "atom/browser/api/atom_api_download_item.h" #include "atom/browser/atom_browser_context.h" #include "atom/browser/native_window.h" #include "atom/browser/ui/file_dialog.h" #include "atom/browser/web_contents_preferences.h" #include "base/bind.h" #include "base/files/file_util.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" namespace atom { namespace { // Generate default file path to save the download. void CreateDownloadPath( const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& default_download_path, const AtomDownloadManagerDelegate::CreateDownloadPathCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::FILE); auto generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, "download"); if (!base::PathExists(default_download_path)) base::CreateDirectory(default_download_path); base::FilePath path(default_download_path.Append(generated_name)); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::BindOnce(callback, path)); } } // namespace AtomDownloadManagerDelegate::AtomDownloadManagerDelegate( content::DownloadManager* manager) : download_manager_(manager), weak_ptr_factory_(this) {} AtomDownloadManagerDelegate::~AtomDownloadManagerDelegate() { if (download_manager_) { DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this), download_manager_->GetDelegate()); download_manager_->SetDelegate(nullptr); download_manager_ = nullptr; } } void AtomDownloadManagerDelegate::GetItemSavePath(content::DownloadItem* item, base::FilePath* path) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); api::DownloadItem* download = api::DownloadItem::FromWrappedClass(isolate, item); if (download) *path = download->GetSavePath(); } void AtomDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& default_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* item = download_manager_->GetDownload(download_id); if (!item) return; NativeWindow* window = nullptr; content::WebContents* web_contents = item->GetWebContents(); auto* relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr; if (relay) window = relay->window.get(); auto* web_preferences = WebContentsPreferences::From(web_contents); bool offscreen = !web_preferences || web_preferences->IsEnabled("offscreen"); base::FilePath path; GetItemSavePath(item, &path); // Show save dialog if save path was not set already on item file_dialog::DialogSettings settings; settings.parent_window = window; settings.force_detached = offscreen; settings.title = item->GetURL().spec(); settings.default_path = default_path; if (path.empty() && file_dialog::ShowSaveDialog(settings, &path)) { // Remember the last selected download directory. AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>( download_manager_->GetBrowserContext()); browser_context->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory, path.DirName()); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); api::DownloadItem* download_item = api::DownloadItem::FromWrappedClass(isolate, item); if (download_item) download_item->SetSavePath(path); } // Running the DownloadTargetCallback with an empty FilePath signals that the // download should be cancelled. // If user cancels the file save dialog, run the callback with empty FilePath. callback.Run(path, content::DownloadItem::TARGET_DISPOSITION_PROMPT, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path, path.empty() ? content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED : content::DOWNLOAD_INTERRUPT_REASON_NONE); } void AtomDownloadManagerDelegate::Shutdown() { weak_ptr_factory_.InvalidateWeakPtrs(); download_manager_ = nullptr; } bool AtomDownloadManagerDelegate::DetermineDownloadTarget( content::DownloadItem* download, const content::DownloadTargetCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!download->GetForcedFilePath().empty()) { callback.Run(download->GetForcedFilePath(), content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, download->GetForcedFilePath(), content::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } // Try to get the save path from JS wrapper. base::FilePath save_path; GetItemSavePath(download, &save_path); if (!save_path.empty()) { callback.Run(save_path, content::DownloadItem::TARGET_DISPOSITION_OVERWRITE, content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, save_path, content::DOWNLOAD_INTERRUPT_REASON_NONE); return true; } AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>(download_manager_->GetBrowserContext()); base::FilePath default_download_path = browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory); CreateDownloadPathCallback download_path_callback = base::Bind(&AtomDownloadManagerDelegate::OnDownloadPathGenerated, weak_ptr_factory_.GetWeakPtr(), download->GetId(), callback); content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::BindOnce(&CreateDownloadPath, download->GetURL(), download->GetContentDisposition(), download->GetSuggestedFilename(), download->GetMimeType(), default_download_path, download_path_callback)); return true; } bool AtomDownloadManagerDelegate::ShouldOpenDownload( content::DownloadItem* download, const content::DownloadOpenDelayedCallback& callback) { return true; } void AtomDownloadManagerDelegate::GetNextId( const content::DownloadIdCallback& callback) { static uint32_t next_id = content::DownloadItem::kInvalidId + 1; callback.Run(next_id++); } } // namespace atom
c++
code
7,029
1,228
// Copyright (c) 2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/moonet/topbar.h" #include "qt/moonet/forms/ui_topbar.h" #include <QPixmap> #include "qt/moonet/lockunlock.h" #include "qt/moonet/qtutils.h" #include "qt/moonet/receivedialog.h" #include "qt/moonet/defaultdialog.h" #include "askpassphrasedialog.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "qt/guiconstants.h" #include "qt/guiutil.h" #include "optionsmodel.h" #include "qt/platformstyle.h" #include "wallet/wallet.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "guiinterface.h" TopBar::TopBar(muuGUI* _mainWindow, QWidget *parent) : PWidget(_mainWindow, parent), ui(new Ui::TopBar) { ui->setupUi(this); // Set parent stylesheet this->setStyleSheet(_mainWindow->styleSheet()); /* Containers */ ui->containerTop->setProperty("cssClass", "container-top"); ui->containerTop->setContentsMargins(10,4,10,10); std::initializer_list<QWidget*> lblTitles = {ui->labelTitle1, ui->labelTitleLocked, ui->labelTitle2, ui->labelTitle3, ui->labelTitle4, ui->labelTitle5, ui->labelTitle6}; setCssProperty(lblTitles, "text-title-topbar"); QFont font; font.setWeight(QFont::Light); foreach (QWidget* w, lblTitles) { w->setFont(font); } // Amount information top ui->widgetTopAmount->setVisible(false); setCssProperty({ui->labelAmountTopPiv, ui->labelAmountTopzmuu}, "amount-small-topbar"); setCssProperty({ui->labelAmountPiv, ui->labelAmountzmuu}, "amount-topbar"); setCssProperty({ui->labelPendingPiv, ui->labelAmountPivLocked, ui->labelPendingzmuu, ui->labelImmaturePiv, ui->labelImmaturezmuu}, "amount-small-topbar"); // Progress Sync progressBar = new QProgressBar(ui->layoutSync); progressBar->setRange(1, 10); progressBar->setValue(4); progressBar->setTextVisible(false); progressBar->setMaximumHeight(2); progressBar->setMaximumWidth(36); setCssProperty(progressBar, "progress-sync"); progressBar->show(); progressBar->raise(); progressBar->move(0, 34); // New button ui->pushButtonFAQ->setButtonClassStyle("cssClass", "btn-check-faq"); ui->pushButtonFAQ->setButtonText("FAQ"); ui->pushButtonConnection->setButtonClassStyle("cssClass", "btn-check-connect-inactive"); ui->pushButtonConnection->setButtonText("No Connection"); ui->pushButtonStack->setButtonClassStyle("cssClass", "btn-check-stack-inactive"); ui->pushButtonStack->setButtonText("Staking Disabled"); ui->pushButtonMint->setButtonClassStyle("cssClass", "btn-check-mint-inactive"); ui->pushButtonMint->setButtonText("Automint Enabled"); ui->pushButtonMint->setVisible(false); ui->pushButtonSync->setButtonClassStyle("cssClass", "btn-check-sync"); ui->pushButtonSync->setButtonText(" %54 Synchronizing.."); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-lock"); if(isLightTheme()){ ui->pushButtonTheme->setButtonClassStyle("cssClass", "btn-check-theme-light"); ui->pushButtonTheme->setButtonText("Light Theme"); }else{ ui->pushButtonTheme->setButtonClassStyle("cssClass", "btn-check-theme-dark"); ui->pushButtonTheme->setButtonText("Dark Theme"); } setCssProperty(ui->qrContainer, "container-qr"); setCssProperty(ui->pushButtonQR, "btn-qr"); // QR image QPixmap pixmap("://img-qr-test"); ui->btnQr->setIcon( QIcon(pixmap.scaled( 70, 70, Qt::KeepAspectRatio)) ); ui->pushButtonLock->setButtonText("Wallet Locked "); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-status-lock"); connect(ui->pushButtonQR, SIGNAL(clicked()), this, SLOT(onBtnReceiveClicked())); connect(ui->btnQr, SIGNAL(clicked()), this, SLOT(onBtnReceiveClicked())); connect(ui->pushButtonLock, SIGNAL(Mouse_Pressed()), this, SLOT(onBtnLockClicked())); connect(ui->pushButtonTheme, SIGNAL(Mouse_Pressed()), this, SLOT(onThemeClicked())); connect(ui->pushButtonFAQ, SIGNAL(Mouse_Pressed()), _mainWindow, SLOT(openFAQ())); } void TopBar::onThemeClicked(){ // Store theme bool lightTheme = !isLightTheme(); setTheme(lightTheme); if(lightTheme){ ui->pushButtonTheme->setButtonClassStyle("cssClass", "btn-check-theme-light", true); ui->pushButtonTheme->setButtonText("Light Theme"); updateStyle(ui->pushButtonTheme); }else{ ui->pushButtonTheme->setButtonClassStyle("cssClass", "btn-check-theme-dark", true); ui->pushButtonTheme->setButtonText("Dark Theme"); updateStyle(ui->pushButtonTheme); } emit themeChanged(lightTheme); } void TopBar::onBtnLockClicked(){ if(walletModel) { if (walletModel->getEncryptionStatus() == WalletModel::Unencrypted) { encryptWallet(); } else { if (!lockUnlockWidget) { lockUnlockWidget = new LockUnlock(window); lockUnlockWidget->setStyleSheet("margin:0px; padding:0px;"); connect(lockUnlockWidget, SIGNAL(Mouse_Leave()), this, SLOT(lockDropdownMouseLeave())); connect(ui->pushButtonLock, &ExpandableButton::Mouse_HoverLeave, [this](){ QMetaObject::invokeMethod(this, "lockDropdownMouseLeave", Qt::QueuedConnection); }); //, SLOT(lockDropdownMouseLeave())); connect(lockUnlockWidget, SIGNAL(lockClicked( const StateClicked&)),this, SLOT(lockDropdownClicked( const StateClicked&))); } lockUnlockWidget->updateStatus(walletModel->getEncryptionStatus()); if (ui->pushButtonLock->width() <= 40) { ui->pushButtonLock->setExpanded(); } // Keep it open ui->pushButtonLock->setKeepExpanded(true); QMetaObject::invokeMethod(this, "openLockUnlock", Qt::QueuedConnection); } } } void TopBar::openLockUnlock(){ lockUnlockWidget->setFixedWidth(ui->pushButtonLock->width()); lockUnlockWidget->adjustSize(); lockUnlockWidget->move( ui->pushButtonLock->pos().rx() + window->getNavWidth() + 10, ui->pushButtonLock->y() + 36 ); lockUnlockWidget->raise(); lockUnlockWidget->activateWindow(); lockUnlockWidget->show(); } void TopBar::encryptWallet() { if (!walletModel) return; showHideOp(true); DefaultDialog *confirmDialog = new DefaultDialog(window); confirmDialog->setText( tr("Encrypting your wallet"), tr("Make sure to encrypt your wallet, to avoid losing funds in case the wallet is accessed by a malicious thrid party. Someone can access the wallet via malware, or directly if they have access to your PC. Wallet encryption prevents other users from accessing your funds. Also, make sure to have downloaded the wallet from https://muugreen.org to prevent you using a \"Fake-wallet\"."), tr("OK")); confirmDialog->adjustSize(); openDialogWithOpaqueBackground(confirmDialog, window); bool ret = confirmDialog->isOk; confirmDialog->deleteLater(); if (ret) { AskPassphraseDialog *dlg = new AskPassphraseDialog(AskPassphraseDialog::Mode::Encrypt, window, walletModel, AskPassphraseDialog::Context::Encrypt); dlg->adjustSize(); openDialogWithOpaqueBackgroundY(dlg, window); refreshStatus(); dlg->deleteLater(); } } WalletModel::EncryptionStatus TopBar::getEncryptionStatus() { return walletModel->getEncryptionStatus(); } static bool isExecuting = false; void TopBar::lockDropdownClicked(const StateClicked& state){ lockUnlockWidget->close(); if(walletModel && !isExecuting) { isExecuting = true; switch (lockUnlockWidget->lock) { case 0: { if (walletModel->getEncryptionStatus() == WalletModel::Locked) break; walletModel->setWalletLocked(true); ui->pushButtonLock->setButtonText("Wallet Locked"); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-status-lock", true); break; } case 1: { if (walletModel->getEncryptionStatus() == WalletModel::Unlocked) break; showHideOp(true); AskPassphraseDialog *dlg = new AskPassphraseDialog(AskPassphraseDialog::Mode::Unlock, window, walletModel, AskPassphraseDialog::Context::ToggleLock); dlg->adjustSize(); openDialogWithOpaqueBackgroundY(dlg, window); if (this->walletModel->getEncryptionStatus() == WalletModel::Unlocked) { ui->pushButtonLock->setButtonText("Wallet Unlocked"); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-status-unlock", true); } dlg->deleteLater(); break; } case 2: { if (walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly) break; showHideOp(true); AskPassphraseDialog *dlg = new AskPassphraseDialog(AskPassphraseDialog::Mode::UnlockAnonymize, window, walletModel, AskPassphraseDialog::Context::ToggleLock); dlg->adjustSize(); openDialogWithOpaqueBackgroundY(dlg, window); if (this->walletModel->getEncryptionStatus() == WalletModel::UnlockedForAnonymizationOnly) { ui->pushButtonLock->setButtonText(tr("Wallet Unlocked for staking")); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-status-staking", true); } dlg->deleteLater(); break; } } ui->pushButtonLock->setKeepExpanded(false); ui->pushButtonLock->setSmall(); ui->pushButtonLock->update(); isExecuting = false; } } void TopBar::lockDropdownMouseLeave(){ if (lockUnlockWidget->isVisible() && !lockUnlockWidget->isHovered()) { lockUnlockWidget->hide(); ui->pushButtonLock->setKeepExpanded(false); ui->pushButtonLock->setSmall(); ui->pushButtonLock->update(); } } void TopBar::onBtnReceiveClicked(){ if(walletModel) { showHideOp(true); ReceiveDialog *receiveDialog = new ReceiveDialog(window); receiveDialog->updateQr(walletModel->getAddressTableModel()->getLastUnusedAddress()); if (openDialogWithOpaqueBackground(receiveDialog, window)) { inform(tr("Address Copied")); } receiveDialog->deleteLater(); } } void TopBar::showTop(){ if(ui->bottom_container->isVisible()){ ui->bottom_container->setVisible(false); ui->widgetTopAmount->setVisible(true); this->setFixedHeight(75); } } void TopBar::showBottom(){ ui->widgetTopAmount->setVisible(false); ui->bottom_container->setVisible(true); this->setFixedHeight(200); this->adjustSize(); } TopBar::~TopBar(){ if(timerStakingIcon){ timerStakingIcon->stop(); } delete ui; } void TopBar::loadClientModel(){ if(clientModel){ // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks()); connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int))); timerStakingIcon = new QTimer(ui->pushButtonStack); connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingStatus())); timerStakingIcon->start(50000); updateStakingStatus(); } } void TopBar::updateAutoMintStatus(){ ui->pushButtonMint->setButtonText(fEnableZeromint ? tr("Automint enabled") : tr("Automint disabled")); ui->pushButtonMint->setChecked(fEnableZeromint); } void TopBar::updateStakingStatus(){ if (nLastCoinStakeSearchInterval) { if (!ui->pushButtonStack->isChecked()) { ui->pushButtonStack->setButtonText(tr("Staking active")); ui->pushButtonStack->setChecked(true); ui->pushButtonStack->setButtonClassStyle("cssClass", "btn-check-stack", true); } }else{ if (ui->pushButtonStack->isChecked()) { ui->pushButtonStack->setButtonText(tr("Staking not active")); ui->pushButtonStack->setChecked(false); ui->pushButtonStack->setButtonClassStyle("cssClass", "btn-check-stack-inactive", true); } } } void TopBar::setNumConnections(int count) { if(count > 0){ if(!ui->pushButtonConnection->isChecked()) { ui->pushButtonConnection->setChecked(true); ui->pushButtonConnection->setButtonClassStyle("cssClass", "btn-check-connect", true); } }else{ if(ui->pushButtonConnection->isChecked()) { ui->pushButtonConnection->setChecked(false); ui->pushButtonConnection->setButtonClassStyle("cssClass", "btn-check-connect-inactive", true); } } ui->pushButtonConnection->setButtonText(tr("%n active connection(s)", "", count)); } void TopBar::setNumBlocks(int count) { if (!clientModel) return; // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); std::string text = ""; switch (blockSource) { case BLOCK_SOURCE_NETWORK: text = "Synchronizing.."; break; case BLOCK_SOURCE_DISK: text = "Importing blocks from disk.."; break; case BLOCK_SOURCE_REINDEX: text = "Reindexing blocks on disk.."; break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection text = "No block source available.."; ui->pushButtonSync->setChecked(false); break; } bool needState = true; if (masternodeSync.IsBlockchainSynced()) { // chain synced emit walletSynced(true); if (masternodeSync.IsSynced()) { // Node synced // TODO: Set synced icon to pushButtonSync here.. ui->pushButtonSync->setButtonText(tr("Synchronized")); progressBar->setRange(0,100); progressBar->setValue(100); return; }else{ // TODO: Show out of sync warning int nAttempt = masternodeSync.RequestedMasternodeAttempt < MASTERNODE_SYNC_THRESHOLD ? masternodeSync.RequestedMasternodeAttempt + 1 : MASTERNODE_SYNC_THRESHOLD; int progress = nAttempt + (masternodeSync.RequestedMasternodeAssets - 1) * MASTERNODE_SYNC_THRESHOLD; if(progress >= 0){ // todo: MN progress.. text = std::string("Synchronizing additional data..");//: %p%", progress); //progressBar->setMaximum(4 * MASTERNODE_SYNC_THRESHOLD); //progressBar->setValue(progress); needState = false; } } } else { emit walletSynced(false); } if(needState) { // Represent time from last generated block in human readable text QDateTime lastBlockDate = clientModel->getLastBlockDate(); QDateTime currentDate = QDateTime::currentDateTime(); int secs = lastBlockDate.secsTo(currentDate); QString timeBehindText; const int HOUR_IN_SECONDS = 60 * 60; const int DAY_IN_SECONDS = 24 * 60 * 60; const int WEEK_IN_SECONDS = 7 * 24 * 60 * 60; const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar if (secs < 2 * DAY_IN_SECONDS) { timeBehindText = tr("%n hour(s)", "", secs / HOUR_IN_SECONDS); } else if (secs < 2 * WEEK_IN_SECONDS) { timeBehindText = tr("%n day(s)", "", secs / DAY_IN_SECONDS); } else if (secs < YEAR_IN_SECONDS) { timeBehindText = tr("%n week(s)", "", secs / WEEK_IN_SECONDS); } else { int years = secs / YEAR_IN_SECONDS; int remainder = secs % YEAR_IN_SECONDS; timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg( tr("%n week(s)", "", remainder / WEEK_IN_SECONDS)); } QString timeBehind(" behind. Scanning block "); QString str = timeBehindText + timeBehind + QString::number(count); text = str.toStdString(); progressBar->setMaximum(1000000000); progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5); } if(text.empty()){ text = "No block source available.."; } ui->pushButtonSync->setButtonText(tr(text.data())); } void TopBar::loadWalletModel(){ connect(walletModel, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(updateBalances(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); connect(walletModel, &WalletModel::encryptionStatusChanged, this, &TopBar::refreshStatus); // update the display unit, to not use the default ("moonet") updateDisplayUnit(); refreshStatus(); } void TopBar::refreshStatus(){ // Check lock status if (!this->walletModel) return; WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); switch (encStatus){ case WalletModel::EncryptionStatus::Unencrypted: ui->pushButtonLock->setButtonText("Wallet Unencrypted"); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-status-unlock", true); break; case WalletModel::EncryptionStatus::Locked: ui->pushButtonLock->setButtonText("Wallet Locked"); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-status-lock", true); break; case WalletModel::EncryptionStatus::UnlockedForAnonymizationOnly: ui->pushButtonLock->setButtonText("Wallet Unlocked for staking"); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-status-staking", true); break; case WalletModel::EncryptionStatus::Unlocked: ui->pushButtonLock->setButtonText("Wallet Unlocked"); ui->pushButtonLock->setButtonClassStyle("cssClass", "btn-check-status-unlock", true); break; } updateStyle(ui->pushButtonLock); } void TopBar::updateDisplayUnit() { if (walletModel && walletModel->getOptionsModel()) { int displayUnitPrev = nDisplayUnit; nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit(); if (displayUnitPrev != nDisplayUnit) updateBalances(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); } } void TopBar::updateBalances(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZeroc
c++
code
20,000
3,963
/** FILE : rtconly_mode.cpp PROJECT : AUTHOR : DESCRITION : */ #include "rtconly_mode.h" #include "global.h" #include "peripheral.h" void rtcOnlyProc() { // static uint32_t tickMs = millis(); // if(millis() - tickMs >= 2000){ // tickMs = millis(); // struct tm tmstruct; // getLocalTime(&tmstruct); // if(tmstruct.tm_year > 100){ // // When valid time condition, checking time condition // uint32_t current_time = tmstruct.tm_hour * 3600 + tmstruct.tm_min * 60 + tmstruct.tm_sec; // uint32_t wakeup_time = config.segments[tmstruct.tm_wday].wakehour * 3600 // + config.segments[tmstruct.tm_wday].wakemin * 60 + config.segments[tmstruct.tm_wday].wakesec; // uint32_t sleep_time = config.segments[tmstruct.tm_wday].sleephour * 3600 // + config.segments[tmstruct.tm_wday].sleepmin * 60 + config.segments[tmstruct.tm_wday].sleepsec; // debugA("Current: %d-%02d-%02d %02d:%02d:%02d\r\n", tmstruct.tm_year + 1900, tmstruct.tm_mon + 1, tmstruct.tm_mday, // tmstruct.tm_hour, tmstruct.tm_min, tmstruct.tm_sec); // debugA("Wakeup: %02d:%02d:%02d, Sleep: %02d:%02d:%02d\r\n", config.segments[tmstruct.tm_wday].wakehour, // config.segments[tmstruct.tm_wday].wakemin, config.segments[tmstruct.tm_wday].wakesec, // config.segments[tmstruct.tm_wday].sleephour, config.segments[tmstruct.tm_wday].sleepsec, // config.segments[tmstruct.tm_wday].sleepmin); // if(sleep_time > wakeup_time){ // if((current_time >= sleep_time) || (current_time < wakeup_time)){ // rtcOnlySleep(); // } // } // else{ // if((current_time > sleep_time) && (current_time < wakeup_time)){ // rtcOnlySleep(); // } // } // } // else{ // rtcOnlySleep(); // } // } } void rtcOnlySleep(uint32_t seconds) { digitalWrite(POWER_12V, HIGH); delay(100); gpio_hold_en((gpio_num_t)POWER_12V); gpio_deep_sleep_hold_en(); delay(100); debugA("Will sleep mode \r\n"); esp_sleep_enable_timer_wakeup(seconds * uS_TO_S_FACTOR); esp_sleep_enable_ext0_wakeup(GPIO_NUM_33, 1); //1 = High, 0 = Low esp_deep_sleep_start(); }
c++
code
2,342
419
//===- LLVMDialect.cpp - LLVM IR Ops and Dialect registration -------------===// // // Copyright 2019 The MLIR Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= // // This file defines the types and operation details for the LLVM IR dialect in // MLIR, and the LLVM IR dialect. It also registers the dialect. // //===----------------------------------------------------------------------===// #include "mlir/LLVMIR/LLVMDialect.h" #include "mlir/IR/Builders.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/StandardTypes.h" #include "llvm/AsmParser/Parser.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/Function.h" #include "llvm/IR/Type.h" #include "llvm/Support/SourceMgr.h" using namespace mlir; using namespace mlir::LLVM; namespace mlir { namespace LLVM { namespace detail { struct LLVMTypeStorage : public ::mlir::TypeStorage { LLVMTypeStorage(llvm::Type *ty) : underlyingType(ty) {} // LLVM types are pointer-unique. using KeyTy = llvm::Type *; bool operator==(const KeyTy &key) const { return key == underlyingType; } static LLVMTypeStorage *construct(TypeStorageAllocator &allocator, llvm::Type *ty) { return new (allocator.allocate<LLVMTypeStorage>()) LLVMTypeStorage(ty); } llvm::Type *underlyingType; }; } // end namespace detail } // end namespace LLVM } // end namespace mlir LLVMType LLVMType::get(MLIRContext *context, llvm::Type *llvmType) { return Base::get(context, FIRST_LLVM_TYPE, llvmType); } llvm::Type *LLVMType::getUnderlyingType() const { return getImpl()->underlyingType; } static void printLLVMBinaryOp(OpAsmPrinter *p, Operation *op) { // Fallback to the generic form if the op is not well-formed (may happen // during incomplete rewrites, and used for debugging). const auto *abstract = op->getAbstractOperation(); (void)abstract; assert(abstract && "pretty printing an unregistered operation"); auto resultType = op->getResult(0)->getType(); if (resultType != op->getOperand(0)->getType() || resultType != op->getOperand(1)->getType()) return p->printGenericOp(op); *p << op->getName().getStringRef() << ' ' << *op->getOperand(0) << ", " << *op->getOperand(1); p->printOptionalAttrDict(op->getAttrs()); *p << " : " << op->getResult(0)->getType(); } //===----------------------------------------------------------------------===// // Printing/parsing for LLVM::ICmpOp. //===----------------------------------------------------------------------===// // Return an array of mnemonics for ICmpPredicates indexed by its value. static const char *const *getICmpPredicateNames() { static const char *predicateNames[]{/*EQ*/ "eq", /*NE*/ "ne", /*SLT*/ "slt", /*SLE*/ "sle", /*SGT*/ "sgt", /*SGE*/ "sge", /*ULT*/ "ult", /*ULE*/ "ule", /*UGT*/ "ugt", /*UGE*/ "uge"}; return predicateNames; } // Returns a value of the ICmp predicate corresponding to the given mnemonic. // Returns -1 if there is no such mnemonic. static int getICmpPredicateByName(StringRef name) { return llvm::StringSwitch<int>(name) .Case("eq", 0) .Case("ne", 1) .Case("slt", 2) .Case("sle", 3) .Case("sgt", 4) .Case("sge", 5) .Case("ult", 6) .Case("ule", 7) .Case("ugt", 8) .Case("uge", 9) .Default(-1); } static void printICmpOp(OpAsmPrinter *p, ICmpOp &op) { *p << op.getOperationName() << " \"" << getICmpPredicateNames()[op.predicate().getZExtValue()] << "\" " << *op.getOperand(0) << ", " << *op.getOperand(1); p->printOptionalAttrDict(op.getAttrs(), {"predicate"}); *p << " : " << op.lhs()->getType(); } // <operation> ::= `llvm.icmp` string-literal ssa-use `,` ssa-use // attribute-dict? `:` type static ParseResult parseICmpOp(OpAsmParser *parser, OperationState *result) { Builder &builder = parser->getBuilder(); Attribute predicate; SmallVector<NamedAttribute, 4> attrs; OpAsmParser::OperandType lhs, rhs; Type type; llvm::SMLoc predicateLoc, trailingTypeLoc; if (parser->getCurrentLocation(&predicateLoc) || parser->parseAttribute(predicate, "predicate", attrs) || parser->parseOperand(lhs) || parser->parseComma() || parser->parseOperand(rhs) || parser->parseOptionalAttributeDict(attrs) || parser->parseColon() || parser->getCurrentLocation(&trailingTypeLoc) || parser->parseType(type) || parser->resolveOperand(lhs, type, result->operands) || parser->resolveOperand(rhs, type, result->operands)) return failure(); // Replace the string attribute `predicate` with an integer attribute. auto predicateStr = predicate.dyn_cast<StringAttr>(); if (!predicateStr) return parser->emitError(predicateLoc, "expected 'predicate' attribute of string type"); int predicateValue = getICmpPredicateByName(predicateStr.getValue()); if (predicateValue == -1) return parser->emitError(predicateLoc) << "'" << predicateStr.getValue() << "' is an incorrect value of the 'predicate' attribute"; attrs[0].second = parser->getBuilder().getI64IntegerAttr(predicateValue); // The result type is either i1 or a vector type <? x i1> if the inputs are // vectors. LLVMDialect *dialect = static_cast<LLVMDialect *>( builder.getContext()->getRegisteredDialect("llvm")); llvm::Type *llvmResultType = llvm::Type::getInt1Ty(dialect->getLLVMContext()); auto argType = type.dyn_cast<LLVM::LLVMType>(); if (!argType) return parser->emitError(trailingTypeLoc, "expected LLVM IR dialect type"); if (argType.getUnderlyingType()->isVectorTy()) llvmResultType = llvm::VectorType::get( llvmResultType, argType.getUnderlyingType()->getVectorNumElements()); auto resultType = builder.getType<LLVM::LLVMType>(llvmResultType); result->attributes = attrs; result->addTypes({resultType}); return success(); } //===----------------------------------------------------------------------===// // Printing/parsing for LLVM::AllocaOp. //===----------------------------------------------------------------------===// static void printAllocaOp(OpAsmPrinter *p, AllocaOp &op) { auto *llvmPtrTy = op.getType().cast<LLVM::LLVMType>().getUnderlyingType(); auto *llvmElemTy = llvm::cast<llvm::PointerType>(llvmPtrTy)->getElementType(); auto elemTy = LLVM::LLVMType::get(op.getContext(), llvmElemTy); auto funcTy = FunctionType::get({op.arraySize()->getType()}, {op.getType()}, op.getContext()); *p << op.getOperationName() << ' ' << *op.arraySize() << " x " << elemTy; p->printOptionalAttrDict(op.getAttrs()); *p << " : " << funcTy; } // <operation> ::= `llvm.alloca` ssa-use `x` type attribute-dict? // `:` type `,` type static ParseResult parseAllocaOp(OpAsmParser *parser, OperationState *result) { SmallVector<NamedAttribute, 4> attrs; OpAsmParser::OperandType arraySize; Type type, elemType; llvm::SMLoc trailingTypeLoc; if (parser->parseOperand(arraySize) || parser->parseKeyword("x") || parser->parseType(elemType) || parser->parseOptionalAttributeDict(attrs) || parser->parseColon() || parser->getCurrentLocation(&trailingTypeLoc) || parser->parseType(type)) return failure(); // Extract the result type from the trailing function type. auto funcType = type.dyn_cast<FunctionType>(); if (!funcType || funcType.getNumInputs() != 1 || funcType.getNumResults() != 1) return parser->emitError( trailingTypeLoc, "expected trailing function type with one argument and one result"); if (parser->resolveOperand(arraySize, funcType.getInput(0), result->operands)) return failure(); result->attributes = attrs; result->addTypes({funcType.getResult(0)}); return success(); } //===----------------------------------------------------------------------===// // Printing/parsing for LLVM::GEPOp. //===----------------------------------------------------------------------===// static void printGEPOp(OpAsmPrinter *p, GEPOp &op) { SmallVector<Type, 8> types; for (auto *operand : op.getOperands()) types.push_back(operand->getType()); auto funcTy = FunctionType::get(types, op.getResult()->getType(), op.getContext()); *p << op.getOperationName() << ' ' << *op.base() << '['; p->printOperands(std::next(op.operand_begin()), op.operand_end()); *p << ']'; p->printOptionalAttrDict(op.getAttrs()); *p << " : " << funcTy; } // <operation> ::= `llvm.getelementptr` ssa-use `[` ssa-use-list `]` // attribute-dict? `:` type static ParseResult parseGEPOp(OpAsmParser *parser, OperationState *result) { SmallVector<NamedAttribute, 4> attrs; OpAsmParser::OperandType base; SmallVector<OpAsmParser::OperandType, 8> indices; Type type; llvm::SMLoc trailingTypeLoc; if (parser->parseOperand(base) || parser->parseOperandList(indices, /*requiredOperandCount=*/-1, OpAsmParser::Delimiter::Square) || parser->parseOptionalAttributeDict(attrs) || parser->parseColon() || parser->getCurrentLocation(&trailingTypeLoc) || parser->parseType(type)) return failure(); // Deconstruct the trailing function type to extract the types of the base // pointer and result (same type) and the types of the indices. auto funcType = type.dyn_cast<FunctionType>(); if (!funcType || funcType.getNumResults() != 1 || funcType.getNumInputs() == 0) return parser->emitError(trailingTypeLoc, "expected trailing function type with at least " "one argument and one result"); if (parser->resolveOperand(base, funcType.getInput(0), result->operands) || parser->resolveOperands(indices, funcType.getInputs().drop_front(), parser->getNameLoc(), result->operands)) return failure(); result->attributes = attrs; result->addTypes(funcType.getResults()); return success(); } //===----------------------------------------------------------------------===// // Printing/parsing for LLVM::LoadOp. //===----------------------------------------------------------------------===// static void printLoadOp(OpAsmPrinter *p, LoadOp &op) { *p << op.getOperationName() << ' ' << *op.addr(); p->printOptionalAttrDict(op.getAttrs()); *p << " : " << op.addr()->getType(); } // Extract the pointee type from the LLVM pointer type wrapped in MLIR. Return // the resulting type wrapped in MLIR, or nullptr on error. static Type getLoadStoreElementType(OpAsmParser *parser, Type type, llvm::SMLoc trailingTypeLoc) { auto llvmTy = type.dyn_cast<LLVM::LLVMType>(); if (!llvmTy) return parser->emitError(trailingTypeLoc, "expected LLVM IR dialect type"), nullptr; auto *llvmPtrTy = dyn_cast<llvm::PointerType>(llvmTy.getUnderlyingType()); if (!llvmPtrTy) return parser->emitError(trailingTypeLoc, "expected LLVM pointer type"), nullptr; auto elemTy = LLVM::LLVMType::get(parser->getBuilder().getContext(), llvmPtrTy->getElementType()); return elemTy; } // <operation> ::= `llvm.load` ssa-use attribute-dict? `:` type static ParseResult parseLoadOp(OpAsmParser *parser, OperationState *result) { SmallVector<NamedAttribute, 4> attrs; OpAsmParser::OperandType addr; Type type; llvm::SMLoc trailingTypeLoc; if (parser->parseOperand(addr) || parser->parseOptionalAttributeDict(attrs) || parser->parseColon() || parser->getCurrentLocation(&trailingTypeLoc) || parser->parseType(type) || parser->resolveOperand(addr, type, result->operands)) return failure(); Type elemTy = getLoadStoreElementType(parser, type, trailingTypeLoc); result->attributes = attrs; result->addTypes(elemTy); return success(); } //===----------------------------------------------------------------------===// // Printing/parsing for LLVM::StoreOp. //===----------------------------------------------------------------------===// static void printStoreOp(OpAsmPrinter *p, StoreOp &op) { *p << op.getOperationName() << ' ' << *op.value() << ", " << *op.addr(); p->printOptionalAttrDict(op.getAttrs()); *p << " : " << op.addr()->getType(); } // <operation> ::= `llvm.store` ssa-use `,` ssa-use attribute-dict? `:` type static ParseResult parseStoreOp(OpAsmParser *parser, OperationState *result) { SmallVector<NamedAttribute, 4> attrs; OpAsmParser::OperandType addr, value; Type type; llvm::SMLoc trailingTypeLoc; if (parser->parseOperand(value) || parser->parseComma() || parser->parseOperand(addr) || parser->parseOptionalAttributeDict(attrs) || parser->parseColon() || parser->getCurrentLocation(&trailingTypeLoc) || parser->parseType(type)) return failure(); Type elemTy = getLoadStoreElementType(parser, type, trailingTypeLoc); if (!elemTy) return failure(); if (parser->resolveOperand(value, elemTy, result->operands) || parser->resolveOperand(addr, type, result->operands)) return failure(); result->attributes = attrs; return success(); } //===----------------------------------------------------------------------===// // Printing/parsing for LLVM::BitcastOp. //===----------------------------------------------------------------------===// static void printBitcastOp(OpAsmPrinter *p, BitcastOp &op) { *p << op.getOperationName() << ' ' << *op.arg(); p->printOptionalAttrDict(op.getAttrs()); *p << " : " << op.arg()->getType() << " to " << op.getType(); } // <operation> ::= `llvm.bitcast` ssa-use attribute-dict? `:` type `to` type static ParseResult parseBitcastOp(OpAsmParser *parser, OperationState *result) { SmallVector<NamedAttribute, 4> attrs; OpAsmParser::OperandType arg; Type sourceType, type; if (parser->parseOperand(arg) || parser->parseOptionalAttributeDict(attrs) || parser->parseColonType(sourceType) || parser->parseKeyword("to") || parser->parseType(type) || parser->resolveOperand(arg, sourceType, result->operands)) return failure(); result->attributes = attrs; result->addTypes(type); return success(); } //===----------------------------------------------------------------------===// // Printing/parsing for LLVM::CallOp. //===----------------------------------------------------------------------===// static void printCallOp(OpAsmPrinter *p, CallOp &op) { auto callee = op.callee(); bool isDirect = callee.hasValue(); // Print the direct callee if present as a function attribute, or an indirect // callee (first operand) otherwise. *p << op.getOperationName() << ' '; if (isDirect) *p << '@' << callee.getValue()->getName().strref(); else *p << *op.getOperand(0); *p << '('; p->printOperands(std::next(op.operand_begin(), callee.hasValue() ? 0 : 1), op.operand_end()); *p << ')'; p->printOptionalAttrDict(op.getAttrs(), {"callee"}); if (isDirect) { *p << " : " << callee.getValue()->getType(); return; } // Reconstruct the function MLIR function type from LLVM function type, // and print it. auto operandType = op.getOperand(0)->getType().cast<LLVM::LLVMType>(); auto *llvmPtrType = dyn_cast<llvm::PointerType>(operandType.getUnderlyingType()); assert(llvmPtrType && "operand #0 must have LLVM pointer type for indirect calls"); auto *llvmType = dyn_cast<llvm::FunctionType>(llvmPtrType->getElementType()); assert(llvmType && "operand #0 must have LLVM Function pointer type for indirect calls"); auto *llvmResultType = llvmType->getReturnType(); SmallVector<Type, 1> resultTypes; if (!llvmResultType->isVoidTy()) resultTypes.push_back(LLVM::LLVMType::get(op.getContext(), llvmResultType)); SmallVector<Type, 8> argTypes; argTypes.reserve(llvmType->getNumParams()); for (int i = 0, e = llvmType->getNumParams(); i < e; ++i) argTypes.push_back( LLVM::LLVMType::get(op.getContext(), llvmType->getParamType(i))); *p << " : " << FunctionType::get(argTypes, resultTypes, op.getContext()); } // <operation> ::= `llvm.call` (function-id | ssa-use) `(` ssa-use-list `)` // attribute-dict? `:` function-type static ParseResult parseCallOp(OpAsmParser *parser, OperationState *result) { SmallVector<NamedAttribute, 4> attrs; SmallVector<OpAsmParser::OperandType, 8> operands; Type type; StringRef calleeName; llvm::SMLoc calleeLoc, trailingTypeLoc; // Parse an operand list that will, in practice, contain 0 or 1 operand. In // case of an indirect call, there will be 1 operand before `(`. In case of a // direct call, there will be no operands and the parser will stop at the // function identifier without complaining. if (parser->parseOperandList(operands)) return failure(); bool isDirect = operands.empty(); // Optionally parse a function identifier. if (isDirect) if (parser->parseFunctionName(calleeName, calleeLoc)) return failure(); if (parser->parseOperandList(operands, /*requiredOperandCount=*/-1, OpAsmParser::Delimiter::Paren) || parser->parseOptionalAttributeDict(attrs) || parser->parseColon() || parser->getCurrentLocation(&trailingTypeLoc) || parser->parseType(type)) return failure(); auto funcType = type.dyn_cast<FunctionType>(); if (!funcType) return parser->emitError(trailingTypeLoc, "expected function type"); if (isDirect) { // Add the direct callee as an Op attribute. Function *func; if (parser->resolveFunctionName(calleeName, funcType, calleeLoc, func)) return failure(); auto funcAttr = parser->getBuilder().getFunctionAttr(func); attrs.push_back(parser->getBuilder().getNamedAttr("callee", funcAttr)); // Make sure types match. if (parser->resolveOperands(operands, funcType.getInputs(), parser->getNameLoc(), result->operands)) return failure(); result->addTypes(funcType.getResults()); } else { // Construct the LLVM IR Dialect function type that the first operand // should match. if (funcType.getNumResults() > 1) return parser->emitError(trailingTypeLoc, "expected function with 0 or 1 result"); Builder &builder = parser->getBuilder(); auto *llvmDialect = static_cast<LLVM::LLVMDialect *>( builder.getContext()->getRegisteredDialect("llvm")); llvm::Type *llvmResultType; Type wrappedResultType; if (funcType.getNumResults() == 0) { llvmResultType = llvm::Type::getVoidTy(llvmDialect->getLLVMContext()); wrappedResultType = builder.getType<LLVM::LLVMType>(llvmResultType); } else { wrappedResultType = funcType.getResult(0); auto wrappedLLVMResultType = wrappedResultType.dyn_cast<LLVM::LLVMType>(); if (!wrappedLLVMResultType) return parser->emitError(trailingTypeLoc, "expected result to have LLVM type"); llvmResultType = wrappedLLVMResultType.getUnderlyingType(); } SmallVec
c++
code
20,000
4,981
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <cassert> #include <ctime> #include <sstream> #include <string> #include <fstream> #include <iomanip> #include <iostream> #include <limits> #include <vector> #include <cctype> #include <sys/stat.h> #include <stdexcept> #include "thrift/platform.h" #include "thrift/generate/t_oop_generator.h" using std::map; using std::ostream; using std::ostringstream; using std::setfill; using std::setw; using std::string; using std::stringstream; using std::vector; static const string endl = "\n"; // avoid ostream << std::endl flushes /** * Java code generator. * */ class t_java_generator : public t_oop_generator { public: t_java_generator(t_program* program, const std::map<std::string, std::string>& parsed_options, const std::string& option_string) : t_oop_generator(program) { (void)option_string; std::map<std::string, std::string>::const_iterator iter; bean_style_ = false; android_style_ = false; private_members_ = false; nocamel_style_ = false; fullcamel_style_ = false; android_legacy_ = false; sorted_containers_ = false; java5_ = false; reuse_objects_ = false; use_option_type_ = false; undated_generated_annotations_ = false; suppress_generated_annotations_ = false; rethrow_unhandled_exceptions_ = false; unsafe_binaries_ = false; for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) { if( iter->first.compare("beans") == 0) { bean_style_ = true; } else if( iter->first.compare("android") == 0) { android_style_ = true; } else if( iter->first.compare("private-members") == 0) { private_members_ = true; } else if( iter->first.compare("nocamel") == 0) { nocamel_style_ = true; } else if( iter->first.compare("fullcamel") == 0) { fullcamel_style_ = true; } else if( iter->first.compare("android_legacy") == 0) { android_legacy_ = true; } else if( iter->first.compare("sorted_containers") == 0) { sorted_containers_ = true; } else if( iter->first.compare("java5") == 0) { java5_ = true; } else if( iter->first.compare("reuse-objects") == 0) { reuse_objects_ = true; } else if( iter->first.compare("option_type") == 0) { use_option_type_ = true; } else if( iter->first.compare("rethrow_unhandled_exceptions") == 0) { rethrow_unhandled_exceptions_ = true; } else if( iter->first.compare("generated_annotations") == 0) { if( iter->second.compare("undated") == 0) { undated_generated_annotations_ = true; } else if(iter->second.compare("suppress") == 0) { suppress_generated_annotations_ = true; } else { throw "unknown option java:" + iter->first + "=" + iter->second; } } else if( iter->first.compare("unsafe_binaries") == 0) { unsafe_binaries_ = true; } else { throw "unknown option java:" + iter->first; } } if (java5_) { android_legacy_ = true; } out_dir_base_ = (bean_style_ ? "gen-javabean" : "gen-java"); } /** * Init and close methods */ void init_generator() override; void close_generator() override; void generate_consts(std::vector<t_const*> consts) override; /** * Program-level generation functions */ void generate_typedef(t_typedef* ttypedef) override; void generate_enum(t_enum* tenum) override; void generate_struct(t_struct* tstruct) override; void generate_union(t_struct* tunion); void generate_xception(t_struct* txception) override; void generate_service(t_service* tservice) override; void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value, bool in_static, bool defval = false); std::string render_const_value(std::ostream& out, t_type* type, t_const_value* value); /** * Service-level generation functions */ void generate_java_struct(t_struct* tstruct, bool is_exception); void generate_java_struct_definition(std::ostream& out, t_struct* tstruct, bool is_xception = false, bool in_class = false, bool is_result = false); void generate_java_struct_parcelable(std::ostream& out, t_struct* tstruct); void generate_java_struct_equality(std::ostream& out, t_struct* tstruct); void generate_java_struct_compare_to(std::ostream& out, t_struct* tstruct); void generate_java_struct_reader(std::ostream& out, t_struct* tstruct); void generate_java_validator(std::ostream& out, t_struct* tstruct); void generate_java_struct_result_writer(std::ostream& out, t_struct* tstruct); void generate_java_struct_writer(std::ostream& out, t_struct* tstruct); void generate_java_struct_tostring(std::ostream& out, t_struct* tstruct); void generate_java_struct_clear(std::ostream& out, t_struct* tstruct); void generate_java_struct_write_object(std::ostream& out, t_struct* tstruct); void generate_java_struct_read_object(std::ostream& out, t_struct* tstruct); void generate_java_meta_data_map(std::ostream& out, t_struct* tstruct); void generate_field_value_meta_data(std::ostream& out, t_type* type); std::string get_java_type_string(t_type* type); void generate_java_struct_field_by_id(ostream& out, t_struct* tstruct); void generate_java_struct_get_fields(ostream& out); void generate_java_struct_get_metadata(ostream& out); void generate_reflection_setters(std::ostringstream& out, t_type* type, std::string field_name, std::string cap_name); void generate_reflection_getters(std::ostringstream& out, t_type* type, std::string field_name, std::string cap_name); void generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct); void generate_generic_isset_method(std::ostream& out, t_struct* tstruct); void generate_java_bean_boilerplate(std::ostream& out, t_struct* tstruct); void generate_function_helpers(t_function* tfunction); std::string as_camel_case(std::string name, bool ucfirst = true); std::string get_rpc_method_name(std::string name); std::string get_cap_name(std::string name); std::string generate_isset_check(t_field* field); std::string generate_isset_check(std::string field); void generate_isset_set(ostream& out, t_field* field, std::string prefix); std::string isset_field_id(t_field* field); void generate_service_interface(t_service* tservice); void generate_service_async_interface(t_service* tservice); void generate_service_helpers(t_service* tservice); void generate_service_client(t_service* tservice); void generate_service_async_client(t_service* tservice); void generate_service_server(t_service* tservice); void generate_service_async_server(t_service* tservice); void generate_process_function(t_service* tservice, t_function* tfunction); void generate_process_async_function(t_service* tservice, t_function* tfunction); void generate_java_union(t_struct* tstruct); void generate_union_constructor(ostream& out, t_struct* tstruct); void generate_union_getters_and_setters(ostream& out, t_struct* tstruct); void generate_union_is_set_methods(ostream& out, t_struct* tstruct); void generate_union_abstract_methods(ostream& out, t_struct* tstruct); void generate_check_type(ostream& out, t_struct* tstruct); void generate_standard_scheme_read_value(ostream& out, t_struct* tstruct); void generate_standard_scheme_write_value(ostream& out, t_struct* tstruct); void generate_tuple_scheme_read_value(ostream& out, t_struct* tstruct); void generate_tuple_scheme_write_value(ostream& out, t_struct* tstruct); void generate_get_field_desc(ostream& out, t_struct* tstruct); void generate_get_struct_desc(ostream& out, t_struct* tstruct); void generate_get_field_name(ostream& out, t_struct* tstruct); void generate_union_comparisons(ostream& out, t_struct* tstruct); void generate_union_hashcode(ostream& out, t_struct* tstruct); void generate_scheme_map(ostream& out, t_struct* tstruct); void generate_standard_writer(ostream& out, t_struct* tstruct, bool is_result); void generate_standard_reader(ostream& out, t_struct* tstruct); void generate_java_struct_standard_scheme(ostream& out, t_struct* tstruct, bool is_result); void generate_java_struct_tuple_scheme(ostream& out, t_struct* tstruct); void generate_java_struct_tuple_reader(ostream& out, t_struct* tstruct); void generate_java_struct_tuple_writer(ostream& out, t_struct* tstruct); void generate_java_scheme_lookup(ostream& out); void generate_javax_generated_annotation(ostream& out); /** * Serialization constructs */ void generate_deserialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool has_metadata = true); void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = "", bool has_metadata = true); void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = "", std::string obj = "", bool has_metadata = true); void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = "", std::string obj = "", bool has_metadata = true); void generate_deserialize_list_element(std::ostream& out, t_list* tlist, std::string prefix = "", std::string obj = "", bool has_metadata = true); void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = "", bool has_metadata = true); void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = ""); void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = "", bool has_metadata = true); void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter, std::string map, bool has_metadata = true); void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter, bool has_metadata = true); void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter, bool has_metadata = true); void generate_deep_copy_container(std::ostream& out, std::string source_name_p1, std::string source_name_p2, std::string result_name, t_type* type); void generate_deep_copy_non_container(std::ostream& out, std::string source_name, std::string dest_name, t_type* type); enum isset_type { ISSET_NONE, ISSET_PRIMITIVE, ISSET_BITSET }; isset_type needs_isset(t_struct* tstruct, std::string* outPrimitiveType = nullptr); /** * Helper rendering functions */ std::string java_package(); std::string java_suppressions(); std::string java_nullable_annotation(); std::string type_name(t_type* ttype, bool in_container = false, bool in_init = false, bool skip_generic = false, bool force_namespace = false); std::string base_type_name(t_base_type* tbase, bool in_container = false); std::string declare_field(t_field* tfield, bool init = false, bool comment = false); std::string function_signature(t_function* tfunction, std::string prefix = ""); std::string function_signature_async(t_function* tfunction, bool use_base_method = false, std::string prefix = ""); std::string argument_list(t_struct* tstruct, bool include_types = true); std::string async_function_call_arglist(t_function* tfunc, bool use_base_method = true, bool include_types = true); std::string async_argument_list(t_function* tfunct, t_struct* tstruct, t_type* ttype, bool include_types = false); std::string type_to_enum(t_type* ttype); void generate_struct_desc(ostream& out, t_struct* tstruct); void generate_field_descs(ostream& out, t_struct* tstruct); void generate_field_name_constants(ostream& out, t_struct* tstruct); std::string make_valid_java_filename(std::string const& fromName); std::string make_valid_java_identifier(std::string const& fromName); std::string make_java_service_name_fix(std::string const& srvName); t_type* get_leaf_type_in_typedef(t_typedef* t_tdef) { if (t_tdef->get_type()->is_typedef()) { return get_leaf_type_in_typedef((t_typedef*) t_tdef->get_type()); } return t_tdef->get_type(); } bool type_can_be_null(t_type* ttype) { ttype = get_true_type(ttype); return ttype->is_container() || ttype->is_struct() || ttype->is_xception() || ttype->is_string() || ttype->is_enum(); } bool is_deprecated(const std::map<std::string, std::string>& annotations) { return annotations.find("deprecated") != annotations.end(); } bool is_enum_set(t_type* ttype) { if (!sorted_containers_) { ttype = get_true_type(ttype); if (ttype->is_set()) { t_set* tset = (t_set*)ttype; t_type* elem_type = get_true_type(tset->get_elem_type()); return elem_type->is_enum(); } } return false; } bool is_enum_map(t_type* ttype) { if (!sorted_containers_) { ttype = get_true_type(ttype); if (ttype->is_map()) { t_map* tmap = (t_map*)ttype; t_type* key_type = get_true_type(tmap->get_key_type()); return key_type->is_enum(); } } return false; } std::string inner_enum_type_name(t_type* ttype) { ttype = get_true_type(ttype); if (ttype->is_map()) { t_map* tmap = (t_map*)ttype; t_type* key_type = get_true_type(tmap->get_key_type()); return type_name(key_type, true) + ".class"; } else if (ttype->is_set()) { t_set* tset = (t_set*)ttype; t_type* elem_type = get_true_type(tset->get_elem_type()); return type_name(elem_type, true) + ".class"; } return ""; } std::string constant_name(std::string name); private: /** * File streams */ std::string package_name_; ofstream_with_content_based_conditional_update f_service_; std::string package_dir_; bool bean_style_; bool android_style_; bool private_members_; bool nocamel_style_; bool fullcamel_style_; bool android_legacy_; bool java5_; bool sorted_containers_; bool reuse_objects_; bool use_option_type_; bool undated_generated_annotations_; bool suppress_generated_annotations_; bool rethrow_unhandled_exceptions_; bool unsafe_binaries_; }; /** * Prepares for file generation by opening up the necessary file output * streams. * * @param tprogram The program to generate */ void t_java_generator::init_generator() { // Make output directory MKDIR(get_out_dir().c_str()); package_name_ = program_->get_namespace("java"); string dir = package_name_; string subdir = get_out_dir(); string::size_type loc; while ((loc = dir.find(".")) != string::npos) { subdir = subdir + "/" + dir.substr(0, loc); MKDIR(subdir.c_str()); dir = dir.substr(loc + 1); } if (dir.size() > 0) { subdir = subdir + "/" + dir; MKDIR(subdir.c_str()); } package_dir_ = subdir; } /** * Packages the generated file * * @return String of the package, i.e. "package org.apache.thriftdemo;" */ string t_java_generator::java_package() { if (!package_name_.empty()) { return string("package ") + package_name_ + ";\n\n"; } return ""; } string t_java_generator::java_suppressions() { return "@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\", \"unused\"})\n"; } string t_java_generator::java_nullable_annotation() { return "@org.apache.thrift.annotation.Nullable"; } /** * Nothing in Java */ void t_java_generator::close_generator() { } /** * Generates a typedef. This is not done in Java, since it does * not support arbitrary name replacements, and it'd be a wacky waste * of overhead to make wrapper classes. * * @param ttypedef The type definition */ void t_java_generator::generate_typedef(t_typedef* ttypedef) { (void)ttypedef; } /** * Enums are a class with a set of static constants. * * @param tenum The enumeration */ void t_java_generator::generate_enum(t_enum* tenum) { bool is_deprecated = this->is_deprecated(tenum->annotations_); // Make output file string f_enum_name = package_dir_ + "/" + make_valid_java_filename(tenum->get_name()) + ".java"; ofstream_with_content_based_conditional_update f_enum; f_enum.open(f_enum_name.c_str()); // Comment and package it f_enum << autogen_comment() << java_package() << endl; generate_java_doc(f_enum, tenum); if (!suppress_generated_annotations_) { generate_javax_generated_annotation(f_enum); } if (is_deprecated) { indent(f_enum) << "@Deprecated" << endl; } indent(f_enum) << "public enum " << tenum->get_name() << " implements org.apache.thrift.TEnum "; scope_up(f_enum); vector<t_enum_value*> constants = tenum->get_constants(); vector<t_enum_value*>::iterator c_iter; bool first = true; for (c_iter = constants.begin(); c_iter != constants.end();
c++
code
19,999
3,715
#include "Torch.h" #include "SFML\Graphics\RenderTarget.hpp" #include "Tile.h" #include "Material.h" #include <iostream> #include "Logger.h" #include "Chunk.h" #include "GameObject.h" #include "ObjectManager.h" #include "World.h" Torch::Torch(int pWidth, int pHeight) { mComplete = false; mWidth = pWidth; mHeight = pHeight; } Torch::~Torch() { delete[] mTilesInRange; } void Torch::update(float dt) { if (!mDead) { processNeighbors(mWidth >> 1, mHeight >> 1, 7.f); } } void Torch::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(*mSprite); } void Torch::smoothLight(int pX, int pY) { /*if (pX == 0 || pX == (mWidth - 1) || pY == 0 || pY == (mHeight - 1)) return; // Tile we are smoothing Tile *c = mTilesInRange[pY * mWidth + pX]; if (c == nullptr) return; int x_min_1 = pX - 1; int x_plus_1 = pX + 1; int y_min_1 = pY - 1; int y_plus_1 = pY + 1; // Get all nearby tiles in all 8 weather directions Tile *NW = mTilesInRange[y_min_1 * mWidth + x_min_1]; Tile *N = mTilesInRange[y_min_1 * mWidth + pX]; Tile *NE = mTilesInRange[y_min_1 * mWidth + x_plus_1]; Tile *E = mTilesInRange[pY * mWidth + x_plus_1]; Tile *SW = mTilesInRange[y_plus_1 * mWidth + x_min_1]; Tile *S = mTilesInRange[y_plus_1 * mWidth + pX]; Tile *SE = mTilesInRange[y_plus_1 * mWidth + x_plus_1]; Tile *W = mTilesInRange[pY * mWidth + x_min_1]; for (int i = 0; i < 4; i++) { int intensitySum = 0; // This is really ugly but I can't come up with a better algorithm if (i == 0) // upper left { intensitySum += c->getQuad()[0].color.a; // me intensitySum += N->getQuad()[3].color.a; intensitySum += NW->getQuad()[2].color.a; intensitySum += W->getQuad()[1].color.a; int alpha = intensitySum / 4; c->getQuad()[0].color.a = alpha; } else if (i == 1) // upper right { intensitySum += c->getQuad()[1].color.a; // me intensitySum += N->getQuad()[2].color.a; intensitySum += NE->getQuad()[3].color.a; intensitySum += E->getQuad()[0].color.a; int alpha = intensitySum / 4; c->getQuad()[1].color.a = alpha; } else if (i == 2) // lower left { intensitySum += c->getQuad()[2].color.a; // me intensitySum += E->getQuad()[3].color.a; intensitySum += SE->getQuad()[0].color.a; intensitySum += S->getQuad()[1].color.a; int alpha = intensitySum / 4; c->getQuad()[2].color.a = alpha; } else if (i == 3) // lower right { intensitySum += c->getQuad()[3].color.a; // me intensitySum += S->getQuad()[0].color.a; intensitySum += SW->getQuad()[1].color.a; intensitySum += W->getQuad()[2].color.a; int alpha = intensitySum / 4; c->getQuad()[3].color.a = alpha; } }*/ } void Torch::processNeighbors(int pX, int pY, float pIntensity) { Tile* current = mTilesInRange[pY * mWidth + pX]; current->setLightIntensity(pIntensity); float newIntensity = pIntensity - 1.f; if (newIntensity <= 0.f) { return; } int x_min_1 = pX - 1; int x_plus_1 = pX + 1; int y_min_1 = pY - 1; int y_plus_1 = pY + 1; Tile *N = mTilesInRange[y_min_1 * mWidth + pX]; // North Tile *E = mTilesInRange[pY * mWidth + x_plus_1]; // East Tile *S = mTilesInRange[y_plus_1 * mWidth + pX]; // South Tile *W = mTilesInRange[pY * mWidth + x_min_1]; // West int northIntensity = newIntensity; if (N->getMaterial()->isCollidable()) { northIntensity -= 1; } if (N != nullptr && N->getIntensity() <= northIntensity) { N->setLightIntensity(northIntensity); processNeighbors(pX, y_min_1, northIntensity); } int eastIntensity = newIntensity; if (E->getMaterial()->isCollidable()) { eastIntensity -= 1; } if (E != nullptr && E->getIntensity() <= eastIntensity) { E->setLightIntensity(eastIntensity); processNeighbors(x_plus_1, pY, eastIntensity); } int southIntensity = newIntensity; if (S->getMaterial()->isCollidable()) { southIntensity -= 1; } if (S != nullptr && S->getIntensity() <= southIntensity) { S->setLightIntensity(southIntensity); processNeighbors(pX, y_plus_1, southIntensity); } int westIntensity = newIntensity; if (W->getMaterial()->isCollidable()) { westIntensity -= 1; } if (W != nullptr && W->getIntensity() <= westIntensity) { W->setLightIntensity(westIntensity); processNeighbors(x_min_1, pY, westIntensity); } } void Torch::setTile(Tile *pTile) { mTile = pTile; // Allocate space for tiles mTilesInRange = new Tile*[(mWidth * mHeight)]; // Set default value of nullptr for (int i = 0; i < (mWidth * mHeight); i++) { mTilesInRange[i] = nullptr; } int width = mWidth; if (!(mWidth & 1)) { width--; } int height = mHeight; if (!(mHeight & 1)) { height--; } // Gather affected tiles collectTiles(); } void Torch::lightsOff() { for (int i = 0; i < (mWidth * mHeight); i++) { if (mTilesInRange[i] != nullptr) { mTilesInRange[i]->setLightIntensity(0); } } } void Torch::collectTiles() { int cx = mWidth >> 1; int cy = mHeight >> 1; int row = 0; int column = 0; Chunk *centerChunk = mTile->getChunk(); for (int x = -cx; x < cx; x++) { row = 0; for (int y = -cy; y < cy; y++) { sf::Vector2f worldPos = mTile->getPosition() + sf::Vector2f(x, y); Tile *tile = mTile->getRelative(x, y); mTilesInRange[row * mWidth + column] = tile; row++; } column++; } }
c++
code
5,294
1,431
// // experimental/detail/channel_send_functions.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_FUNCTIONS_HPP #define BOOST_ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_FUNCTIONS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/experimental/detail/channel_message.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace experimental { namespace detail { template <typename Derived, typename Executor, typename... Signatures> class channel_send_functions; template <typename Derived, typename Executor, typename R, typename... Args> class channel_send_functions<Derived, Executor, R(Args...)> { public: template <typename... Args2> typename enable_if< is_constructible<detail::channel_message<R(Args...)>, int, Args2...>::value, bool >::type try_send(BOOST_ASIO_MOVE_ARG(Args2)... args) { typedef typename detail::channel_message<R(Args...)> message_type; Derived* self = static_cast<Derived*>(this); return self->service_->template try_send<message_type>( self->impl_, BOOST_ASIO_MOVE_CAST(Args2)(args)...); } template <typename... Args2> typename enable_if< is_constructible<detail::channel_message<R(Args...)>, int, Args2...>::value, std::size_t >::type try_send_n(std::size_t count, BOOST_ASIO_MOVE_ARG(Args2)... args) { typedef typename detail::channel_message<R(Args...)> message_type; Derived* self = static_cast<Derived*>(this); return self->service_->template try_send_n<message_type>( self->impl_, count, BOOST_ASIO_MOVE_CAST(Args2)(args)...); } template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) CompletionToken BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)> auto async_send(Args... args, BOOST_ASIO_MOVE_ARG(CompletionToken) token BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(Executor)) { typedef typename Derived::payload_type payload_type; typedef typename detail::channel_message<R(Args...)> message_type; Derived* self = static_cast<Derived*>(this); return async_initiate<CompletionToken, void (boost::system::error_code)>( typename Derived::initiate_async_send(self), token, payload_type(message_type(0, BOOST_ASIO_MOVE_CAST(Args)(args)...))); } }; template <typename Derived, typename Executor, typename R, typename... Args, typename... Signatures> class channel_send_functions<Derived, Executor, R(Args...), Signatures...> : public channel_send_functions<Derived, Executor, Signatures...> { public: using channel_send_functions<Derived, Executor, Signatures...>::try_send; using channel_send_functions<Derived, Executor, Signatures...>::async_send; template <typename... Args2> typename enable_if< is_constructible<detail::channel_message<R(Args...)>, int, Args2...>::value, bool >::type try_send(BOOST_ASIO_MOVE_ARG(Args2)... args) { typedef typename detail::channel_message<R(Args...)> message_type; Derived* self = static_cast<Derived*>(this); return self->service_->template try_send<message_type>( self->impl_, BOOST_ASIO_MOVE_CAST(Args2)(args)...); } template <typename... Args2> typename enable_if< is_constructible<detail::channel_message<R(Args...)>, int, Args2...>::value, std::size_t >::type try_send_n(std::size_t count, BOOST_ASIO_MOVE_ARG(Args2)... args) { typedef typename detail::channel_message<R(Args...)> message_type; Derived* self = static_cast<Derived*>(this); return self->service_->template try_send_n<message_type>( self->impl_, count, BOOST_ASIO_MOVE_CAST(Args2)(args)...); } template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) CompletionToken BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)> auto async_send(Args... args, BOOST_ASIO_MOVE_ARG(CompletionToken) token BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(Executor)) { typedef typename Derived::payload_type payload_type; typedef typename detail::channel_message<R(Args...)> message_type; Derived* self = static_cast<Derived*>(this); return async_initiate<CompletionToken, void (boost::system::error_code)>( typename Derived::initiate_async_send(self), token, payload_type(message_type(0, BOOST_ASIO_MOVE_CAST(Args)(args)...))); } }; } // namespace detail } // namespace experimental } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_EXPERIMENTAL_DETAIL_CHANNEL_SEND_FUNCTIONS_HPP
c++
code
5,032
1,037
#pragma once #include "ParallelPort.hpp" #include "Utility.hpp" struct IVideoSink; class DisplayGenerator : public RestProvider { public: public: struct DMARequest { uint64_t tick; uint16_t address; explicit operator bool() const { return tick != 0; } }; DisplayGenerator( std::shared_ptr<IVideoSink> videoSink ); ~DisplayGenerator() override = default; void dispCtl( bool dispColor, bool dispFlip, bool dmaEnable ); void setPBKUP( uint8_t value ); void firstHblank( uint64_t tick, uint8_t hbackup ); DMARequest hblank( uint64_t tick, int row ); DMARequest pushData( uint64_t tick, uint64_t data ); void updatePalette( uint64_t tick, uint8_t reg, uint8_t value ); void updateDispAddr( uint64_t tick, uint16_t dispAdr ); void vblank( uint64_t tick ); bool rest() const override; private: bool flushDisplay( uint64_t tick ); private: std::array<uint64_t,10> mDMAData; std::shared_ptr<IVideoSink> mVideoSink; uint64_t mRowStartTick; uint32_t mDMAIteration; int32_t mDisplayRow; uint32_t mEmitedScreenBytes; uint16_t mDispAdr; bool mDispColor; bool mDispFlip; bool mDMAEnable; int mDMAOffset; static constexpr uint64_t DMA_ITERATIONS = 10; static constexpr uint64_t TICKS_PER_PIXEL = 12; static constexpr uint64_t TICKS_PER_BYTE = TICKS_PER_PIXEL * 2; static constexpr uint64_t ROW_TICKS = TICKS_PER_PIXEL * SCREEN_WIDTH; };
c++
code
1,422
250
/***************************************************************** | | AP4 - data Atom | | Copyright 2002 Gilles Boccon-Gibod & Julien Boeuf | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL is free software; you can redistribute it and/or modify | it under the terms of the GNU General Public License as published by | the Free Software Foundation; either version 2, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4.h" #include "Ap4DataAtom.h" /*---------------------------------------------------------------------- | AP4_DataAtom::AP4_DataAtom +---------------------------------------------------------------------*/ AP4_DataAtom::AP4_DataAtom(AP4_Size size, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_DATA) { size -= AP4_ATOM_HEADER_SIZE; stream.ReadUI32(m_DataType); stream.ReadUI32(m_Reserved); size -= 8; m_Data.SetDataSize(size); stream.Read(m_Data.UseData(), size); }
c++
code
1,852
555
#include "StdAfx.h" #include "TransformPlus.h" #include<cstring> #include<sstream> TransformPlus::TransformPlus(void) { } TransformPlus::~TransformPlus(void) { } //CString CString TransformPlus::toCString(string str) { CString cstr(str.c_str()); return cstr; } CString TransformPlus::toCString(double dbl) { CString t; t.Format(_T("%f"), dbl); return t; } CString TransformPlus::toCString(int i) { CString t; t.Format(_T("%d"), i); return t; } //String string TransformPlus::toString(CString cstr) { string str = (CStringA)cstr; return str; } string TransformPlus::toString(double dbl) { char buffer[20]; sprintf_s(buffer, "%f", dbl); string str = buffer; /*stringstream ss; string buffer; ss << dbl; ss >> buffer;*/ return buffer; } string TransformPlus::toString(int i) { stringstream ss; string str; ss << i; ss >> str; return str; } string TransformPlus::toString(char* c) { string s(c); return s; } //double double TransformPlus::toDouble(CString cstr) { return _wtof(cstr); /*string str = (CStringA)cstr; return atof(str.c_str());*/ } double TransformPlus::toDouble(string str) { double value = atof(str.c_str()); return value; } double TransformPlus::toDouble(int i) { double dbl = (double)i; return dbl; } //int int TransformPlus::toInt(CString cstr) { int i = _ttoi(cstr); return i; } int TransformPlus::toInt(string str) { int n = atoi(str.c_str()); return n; } int TransformPlus::toInt(double dbl) { int i = (int)dbl; return i; }
c++
code
1,498
416
#include "envoy/buffer/buffer.h" #include "envoy/event/file_event.h" #include "common/buffer/buffer_impl.h" #include "common/common/fancy_logger.h" #include "common/network/address_impl.h" #include "extensions/io_socket/user_space/io_handle_impl.h" #include "test/mocks/event/mocks.h" #include "absl/container/fixed_array.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::NiceMock; namespace Envoy { namespace Extensions { namespace IoSocket { namespace UserSpace { namespace { MATCHER(IsInvalidAddress, "") { return arg.err_->getErrorCode() == Api::IoError::IoErrorCode::NoSupport; } MATCHER(IsNotSupportedResult, "") { return arg.errno_ == SOCKET_ERROR_NOT_SUP; } ABSL_MUST_USE_RESULT std::pair<Buffer::Slice, Buffer::RawSlice> allocateOneSlice(uint64_t size) { Buffer::Slice mutable_slice(size, nullptr); auto slice = mutable_slice.reserve(size); EXPECT_NE(nullptr, slice.mem_); EXPECT_EQ(size, slice.len_); return {std::move(mutable_slice), slice}; } class MockFileEventCallback { public: MOCK_METHOD(void, called, (uint32_t arg)); }; class IoHandleImplTest : public testing::Test { public: IoHandleImplTest() : buf_(1024) { std::tie(io_handle_, io_handle_peer_) = IoHandleFactory::createIoHandlePair(); } NiceMock<Event::MockDispatcher> dispatcher_; // Owned by IoHandleImpl. NiceMock<Event::MockSchedulableCallback>* schedulable_cb_; MockFileEventCallback cb_; std::unique_ptr<IoHandleImpl> io_handle_; std::unique_ptr<IoHandleImpl> io_handle_peer_; absl::FixedArray<char> buf_; }; // Test recv side effects. TEST_F(IoHandleImplTest, BasicRecv) { Buffer::OwnedImpl buf_to_write("0123456789"); io_handle_peer_->write(buf_to_write); { auto result = io_handle_->recv(buf_.data(), buf_.size(), 0); ASSERT_EQ(10, result.rc_); ASSERT_EQ("0123456789", absl::string_view(buf_.data(), result.rc_)); } { auto result = io_handle_->recv(buf_.data(), buf_.size(), 0); // `EAGAIN`. EXPECT_FALSE(result.ok()); EXPECT_EQ(Api::IoError::IoErrorCode::Again, result.err_->getErrorCode()); } { io_handle_->setWriteEnd(); auto result = io_handle_->recv(buf_.data(), buf_.size(), 0); EXPECT_TRUE(result.ok()); } } // Test recv side effects. TEST_F(IoHandleImplTest, RecvPeek) { Buffer::OwnedImpl buf_to_write("0123456789"); io_handle_peer_->write(buf_to_write); { ::memset(buf_.data(), 1, buf_.size()); auto result = io_handle_->recv(buf_.data(), 5, MSG_PEEK); ASSERT_EQ(5, result.rc_); ASSERT_EQ("01234", absl::string_view(buf_.data(), result.rc_)); // The data beyond the boundary is untouched. ASSERT_EQ(std::string(buf_.size() - 5, 1), absl::string_view(buf_.data() + 5, buf_.size() - 5)); } { auto result = io_handle_->recv(buf_.data(), buf_.size(), MSG_PEEK); ASSERT_EQ(10, result.rc_); ASSERT_EQ("0123456789", absl::string_view(buf_.data(), result.rc_)); } { // Drain the pending buffer. auto recv_result = io_handle_->recv(buf_.data(), buf_.size(), 0); EXPECT_TRUE(recv_result.ok()); EXPECT_EQ(10, recv_result.rc_); ASSERT_EQ("0123456789", absl::string_view(buf_.data(), recv_result.rc_)); auto peek_result = io_handle_->recv(buf_.data(), buf_.size(), 0); // `EAGAIN`. EXPECT_FALSE(peek_result.ok()); EXPECT_EQ(Api::IoError::IoErrorCode::Again, peek_result.err_->getErrorCode()); } { // Peek upon shutdown. io_handle_->setWriteEnd(); auto result = io_handle_->recv(buf_.data(), buf_.size(), MSG_PEEK); EXPECT_EQ(0, result.rc_); ASSERT(result.ok()); } } TEST_F(IoHandleImplTest, RecvPeekWhenPendingDataButShutdown) { Buffer::OwnedImpl buf_to_write("0123456789"); io_handle_peer_->write(buf_to_write); auto result = io_handle_->recv(buf_.data(), buf_.size(), MSG_PEEK); ASSERT_EQ(10, result.rc_); ASSERT_EQ("0123456789", absl::string_view(buf_.data(), result.rc_)); } TEST_F(IoHandleImplTest, MultipleRecvDrain) { Buffer::OwnedImpl buf_to_write("abcd"); io_handle_peer_->write(buf_to_write); { auto result = io_handle_->recv(buf_.data(), 1, 0); EXPECT_TRUE(result.ok()); EXPECT_EQ(1, result.rc_); EXPECT_EQ("a", absl::string_view(buf_.data(), 1)); } { auto result = io_handle_->recv(buf_.data(), buf_.size(), 0); EXPECT_TRUE(result.ok()); EXPECT_EQ(3, result.rc_); EXPECT_EQ("bcd", absl::string_view(buf_.data(), 3)); EXPECT_EQ(0, io_handle_->getWriteBuffer()->length()); } } // Test read side effects. TEST_F(IoHandleImplTest, ReadEmpty) { Buffer::OwnedImpl buf; auto result = io_handle_->read(buf, 10); EXPECT_FALSE(result.ok()); EXPECT_EQ(Api::IoError::IoErrorCode::Again, result.err_->getErrorCode()); io_handle_->setWriteEnd(); result = io_handle_->read(buf, 10); EXPECT_TRUE(result.ok()); EXPECT_EQ(0, result.rc_); } // Read allows max_length value 0 and returns no error. TEST_F(IoHandleImplTest, ReadWhileProvidingNoCapacity) { Buffer::OwnedImpl buf; absl::optional<uint64_t> max_length_opt{0}; auto result = io_handle_->read(buf, max_length_opt); EXPECT_TRUE(result.ok()); EXPECT_EQ(0, result.rc_); } // Test read side effects. TEST_F(IoHandleImplTest, ReadContent) { Buffer::OwnedImpl buf_to_write("abcdefg"); io_handle_peer_->write(buf_to_write); Buffer::OwnedImpl buf; auto result = io_handle_->read(buf, 3); EXPECT_TRUE(result.ok()); EXPECT_EQ(3, result.rc_); ASSERT_EQ(3, buf.length()); ASSERT_EQ(4, io_handle_->getWriteBuffer()->length()); result = io_handle_->read(buf, 10); EXPECT_TRUE(result.ok()); EXPECT_EQ(4, result.rc_); ASSERT_EQ(7, buf.length()); ASSERT_EQ(0, io_handle_->getWriteBuffer()->length()); } // Test read throttling on watermark buffer. TEST_F(IoHandleImplTest, ReadThrottling) { { // Prepare data to read. Buffer::OwnedImpl buf_to_write(std::string(13 * FRAGMENT_SIZE, 'a')); while (buf_to_write.length() > 0) { io_handle_peer_->write(buf_to_write); } } Buffer::OwnedImpl unlimited_buf; { // Read at most 8 * FRAGMENT_SIZE to unlimited buffer. auto result0 = io_handle_->read(unlimited_buf, absl::nullopt); EXPECT_TRUE(result0.ok()); EXPECT_EQ(result0.rc_, 8 * FRAGMENT_SIZE); EXPECT_EQ(unlimited_buf.length(), 8 * FRAGMENT_SIZE); EXPECT_EQ(unlimited_buf.toString(), std::string(8 * FRAGMENT_SIZE, 'a')); } Buffer::WatermarkBuffer buf([]() {}, []() {}, []() {}); buf.setWatermarks(FRAGMENT_SIZE + 1); { // Verify that read() populates the buf to high watermark. auto result = io_handle_->read(buf, 8 * FRAGMENT_SIZE + 1); EXPECT_TRUE(result.ok()); EXPECT_EQ(result.rc_, FRAGMENT_SIZE + 1); EXPECT_EQ(buf.length(), FRAGMENT_SIZE + 1); EXPECT_FALSE(buf.highWatermarkTriggered()); EXPECT_EQ(buf.toString(), std::string(FRAGMENT_SIZE + 1, 'a')); } { // Verify that read returns FRAGMENT_SIZE if the buf is over high watermark. auto result1 = io_handle_->read(buf, 8 * FRAGMENT_SIZE + 1); EXPECT_TRUE(result1.ok()); EXPECT_EQ(result1.rc_, FRAGMENT_SIZE); EXPECT_EQ(buf.length(), 2 * FRAGMENT_SIZE + 1); EXPECT_TRUE(buf.highWatermarkTriggered()); EXPECT_EQ(buf.toString(), std::string(2 * FRAGMENT_SIZE + 1, 'a')); } { // Verify that read() returns FRAGMENT_SIZE bytes if the prepared buf is 1 byte away from high // watermark. The buf highWatermarkTriggered is true before the read. buf.drain(FRAGMENT_SIZE + 1); EXPECT_EQ(buf.length(), buf.highWatermark() - 1); EXPECT_TRUE(buf.highWatermarkTriggered()); auto result2 = io_handle_->read(buf, 8 * FRAGMENT_SIZE + 1); EXPECT_TRUE(result2.ok()); EXPECT_EQ(result2.rc_, FRAGMENT_SIZE); EXPECT_TRUE(buf.highWatermarkTriggered()); EXPECT_EQ(buf.toString(), std::string(buf.highWatermark() - 1 + FRAGMENT_SIZE, 'a')); } { // Verify that read() returns FRAGMENT_SIZE bytes if the prepared buf is 1 byte away from high // watermark. The buf highWatermarkTriggered is false before the read. buf.drain(buf.length()); buf.add(std::string(buf.highWatermark() - 1, 'a')); EXPECT_EQ(buf.length(), buf.highWatermark() - 1); // Buffer is populated from below low watermark to high watermark - 1, so the high watermark is // not triggered yet. EXPECT_FALSE(buf.highWatermarkTriggered()); auto result3 = io_handle_->read(buf, 8 * FRAGMENT_SIZE + 1); EXPECT_TRUE(result3.ok()); EXPECT_EQ(result3.rc_, FRAGMENT_SIZE); EXPECT_TRUE(buf.highWatermarkTriggered()); EXPECT_EQ(buf.toString(), std::string(buf.highWatermark() - 1 + FRAGMENT_SIZE, 'a')); } } // Test readv behavior. TEST_F(IoHandleImplTest, BasicReadv) { Buffer::OwnedImpl buf_to_write("abc"); io_handle_peer_->write(buf_to_write); Buffer::OwnedImpl buf; auto reservation = buf.reserveSingleSlice(1024); auto slice = reservation.slice(); auto result = io_handle_->readv(1024, &slice, 1); EXPECT_TRUE(result.ok()); EXPECT_EQ(3, result.rc_); result = io_handle_->readv(1024, &slice, 1); EXPECT_FALSE(result.ok()); EXPECT_EQ(Api::IoError::IoErrorCode::Again, result.err_->getErrorCode()); io_handle_->setWriteEnd(); result = io_handle_->readv(1024, &slice, 1); // EOF EXPECT_TRUE(result.ok()); EXPECT_EQ(0, result.rc_); } // Test readv on slices. TEST_F(IoHandleImplTest, ReadvMultiSlices) { Buffer::OwnedImpl buf_to_write(std::string(1024, 'a')); io_handle_peer_->write(buf_to_write); char full_frag[1024]; Buffer::RawSlice slices[2] = {{full_frag, 512}, {full_frag + 512, 512}}; auto result = io_handle_->readv(1024, slices, 2); EXPECT_EQ(absl::string_view(full_frag, 1024), std::string(1024, 'a')); EXPECT_TRUE(result.ok()); EXPECT_EQ(1024, result.rc_); } TEST_F(IoHandleImplTest, FlowControl) { io_handle_->setWatermarks(128); EXPECT_FALSE(io_handle_->isReadable()); EXPECT_TRUE(io_handle_->isWritable()); // Populate the data for io_handle_. Buffer::OwnedImpl buffer(std::string(256, 'a')); io_handle_peer_->write(buffer); EXPECT_TRUE(io_handle_->isReadable()); EXPECT_FALSE(io_handle_->isWritable()); bool writable_flipped = false; // During the repeated recv, the writable flag must switch to true. auto& internal_buffer = *io_handle_->getWriteBuffer(); while (internal_buffer.length() > 0) { SCOPED_TRACE(internal_buffer.length()); FANCY_LOG(debug, "internal buffer length = {}", internal_buffer.length()); EXPECT_TRUE(io_handle_->isReadable()); bool writable = io_handle_->isWritable(); FANCY_LOG(debug, "internal buffer length = {}, writable = {}", internal_buffer.length(), writable); if (writable) { writable_flipped = true; } else { ASSERT_FALSE(writable_flipped); } auto result = io_handle_->recv(buf_.data(), 32, 0); EXPECT_TRUE(result.ok()); EXPECT_EQ(32, result.rc_); } ASSERT_EQ(0, internal_buffer.length()); ASSERT_TRUE(writable_flipped); // Finally the buffer is empty. EXPECT_FALSE(io_handle_->isReadable()); EXPECT_TRUE(io_handle_->isWritable()); } // Consistent with other IoHandle: allow write empty data when handle is closed. TEST_F(IoHandleImplTest, NoErrorWriteZeroDataToClosedIoHandle) { io_handle_->close(); { Buffer::OwnedImpl buf; auto result = io_handle_->write(buf); ASSERT_EQ(0, result.rc_); ASSERT(result.ok()); } { Buffer::RawSlice slice{nullptr, 0}; auto result = io_handle_->writev(&slice, 1); ASSERT_EQ(0, result.rc_); ASSERT(result.ok()); } } TEST_F(IoHandleImplTest, ErrorOnClosedIoHandle) { io_handle_->close(); { auto [guard, slice] = allocateOneSlice(1024); auto result = io_handle_->recv(slice.mem_, slice.len_, 0); ASSERT(!result.ok()); ASSERT_EQ(Api::IoError::IoErrorCode::BadFd, result.err_->getErrorCode()); } { Buffer::OwnedImpl buf; auto result = io_handle_->read(buf, 10); ASSERT(!result.ok()); ASSERT_EQ(Api::IoError::IoErrorCode::BadFd, result.err_->getErrorCode()); } { auto [guard, slice] = allocateOneSlice(1024); auto result = io_handle_->readv(1024, &slice, 1); ASSERT(!result.ok()); ASSERT_EQ(Api::IoError::IoErrorCode::BadFd, result.err_->getErrorCode()); } { Buffer::OwnedImpl buf("0123456789"); auto result = io_handle_->write(buf); ASSERT(!result.ok()); ASSERT_EQ(Api::IoError::IoErrorCode::BadFd, result.err_->getErrorCode()); } { Buffer::OwnedImpl buf("0123456789"); auto slices = buf.getRawSlices(); ASSERT(!slices.empty()); auto result = io_handle_->writev(slices.data(), slices.size()); ASSERT(!result.ok()); ASSERT_EQ(Api::IoError::IoErrorCode::BadFd, result.err_->getErrorCode()); } } TEST_F(IoHandleImplTest, RepeatedShutdownWR) { EXPECT_EQ(io_handle_peer_->shutdown(ENVOY_SHUT_WR).rc_, 0); EXPECT_EQ(io_handle_peer_->shutdown(ENVOY_SHUT_WR).rc_, 0); } TEST_F(IoHandleImplTest, ShutDownOptionsNotSupported) { ASSERT_DEBUG_DEATH(io_handle_peer_->shutdown(ENVOY_SHUT_RD), ""); ASSERT_DEBUG_DEATH(io_handle_peer_->shutdown(ENVOY_SHUT_RDWR), ""); } TEST_F(IoHandleImplTest, WriteByMove) { Buffer::OwnedImpl buf("0123456789"); auto result = io_handle_peer_->write(buf); EXPECT_TRUE(result.ok()); EXPECT_EQ(10, result.rc_); EXPECT_EQ("0123456789", io_handle_->getWriteBuffer()->toString()); EXPECT_EQ(0, buf.length()); } // Test write return error code. Ignoring the side effect of event scheduling. TEST_F(IoHandleImplTest, WriteAgain) { // Populate write destination with massive data so as to not writable. io_handle_peer_->setWatermarks(128); Buffer::OwnedImpl pending_data(std::string(256, 'a')); io_handle_->write(pending_data); EXPECT_FALSE(io_handle_peer_->isWritable()); Buffer::OwnedImpl buf("0123456789"); auto result = io_handle_->write(buf); ASSERT_EQ(result.err_->getErrorCode(), Api::IoError::IoErrorCode::Again); EXPECT_EQ(10, buf.length()); } TEST_F(IoHandleImplTest, PartialWrite) { const uint64_t INITIAL_SIZE = 4 * FRAGMENT_SIZE; io_handle_peer_->setWatermarks(FRAGMENT_SIZE + 1); Buffer::OwnedImpl pending_data(std::string(INITIAL_SIZE, 'a')); { // Write until high watermark. The write bytes reaches high watermark value but high watermark // is not triggered. auto result = io_handle_->write(pending_data); EXPECT_TRUE(result.ok()); EXPECT_EQ(result.rc_, FRAGMENT_SIZE + 1); EXPECT_EQ(pending_data.length(), INITIAL_SIZE - (FRAGMENT_SIZE + 1)); EXPECT_TRUE(io_handle_peer_->isWritable()); EXPECT_EQ(io_handle_peer_->getWriteBuffer()->toString(), std::string(FRAGMENT_SIZE + 1, 'a')); } { // Write another fragment since when high watermark is reached. auto result1 = io_handle_->write(pending_data); EXPECT_TRUE(result1.ok()); EXPECT_EQ(result1.rc_, FRAGMENT_SIZE); EXPECT_EQ(pending_data.length(), INITIAL_SIZE - (FRAGMENT_SIZE + 1) - FRAGMENT_SIZE); EXPECT_FALSE(io_handle_peer_->isWritable()); EXPECT_EQ(io_handle_peer_->getWriteBuffer()->toString(), std::string(2 * FRAGMENT_SIZE + 1, 'a')); } { // Confirm that the further write return `EAGAIN`. auto result2 = io_handle_->write(pending_data); ASSERT_EQ(result2.err_->getErrorCode(), Api::IoError::IoErrorCode::Again); ASSERT_EQ(result2.rc_, 0); } { // Make the peer writable again. Buffer::OwnedImpl black_hole_buffer; auto result_drain = io_handle_peer_->read(black_hole_buffer, FRAGMENT_SIZE + FRAGMENT_SIZE / 2 + 2); ASSERT_EQ(result_drain.rc_, FRAGMENT_SIZE + FRAGMENT_SIZE / 2 + 2); EXPECT_TRUE(io_handle_peer_->isWritable()); } { // The buffer in peer is less than FRAGMENT_SIZE away from high watermark. Write a FRAGMENT_SIZE // anyway. auto len = io_handle_peer_->getWriteBuffer()->length(); EXPECT_LT(io_handle_peer_->getWriteBuffer()->highWatermark() - len, FRAGMENT_SIZE); EXPECT_GT(pending_data.length(), FRAGMENT_SIZE); auto result3 = io_handle_->write(pending_data); EXPECT_EQ(result3.rc_, FRAGMENT_SIZE); EXPECT_FALSE(io_handle_peer_->isWritable()); EXPECT_EQ(io_handle_peer_->getWriteBuffer()->toString(), std::string(len + FRAGMENT_SIZE, 'a')); } } TEST_F(IoHandleImplTest, WriteErrorAfterShutdown) { Buffer::OwnedImpl buf("0123456789"); // Write after shutdown. io_handle_->shutdown(ENVOY_SHUT_WR); auto result = io_handle_->write(buf); ASSERT_EQ(result.err_->getErrorCode(), Api::IoError::IoErrorCode::UnknownError); EXPECT_EQ(10, buf.length()); } TEST_F(IoHandleImplTest, WriteErrorAfterClose) { Buffer::OwnedImpl buf("0123456789"); io_handle_peer_->close(); EXPECT_TRUE(io_handle_->isOpen()); auto result = io_handle_->write(buf); ASSERT_EQ(result.err_->getErrorCode(), Api::IoError::IoErrorCode::UnknownError); } // Test writev return error code. Ignoring the side effect of event scheduling. TEST_F(IoHandleImplTest, WritevAgain) { Buffer::OwnedImpl buf_to_write(std::string(256, ' ')); io_handle_->write(buf_to_write); auto [guard, slice] = allocateOneSlice(128); io_handle_peer_->setWatermarks(128); auto result = io_handle_->writev(&slice, 1); ASSERT_EQ(result.err_->getErrorCode(), Api::IoError::IoErrorCode::Again); } TEST_F(IoHandleImplTest, PartialWritev) { io_handle_peer_->setWatermarks(128); Buffer::OwnedImpl pending_data("a"); auto long_frag = Buffer::OwnedBufferFragmentImpl::create( std::string(255, 'b'), [](const Buffer::OwnedBufferFragmentImpl* fragment) { delete fragment; }); auto tail_frag = Buffer::OwnedBufferFragmentImpl::create( "ccc", [](const Buffer::OwnedBufferFragmentImpl* fragment) { delete fragment; }); pending_data.addBufferFragment(*long_frag.release()); pending_data.addBufferFragment(*tail_frag.release()); // Partial write: the first two slices are moved because the second slice move reaches the high // watermark. auto slices = pending_data.getRawSlices(); EXPECT_EQ(3, slices.size()); auto result = io_handle_->writev(slices.data(), slices.size()); EXPECT_TRUE(result.ok()); EXPECT_EQ(result.rc_, 256); pending_data.drain(result.rc_); EXPECT_EQ(pending_data.length(), 3); EXPECT_FALSE(io_handle_peer_->isWritable()); // Confirm that the further write return `EAGAIN`. auto slices2 = pending_data.getRawSlices(); auto result2 = io_handle_->writev(slices2.data(), slices2.size()); ASSERT_EQ(result2.err_->getErrorCode(), Api::IoError::IoErrorCode::Again); // Make the peer writable again. Buffer::OwnedImpl black_hole_buffer; io_handle_peer_->read(black_hole_buffer, 10240); EXPECT_TRUE(io_handle_peer_->isWritable()); auto slices3 = pending_data.getRawSlices(); auto result3 = io_handle_->writev(slices3.data(), slices3.size()); EXPECT_EQ(result3.rc_, 3); pending_data.drain(result3.rc_); EXPECT_EQ(0, pending_data.length()); } TEST_F(IoHandleImplTest, WritevErrorAfterShutdown) { auto [guard, slice] = allocateOneSlice(128); // Writev after shutdown. io_handle_->shutdown(ENVOY_SHUT_WR); auto result = io_handle_->writev(&slice, 1); ASSERT_EQ(result.err_->getErrorCode(), Api::IoError::IoErrorCode::UnknownError); } TEST_F(IoHandleImplTest, WritevErrorAfterClose) { auto [guard, slice] = allocateOneSlice(1024); // Close the peer. io_handle_peer_->close(); EXPECT_TRUE(io_handle_->isOpen()); auto result = io_handle_->writev(&slice, 1); ASSERT_EQ(result.err_->getErrorCode(), Api::IoError::IoErrorCode::UnknownError); } TEST_F(IoHandleImplTest, WritevToPeer) { std::string raw_data("0123456789"); absl::InlinedVector<Buffer::RawSlice, 4> slices{ // Contains 1 byte. Buffer::RawSlice{static_cast<void*>(raw_data.data()), 1}, // Contains 0 byte. Buffer::RawSlice{nullptr, 1}, // Contains 0 byte. Buffer::RawSlice{raw_data.data() + 1, 0}, // Contains 2 byte. Buffer::RawSlice{raw_data.data() + 1, 2}, }; io_handle_peer_->writev(slices.data(), slices.size()); EXPECT_EQ(3, io_handle_->getWriteBuffer()->length()); EXPECT_EQ("012", io_handle_->getWriteBuffer
c++
code
20,000
5,007
// Copyright (c) 2016 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 "source/opt/set_spec_constant_default_value_pass.h" #include <algorithm> #include <cctype> #include <cstring> #include <tuple> #include <vector> #include "source/opt/def_use_manager.h" #include "source/opt/ir_context.h" #include "source/opt/make_unique.h" #include "source/opt/type_manager.h" #include "source/opt/types.h" #include "source/util/parse_number.h" #include "spirv-tools/libspirv.h" namespace spvtools { namespace opt { namespace { using utils::EncodeNumberStatus; using utils::NumberType; using utils::ParseAndEncodeNumber; using utils::ParseNumber; // Given a numeric value in a null-terminated c string and the expected type of // the value, parses the string and encodes it in a vector of words. If the // value is a scalar integer or floating point value, encodes the value in // SPIR-V encoding format. If the value is 'false' or 'true', returns a vector // with single word with value 0 or 1 respectively. Returns the vector // containing the encoded value on success. Otherwise returns an empty vector. std::vector<uint32_t> ParseDefaultValueStr(const char* text, const analysis::Type* type) { std::vector<uint32_t> result; if (!strcmp(text, "true") && type->AsBool()) { result.push_back(1u); } else if (!strcmp(text, "false") && type->AsBool()) { result.push_back(0u); } else { NumberType number_type = {32, SPV_NUMBER_UNSIGNED_INT}; if (const auto* IT = type->AsInteger()) { number_type.bitwidth = IT->width(); number_type.kind = IT->IsSigned() ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT; } else if (const auto* FT = type->AsFloat()) { number_type.bitwidth = FT->width(); number_type.kind = SPV_NUMBER_FLOATING; } else { // Does not handle types other then boolean, integer or float. Returns // empty vector. result.clear(); return result; } EncodeNumberStatus rc = ParseAndEncodeNumber( text, number_type, [&result](uint32_t word) { result.push_back(word); }, nullptr); // Clear the result vector on failure. if (rc != EncodeNumberStatus::kSuccess) { result.clear(); } } return result; } // Given a bit pattern and a type, checks if the bit pattern is compatible // with the type. If so, returns the bit pattern, otherwise returns an empty // bit pattern. If the given bit pattern is empty, returns an empty bit // pattern. If the given type represents a SPIR-V Boolean type, the bit pattern // to be returned is determined with the following standard: // If any words in the input bit pattern are non zero, returns a bit pattern // with 0x1, which represents a 'true'. // If all words in the bit pattern are zero, returns a bit pattern with 0x0, // which represents a 'false'. std::vector<uint32_t> ParseDefaultValueBitPattern( const std::vector<uint32_t>& input_bit_pattern, const analysis::Type* type) { std::vector<uint32_t> result; if (type->AsBool()) { if (std::any_of(input_bit_pattern.begin(), input_bit_pattern.end(), [](uint32_t i) { return i != 0; })) { result.push_back(1u); } else { result.push_back(0u); } return result; } else if (const auto* IT = type->AsInteger()) { if (IT->width() == input_bit_pattern.size() * sizeof(uint32_t) * 8) { return std::vector<uint32_t>(input_bit_pattern); } } else if (const auto* FT = type->AsFloat()) { if (FT->width() == input_bit_pattern.size() * sizeof(uint32_t) * 8) { return std::vector<uint32_t>(input_bit_pattern); } } result.clear(); return result; } // Returns true if the given instruction's result id could have a SpecId // decoration. bool CanHaveSpecIdDecoration(const Instruction& inst) { switch (inst.opcode()) { case SpvOp::SpvOpSpecConstant: case SpvOp::SpvOpSpecConstantFalse: case SpvOp::SpvOpSpecConstantTrue: return true; default: return false; } } // Given a decoration group defining instruction that is decorated with SpecId // decoration, finds the spec constant defining instruction which is the real // target of the SpecId decoration. Returns the spec constant defining // instruction if such an instruction is found, otherwise returns a nullptr. Instruction* GetSpecIdTargetFromDecorationGroup( const Instruction& decoration_group_defining_inst, analysis::DefUseManager* def_use_mgr) { // Find the OpGroupDecorate instruction which consumes the given decoration // group. Note that the given decoration group has SpecId decoration, which // is unique for different spec constants. So the decoration group cannot be // consumed by different OpGroupDecorate instructions. Therefore we only need // the first OpGroupDecoration instruction that uses the given decoration // group. Instruction* group_decorate_inst = nullptr; if (def_use_mgr->WhileEachUser(&decoration_group_defining_inst, [&group_decorate_inst](Instruction* user) { if (user->opcode() == SpvOp::SpvOpGroupDecorate) { group_decorate_inst = user; return false; } return true; })) return nullptr; // Scan through the target ids of the OpGroupDecorate instruction. There // should be only one spec constant target consumes the SpecId decoration. // If multiple target ids are presented in the OpGroupDecorate instruction, // they must be the same one that defined by an eligible spec constant // instruction. If the OpGroupDecorate instruction has different target ids // or a target id is not defined by an eligible spec cosntant instruction, // returns a nullptr. Instruction* target_inst = nullptr; for (uint32_t i = 1; i < group_decorate_inst->NumInOperands(); i++) { // All the operands of a OpGroupDecorate instruction should be of type // SPV_OPERAND_TYPE_ID. uint32_t candidate_id = group_decorate_inst->GetSingleWordInOperand(i); Instruction* candidate_inst = def_use_mgr->GetDef(candidate_id); if (!candidate_inst) { continue; } if (!target_inst) { // If the spec constant target has not been found yet, check if the // candidate instruction is the target. if (CanHaveSpecIdDecoration(*candidate_inst)) { target_inst = candidate_inst; } else { // Spec id decoration should not be applied on other instructions. // TODO(qining): Emit an error message in the invalid case once the // error handling is done. return nullptr; } } else { // If the spec constant target has been found, check if the candidate // instruction is the same one as the target. The module is invalid if // the candidate instruction is different with the found target. // TODO(qining): Emit an error messaage in the invalid case once the // error handling is done. if (candidate_inst != target_inst) return nullptr; } } return target_inst; } } // namespace Pass::Status SetSpecConstantDefaultValuePass::Process() { // The operand index of decoration target in an OpDecorate instruction. const uint32_t kTargetIdOperandIndex = 0; // The operand index of the decoration literal in an OpDecorate instruction. const uint32_t kDecorationOperandIndex = 1; // The operand index of Spec id literal value in an OpDecorate SpecId // instruction. const uint32_t kSpecIdLiteralOperandIndex = 2; // The number of operands in an OpDecorate SpecId instruction. const uint32_t kOpDecorateSpecIdNumOperands = 3; // The in-operand index of the default value in a OpSpecConstant instruction. const uint32_t kOpSpecConstantLiteralInOperandIndex = 0; bool modified = false; // Scan through all the annotation instructions to find 'OpDecorate SpecId' // instructions. Then extract the decoration target of those instructions. // The decoration targets should be spec constant defining instructions with // opcode: OpSpecConstant{|True|False}. The spec id of those spec constants // will be used to look up their new default values in the mapping from // spec id to new default value strings. Once a new default value string // is found for a spec id, the string will be parsed according to the target // spec constant type. The parsed value will be used to replace the original // default value of the target spec constant. for (Instruction& inst : context()->annotations()) { // Only process 'OpDecorate SpecId' instructions if (inst.opcode() != SpvOp::SpvOpDecorate) continue; if (inst.NumOperands() != kOpDecorateSpecIdNumOperands) continue; if (inst.GetSingleWordInOperand(kDecorationOperandIndex) != uint32_t(SpvDecoration::SpvDecorationSpecId)) { continue; } // 'inst' is an OpDecorate SpecId instruction. uint32_t spec_id = inst.GetSingleWordOperand(kSpecIdLiteralOperandIndex); uint32_t target_id = inst.GetSingleWordOperand(kTargetIdOperandIndex); // Find the spec constant defining instruction. Note that the // target_id might be a decoration group id. Instruction* spec_inst = nullptr; if (Instruction* target_inst = get_def_use_mgr()->GetDef(target_id)) { if (target_inst->opcode() == SpvOp::SpvOpDecorationGroup) { spec_inst = GetSpecIdTargetFromDecorationGroup(*target_inst, get_def_use_mgr()); } else { spec_inst = target_inst; } } else { continue; } if (!spec_inst) continue; // Get the default value bit pattern for this spec id. std::vector<uint32_t> bit_pattern; if (spec_id_to_value_str_.size() != 0) { // Search for the new string-form default value for this spec id. auto iter = spec_id_to_value_str_.find(spec_id); if (iter == spec_id_to_value_str_.end()) { continue; } // Gets the string of the default value and parses it to bit pattern // with the type of the spec constant. const std::string& default_value_str = iter->second; bit_pattern = ParseDefaultValueStr( default_value_str.c_str(), context()->get_type_mgr()->GetType(spec_inst->type_id())); } else { // Search for the new bit-pattern-form default value for this spec id. auto iter = spec_id_to_value_bit_pattern_.find(spec_id); if (iter == spec_id_to_value_bit_pattern_.end()) { continue; } // Gets the bit-pattern of the default value from the map directly. bit_pattern = ParseDefaultValueBitPattern( iter->second, context()->get_type_mgr()->GetType(spec_inst->type_id())); } if (bit_pattern.empty()) continue; // Update the operand bit patterns of the spec constant defining // instruction. switch (spec_inst->opcode()) { case SpvOp::SpvOpSpecConstant: // If the new value is the same with the original value, no // need to do anything. Otherwise update the operand words. if (spec_inst->GetInOperand(kOpSpecConstantLiteralInOperandIndex) .words != bit_pattern) { spec_inst->SetInOperand(kOpSpecConstantLiteralInOperandIndex, std::move(bit_pattern)); modified = true; } break; case SpvOp::SpvOpSpecConstantTrue: // If the new value is also 'true', no need to change anything. // Otherwise, set the opcode to OpSpecConstantFalse; if (!static_cast<bool>(bit_pattern.front())) { spec_inst->SetOpcode(SpvOp::SpvOpSpecConstantFalse); modified = true; } break; case SpvOp::SpvOpSpecConstantFalse: // If the new value is also 'false', no need to change anything. // Otherwise, set the opcode to OpSpecConstantTrue; if (static_cast<bool>(bit_pattern.front())) { spec_inst->SetOpcode(SpvOp::SpvOpSpecConstantTrue); modified = true; } break; default: break; } // No need to update the DefUse manager, as this pass does not change any // ids. } return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange; } // Returns true if the given char is ':', '\0' or considered as blank space // (i.e.: '\n', '\r', '\v', '\t', '\f' and ' '). bool IsSeparator(char ch) { return std::strchr(":\0", ch) || std::isspace(ch) != 0; } std::unique_ptr<SetSpecConstantDefaultValuePass::SpecIdToValueStrMap> SetSpecConstantDefaultValuePass::ParseDefaultValuesString(const char* str) { if (!str) return nullptr; auto spec_id_to_value = MakeUnique<SpecIdToValueStrMap>(); // The parsing loop, break when points to the end. while (*str) { // Find the spec id. while (std::isspace(*str)) str++; // skip leading spaces. const char* entry_begin = str; while (!IsSeparator(*str)) str++; const char* entry_end = str; std::string spec_id_str(entry_begin, entry_end - entry_begin); uint32_t spec_id = 0; if (!ParseNumber(spec_id_str.c_str(), &spec_id)) { // The spec id is not a valid uint32 number. return nullptr; } auto iter = spec_id_to_value->find(spec_id); if (iter != spec_id_to_value->end()) { // Same spec id has been defined before return nullptr; } // Find the ':', spaces between the spec id and the ':' are not allowed. if (*str++ != ':') { // ':' not found return nullptr; } // Find the value string const char* val_begin = str; while (!IsSeparator(*str)) str++; const char* val_end = str; if (val_end == val_begin) { // Value string is empty. return nullptr; } // Update the mapping with spec id and value string. (*spec_id_to_value)[spec_id] = std::string(val_begin, val_end - val_begin); // Skip trailing spaces. while (std::isspace(*str)) str++; } return spec_id_to_value; } } // namespace opt } // namespace spvtools
c++
code
14,743
2,855
/**************************************************************************** * * Copyright (C) 2013-2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /* Auto-generated by genmsg_cpp from file differential_pressure.msg */ #include <inttypes.h> #include <px4_log.h> #include <px4_defines.h> #include <uORB/topics/differential_pressure.h> #include <drivers/drv_hrt.h> #include <lib/drivers/device/Device.hpp> constexpr char __orb_differential_pressure_fields[] = "uint64_t timestamp;uint64_t error_count;float differential_pressure_raw_pa;float differential_pressure_filtered_pa;float temperature;uint32_t device_id;"; ORB_DEFINE(differential_pressure, struct differential_pressure_s, 32, __orb_differential_pressure_fields); void print_message(const differential_pressure_s& message) { PX4_INFO_RAW(" differential_pressure_s\n"); if (message.timestamp != 0) { PX4_INFO_RAW("\ttimestamp: %" PRIu64 " (%.6f seconds ago)\n", message.timestamp, hrt_elapsed_time(&message.timestamp) / 1e6); } else { PX4_INFO_RAW("\n"); } PX4_INFO_RAW("\terror_count: %" PRIu64 "\n", message.error_count); PX4_INFO_RAW("\tdifferential_pressure_raw_pa: %.4f\n", (double)message.differential_pressure_raw_pa); PX4_INFO_RAW("\tdifferential_pressure_filtered_pa: %.4f\n", (double)message.differential_pressure_filtered_pa); PX4_INFO_RAW("\ttemperature: %.4f\n", (double)message.temperature); char device_id_buffer[80]; device::Device::device_id_print_buffer(device_id_buffer, sizeof(device_id_buffer), message.device_id); PX4_INFO_RAW("\tdevice_id: %d (%s) \n", message.device_id, device_id_buffer); }
c++
code
3,183
722
#include <bits/stdc++.h> using namespace std; #include "distance_matrix.hpp" #include "node.hpp" #include "randomness_matrix.hpp" int Block::nextID = 0; int Block::max_height = 0; int no_blocks[100] = {0}; int main(int argc, char *argv[]) { if (argc != 5) { cerr << "Incorrect Usage!" << endl; cerr << "Correct Usage: ./simulator <number_of_nodes> " "<distance_matrix_csv> <number_of_rounds> <randomness_file>" << endl; return 1; } int n = stoi(argv[1]), r = stoi(argv[3]); Distance_matrix D(n, argv[2]); // D.print(); array<double, 4> strategy_space = {1, 0.75, 0.5, 0.25}; Randomness_matrix R(n, r, argv[4]); list<Block> mined; mined.push_back(Block()); double p = 0.02; for (int i = 0; i < r; i++) { for (int j = 0; j < n; j++) { if (R[i][j] < p) { int longest_chain_length = 0; for (auto it = mined.begin(); it != mined.end(); ++it) { if (it->creator == -1 || it->round <= i - D[it->creator][j]) longest_chain_length = max(it->height, longest_chain_length); } for (auto it = mined.begin(); it != mined.end(); ++it) { if (it->height == longest_chain_length) { cout << i << ' ' << j << " points to " << it->ID << endl; mined.push_back(Block(i, i - D[it->creator][j] + 1, j, it)); } } } } } cout << "Total Blocks Mined: " << mined.size() << endl; auto min_it = mined.end(), first_it = mined.end(); double min_var = double(INT_MAX); vector<double> rewards(100, 0); for (auto it = mined.begin(); it != mined.end(); it++) { if (it->height == Block::max_height) { double mean = it->total_chain_reward() / double(it->height); double variance = it->total_variance(mean); list<Block> proposed_chain; it->chain(proposed_chain); // for (auto it2 = proposed_chain.begin(); it2 != proposed_chain.end(); // it2++) { // cerr << it2->reward << ','; // } for (auto it2 = proposed_chain.begin(); it2 != proposed_chain.end(); it2++) { // cerr << it2->creator << ','; if (it2->reward > 10) { cout << "Error!!" << endl; return 1; } rewards[it2->creator] += it2->reward; no_blocks[it2->creator]++; } // cerr << endl; // double var = variance / mean; // if (var < min_var) { // min_it = it; // min_var = var; // } if (first_it == mined.end()) { first_it = it; } } } for (int i = 0; i < 99; i++) { cerr << rewards[i] << ','; } cerr << rewards[100] << endl; for (int i = 0; i < 99; i++) { cerr << no_blocks[i] << ','; } cerr << no_blocks[100] << endl; // list<Block> fair_chain; // min_it->chain(fair_chain); // cout << "Fair Chain: " << endl; // for (auto it = fair_chain.begin(); it != fair_chain.end(); ++it) { // cout << "Miner : " << it->creator << " Reward: " << setprecision(5) // << it->reward << " Leftover: " << it->leftover // << " Strategy: " << it->strategy << endl; // } list<Block> first_chain; first_it->chain(first_chain); cout << "First Chain: " << endl; for (auto it = first_chain.begin(); it != first_chain.end(); ++it) { cout << "Miner : " << it->creator << " Reward: " << setprecision(5) << it->reward << " Leftover: " << it->leftover << " Strategy: " << it->strategy << endl; } // cout << "Slow: " << slow << " Fast: " << fast << endl; return 0; }
c++
code
3,558
1,062
#include <iostream> using namespace std; float quaternion[4] = { 0 }; float conjugateQuaternion[4] = { 0 }; float vector[3] = { 0 }; float pureQuaternion[4] = { 0 }; float intermediateResultQuaternion[4] = { 0 }; float resultQuaternion[4] = { 0 }; void HamiltonProduct(float* q, float* p, float* result); int main() { cout << "This program will rotate a vector using the quaternion product" << endl; cout << "Introduce the components of the vector" << endl; for (int i = 0; i < 3; i++) { cout<<"Introduce the term number "<<i<<endl; cin >> vector[i]; } cout << "Introduce the components of the quaternion" << endl; for (int i = 0; i < 4; i++) { cout << "Introduce the term number " << i << endl; cin >> quaternion[i]; } cout << "Creating the pure quaternion from the vector..." << endl; pureQuaternion[0] = 0; for (int i = 0; i < 3; i++) pureQuaternion[i + 1] = vector[i]; cout << "Creating the conjugate from the quaternion..." << endl; conjugateQuaternion[0] = quaternion[0]; for (int i = 1; i < 4; i++) conjugateQuaternion[i] = -quaternion[i]; HamiltonProduct(quaternion, pureQuaternion, intermediateResultQuaternion); cout << "First operation result: " << endl; for (int i = 0; i < 4; i++) cout << intermediateResultQuaternion[i] << endl; HamiltonProduct(intermediateResultQuaternion, conjugateQuaternion, resultQuaternion); cout << "Final quaternion result: " << endl; for (int i = 0; i < 4; i++) cout << resultQuaternion[i]<<endl; for (int i = 0; i < 3; i++) vector[i] = resultQuaternion[i + 1]; cout << "The vector after the rotation is: " << endl; for (int i = 0; i < 3; i++) cout << vector[i] << endl; cout << "Imput any key to exit" << endl; char end; cin >> end; cout << "Exiting the program" << endl; return 0; } void HamiltonProduct(float* q, float* p, float* result) { result[0] = q[0] * p[0] - q[1] * p[1] - q[2] * p[2] - q[3] * p[3]; result[1] = q[0] * p[1] + q[1] * p[0] + q[2] * p[3] - q[3] * p[2]; result[2] = q[0] * p[2] - q[1] * p[3] + q[2] * p[0] + q[3] * p[1]; result[3] = q[0] * p[3] + q[1] * p[2] - q[2] * p[1] + q[3] * p[0]; }
c++
code
2,104
724
#include <cstdio> #include <iostream> #include <queue> #define int long long const int MAX_N = 1000050; int a[MAX_N], b[MAX_N]; std::priority_queue<int> q; template <typename T> T read(); signed main() { std::ios::sync_with_stdio(false); int n = read<int>(), ans = 0, res = 0; a[1] = b[1] = read<int>() - 1; q.push(a[1]); for (int i = 2; i <= n; i++) { int x = read<int>() - i; b[i] = x; q.push(x); if (q.top() > x) { ans += q.top() - x; q.pop(); q.push(x); } a[i] = q.top(); } for (int i = n - 1; i > 0; i--) { a[i] = std::min(a[i], a[i + 1]); } for (int i = 1; i <= n; i++) { res += std::abs(a[i] - b[i]); } std::cout << res << '\n'; for (int i = 1; i <= n; i++) { std::cout << a[i] + i << ' '; } return 0; } template <typename T> T read() { T x = 0, f = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); } while (isdigit(ch)) { x = x * 10 + ch - 48; ch = getchar(); } return x * f; }
c++
code
1,160
427
// 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 "base/trace_event/malloc_dump_provider.h" #include <stddef.h> #include <unordered_map> #include "base/allocator/allocator_extension.h" #include "base/allocator/buildflags.h" #include "base/allocator/partition_allocator/partition_alloc_config.h" #include "base/allocator/partition_allocator/partition_bucket_lookup.h" #include "base/debug/profiler.h" #include "base/format_macros.h" #include "base/memory/nonscannable_memory.h" #include "base/metrics/histogram_functions.h" #include "base/strings/stringprintf.h" #include "base/trace_event/process_memory_dump.h" #include "base/trace_event/traced_value.h" #include "build/build_config.h" #if defined(OS_APPLE) #include <malloc/malloc.h> #else #include <malloc.h> #endif #if defined(OS_WIN) #include <windows.h> #endif #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) #include <features.h> #endif #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "base/allocator/allocator_shim_default_dispatch_to_partition_alloc.h" #endif #if defined(PA_THREAD_CACHE_ALLOC_STATS) #include "base/allocator/partition_allocator/partition_alloc_constants.h" #endif namespace base { namespace trace_event { namespace { #if defined(OS_WIN) // A structure containing some information about a given heap. struct WinHeapInfo { size_t committed_size; size_t uncommitted_size; size_t allocated_size; size_t block_count; }; // NOTE: crbug.com/665516 // Unfortunately, there is no safe way to collect information from secondary // heaps due to limitations and racy nature of this piece of WinAPI. void WinHeapMemoryDumpImpl(WinHeapInfo* crt_heap_info) { // Iterate through whichever heap our CRT is using. HANDLE crt_heap = reinterpret_cast<HANDLE>(_get_heap_handle()); ::HeapLock(crt_heap); PROCESS_HEAP_ENTRY heap_entry; heap_entry.lpData = nullptr; // Walk over all the entries in the main heap. while (::HeapWalk(crt_heap, &heap_entry) != FALSE) { if ((heap_entry.wFlags & PROCESS_HEAP_ENTRY_BUSY) != 0) { crt_heap_info->allocated_size += heap_entry.cbData; crt_heap_info->block_count++; } else if ((heap_entry.wFlags & PROCESS_HEAP_REGION) != 0) { crt_heap_info->committed_size += heap_entry.Region.dwCommittedSize; crt_heap_info->uncommitted_size += heap_entry.Region.dwUnCommittedSize; } } CHECK(::HeapUnlock(crt_heap) == TRUE); } void ReportWinHeapStats(MemoryDumpLevelOfDetail level_of_detail, ProcessMemoryDump* pmd, size_t* total_virtual_size, size_t* resident_size, size_t* allocated_objects_size, size_t* allocated_objects_count) { // This is too expensive on Windows, crbug.com/780735. if (level_of_detail == MemoryDumpLevelOfDetail::DETAILED) { WinHeapInfo main_heap_info = {}; WinHeapMemoryDumpImpl(&main_heap_info); *total_virtual_size += main_heap_info.committed_size + main_heap_info.uncommitted_size; // Resident size is approximated with committed heap size. Note that it is // possible to do this with better accuracy on windows by intersecting the // working set with the virtual memory ranges occuipied by the heap. It's // not clear that this is worth it, as it's fairly expensive to do. *resident_size += main_heap_info.committed_size; *allocated_objects_size += main_heap_info.allocated_size; *allocated_objects_count += main_heap_info.block_count; if (pmd) { MemoryAllocatorDump* win_heap_dump = pmd->CreateAllocatorDump("malloc/win_heap"); win_heap_dump->AddScalar("size", "bytes", main_heap_info.allocated_size); } } } #endif // defined(OS_WIN) #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) void ReportPartitionAllocStats(ProcessMemoryDump* pmd, MemoryDumpLevelOfDetail level_of_detail, size_t* total_virtual_size, size_t* resident_size, size_t* allocated_objects_size) { MemoryDumpPartitionStatsDumper partition_stats_dumper("malloc", pmd, level_of_detail); bool is_light_dump = level_of_detail == MemoryDumpLevelOfDetail::BACKGROUND; auto* allocator = internal::PartitionAllocMalloc::Allocator(); allocator->DumpStats("allocator", is_light_dump, &partition_stats_dumper); auto* original_allocator = internal::PartitionAllocMalloc::OriginalAllocator(); if (original_allocator) { original_allocator->DumpStats("original", is_light_dump, &partition_stats_dumper); } auto* aligned_allocator = internal::PartitionAllocMalloc::AlignedAllocator(); if (aligned_allocator != allocator) { aligned_allocator->DumpStats("aligned", is_light_dump, &partition_stats_dumper); } auto& nonscannable_allocator = internal::NonScannableAllocator::Instance(); if (auto* root = nonscannable_allocator.root()) root->DumpStats("nonscannable", is_light_dump, &partition_stats_dumper); auto& nonquarantinable_allocator = internal::NonQuarantinableAllocator::Instance(); if (auto* root = nonquarantinable_allocator.root()) root->DumpStats("nonquarantinable", is_light_dump, &partition_stats_dumper); *total_virtual_size += partition_stats_dumper.total_resident_bytes(); *resident_size += partition_stats_dumper.total_resident_bytes(); *allocated_objects_size += partition_stats_dumper.total_active_bytes(); } #endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } // namespace // static const char MallocDumpProvider::kAllocatedObjects[] = "malloc/allocated_objects"; // static MallocDumpProvider* MallocDumpProvider::GetInstance() { return Singleton<MallocDumpProvider, LeakySingletonTraits<MallocDumpProvider>>::get(); } MallocDumpProvider::MallocDumpProvider() = default; MallocDumpProvider::~MallocDumpProvider() = default; // Called at trace dump point time. Creates a snapshot the memory counters for // the current process. bool MallocDumpProvider::OnMemoryDump(const MemoryDumpArgs& args, ProcessMemoryDump* pmd) { { base::AutoLock auto_lock(emit_metrics_on_memory_dump_lock_); if (!emit_metrics_on_memory_dump_) return true; } size_t total_virtual_size = 0; size_t resident_size = 0; size_t allocated_objects_size = 0; size_t allocated_objects_count = 0; #if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) ReportPartitionAllocStats(pmd, args.level_of_detail, &total_virtual_size, &resident_size, &allocated_objects_size); #if OS_WIN ReportWinHeapStats(args.level_of_detail, pmd, &total_virtual_size, &resident_size, &allocated_objects_size, &allocated_objects_count); #endif // TODO(keishi): Add glibc malloc on Android #elif BUILDFLAG(USE_TCMALLOC) bool res = allocator::GetNumericProperty("generic.heap_size", &total_virtual_size); DCHECK(res); res = allocator::GetNumericProperty("generic.total_physical_bytes", &resident_size); DCHECK(res); res = allocator::GetNumericProperty("generic.current_allocated_bytes", &allocated_objects_size); DCHECK(res); #elif defined(OS_APPLE) malloc_statistics_t stats = {0}; malloc_zone_statistics(nullptr, &stats); total_virtual_size = stats.size_allocated; allocated_objects_size = stats.size_in_use; // Resident size is approximated pretty well by stats.max_size_in_use. // However, on macOS, freed blocks are both resident and reusable, which is // semantically equivalent to deallocated. The implementation of libmalloc // will also only hold a fixed number of freed regions before actually // starting to deallocate them, so stats.max_size_in_use is also not // representative of the peak size. As a result, stats.max_size_in_use is // typically somewhere between actually resident [non-reusable] pages, and // peak size. This is not very useful, so we just use stats.size_in_use for // resident_size, even though it's an underestimate and fails to account for // fragmentation. See // https://bugs.chromium.org/p/chromium/issues/detail?id=695263#c1. resident_size = stats.size_in_use; #elif defined(OS_WIN) ReportWinHeapStats(args.level_of_detail, nullptr, &total_virtual_size, &resident_size, &allocated_objects_size, &allocated_objects_count); #elif defined(OS_FUCHSIA) // TODO(fuchsia): Port, see https://crbug.com/706592. #elif defined(__MUSL__) #else #if defined(__GLIBC__) && defined(__GLIBC_PREREQ) #if __GLIBC_PREREQ(2, 33) #define MALLINFO2_FOUND_IN_LIBC struct mallinfo2 info = mallinfo2(); #endif #endif // defined(__GLIBC__) && defined(__GLIBC_PREREQ) #if !defined(MALLINFO2_FOUND_IN_LIBC) struct mallinfo info = mallinfo(); #endif #undef MALLINFO2_FOUND_IN_LIBC // In case of Android's jemalloc |arena| is 0 and the outer pages size is // reported by |hblkhd|. In case of dlmalloc the total is given by // |arena| + |hblkhd|. For more details see link: http://goo.gl/fMR8lF. total_virtual_size = info.arena + info.hblkhd; resident_size = info.uordblks; // Total allocated space is given by |uordblks|. allocated_objects_size = info.uordblks; #endif MemoryAllocatorDump* outer_dump = pmd->CreateAllocatorDump("malloc"); outer_dump->AddScalar("virtual_size", MemoryAllocatorDump::kUnitsBytes, total_virtual_size); outer_dump->AddScalar(MemoryAllocatorDump::kNameSize, MemoryAllocatorDump::kUnitsBytes, resident_size); outer_dump->AddScalar(MemoryAllocatorDump::kNameSize, MemoryAllocatorDump::kUnitsBytes, allocated_objects_size); if (allocated_objects_count != 0) { outer_dump->AddScalar(MemoryAllocatorDump::kNameObjectCount, MemoryAllocatorDump::kUnitsObjects, allocated_objects_count); } if (resident_size > allocated_objects_size) { // Explicitly specify why is extra memory resident. In tcmalloc it accounts // for free lists and caches. In mac and ios it accounts for the // fragmentation and metadata. MemoryAllocatorDump* other_dump = pmd->CreateAllocatorDump("malloc/metadata_fragmentation_caches"); other_dump->AddScalar(MemoryAllocatorDump::kNameSize, MemoryAllocatorDump::kUnitsBytes, resident_size - allocated_objects_size); } return true; } void MallocDumpProvider::EnableMetrics() { base::AutoLock auto_lock(emit_metrics_on_memory_dump_lock_); emit_metrics_on_memory_dump_ = true; } void MallocDumpProvider::DisableMetrics() { base::AutoLock auto_lock(emit_metrics_on_memory_dump_lock_); emit_metrics_on_memory_dump_ = false; } #if BUILDFLAG(USE_PARTITION_ALLOC) // static const char* MemoryDumpPartitionStatsDumper::kPartitionsDumpName = "partitions"; std::string GetPartitionDumpName(const char* root_name, const char* partition_name) { return base::StringPrintf("%s/%s/%s", root_name, MemoryDumpPartitionStatsDumper::kPartitionsDumpName, partition_name); } void MemoryDumpPartitionStatsDumper::PartitionDumpTotals( const char* partition_name, const base::PartitionMemoryStats* memory_stats) { total_mmapped_bytes_ += memory_stats->total_mmapped_bytes; total_resident_bytes_ += memory_stats->total_resident_bytes; total_active_bytes_ += memory_stats->total_active_bytes; std::string dump_name = GetPartitionDumpName(root_name_, partition_name); MemoryAllocatorDump* allocator_dump = memory_dump_->CreateAllocatorDump(dump_name); allocator_dump->AddScalar("size", "bytes", memory_stats->total_resident_bytes); allocator_dump->AddScalar("allocated_objects_size", "bytes", memory_stats->total_active_bytes); allocator_dump->AddScalar("virtual_size", "bytes", memory_stats->total_mmapped_bytes); allocator_dump->AddScalar("virtual_committed_size", "bytes", memory_stats->total_committed_bytes); allocator_dump->AddScalar("max_committed_size", "bytes", memory_stats->max_committed_bytes); allocator_dump->AddScalar("allocated_size", "bytes", memory_stats->total_allocated_bytes); allocator_dump->AddScalar("max_allocated_size", "bytes", memory_stats->max_allocated_bytes); allocator_dump->AddScalar("decommittable_size", "bytes", memory_stats->total_decommittable_bytes); allocator_dump->AddScalar("discardable_size", "bytes", memory_stats->total_discardable_bytes); #if BUILDFLAG(USE_BACKUP_REF_PTR) allocator_dump->AddScalar("brp_quarantined_size", "bytes", memory_stats->total_brp_quarantined_bytes); allocator_dump->AddScalar("brp_quarantined_count", "count", memory_stats->total_brp_quarantined_count); #endif allocator_dump->AddScalar("syscall_count", "count", memory_stats->syscall_count); allocator_dump->AddScalar("syscall_total_time_ms", "ms", memory_stats->syscall_total_time_ns / 1e6); if (memory_stats->has_thread_cache) { const auto& thread_cache_stats = memory_stats->current_thread_cache_stats; auto* thread_cache_dump = memory_dump_->CreateAllocatorDump( dump_name + "/thread_cache/main_thread"); ReportPartitionAllocThreadCacheStats(memory_dump_, thread_cache_dump, thread_cache_stats, ".MainThread", detailed_); const auto& all_thread_caches_stats = memory_stats->all_thread_caches_stats; auto* all_thread_caches_dump = memory_dump_->CreateAllocatorDump(dump_name + "/thread_cache"); ReportPartitionAllocThreadCacheStats(memory_dump_, all_thread_caches_dump, all_thread_caches_stats, "", detailed_); } } void MemoryDumpPartitionStatsDumper::PartitionsDumpBucketStats( const char* partition_name, const base::PartitionBucketMemoryStats* memory_stats) { DCHECK(memory_stats->is_valid); std::string dump_name = GetPartitionDumpName(root_name_, partition_name); if (memory_stats->is_direct_map) { dump_name.append(base::StringPrintf("/buckets/directMap_%" PRIu64, ++uid_)); } else { // Normal buckets go up to ~1MiB, 7 digits. dump_name.append(base::StringPrintf("/buckets/bucket_%07" PRIu32, memory_stats->bucket_slot_size)); } MemoryAllocatorDump* allocator_dump = memory_dump_->CreateAllocatorDump(dump_name); allocator_dump->AddScalar("size", "bytes", memory_stats->resident_bytes); allocator_dump->AddScalar("allocated_objects_size", "bytes", memory_stats->active_bytes); allocator_dump->AddScalar("slot_size", "bytes", memory_stats->bucket_slot_size); allocator_dump->AddScalar("decommittable_size", "bytes", memory_stats->decommittable_bytes); allocator_dump->AddScalar("discardable_size", "bytes", memory_stats->discardable_bytes); // TODO(bartekn): Rename the scalar names. allocator_dump->AddScalar("total_slot_span_size", "bytes", memory_stats->allocated_slot_span_size); allocator_dump->AddScalar("active_slot_spans", "objects", memory_stats->num_active_slot_spans); allocator_dump->AddScalar("full_slot_spans", "objects", memory_stats->num_full_slot_spans); allocator_dump->AddScalar("empty_slot_spans", "objects", memory_stats->num_empty_slot_spans); allocator_dump->AddScalar("decommitted_slot_spans", "objects", memory_stats->num_decommitted_slot_spans); } void ReportPartitionAllocThreadCacheStats(ProcessMemoryDump* pmd, MemoryAllocatorDump* dump, const ThreadCacheStats& stats, const std::string& metrics_suffix, bool detailed) { dump->AddScalar("alloc_count", "scalar", stats.alloc_count); dump->AddScalar("alloc_hits", "scalar", stats.alloc_hits); dump->AddScalar("alloc_misses", "scalar", stats.alloc_misses); dump->AddScalar("alloc_miss_empty", "scalar", stats.alloc_miss_empty); dump->AddScalar("alloc_miss_too_large", "scalar", stats.alloc_miss_too_large); dump->AddScalar("cache_fill_count", "scalar", stats.cache_fill_count); dump->AddScalar("cache_fill_hits", "scalar", stats.cache_fill_hits); dump->AddScalar("cache_fill_misses", "scalar", stats.cache_fill_misses); dump->AddScalar("batch_fill_count", "scalar", stats.batch_fill_count); dump->AddScalar("size", "bytes", stats.bucket_total_memory); dump->AddScalar("metadata_overhead", "bytes", stats.metadata_overhead); if (stats.alloc_count) { int hit_rate_percent = static_cast<int>((100 * stats.alloc_hits) / stats.alloc_count); base::UmaHistogramPercentage( "Memory.PartitionAlloc.ThreadCache.HitRate" + metrics_suffix, hit_rate_percent); int batch_fill_rate_percent = static_cast<int>((100 * stats.batch_fill_count) / stats.alloc_count); base::UmaHistogramPercentage( "Memory.PartitionAlloc.ThreadCache.BatchFillRate" + metrics_suffix, batch_fill_rate_percent); #if defined(PA_THREAD_CACHE_ALLOC_STATS) if (detailed) { base::internal::BucketIndexLookup lookup{}; std::string name = dump->absolute_name(); for (size_t i = 0; i < kNumBuckets; i++) { size_t bucket_size = lookup.bucket_sizes()[i]; if (bucket_size == kInvalidBucketSize) continue; // Covers all normal buckets, that is up to ~1MiB, so 7 digits. std::string dump_name = base::StringPrintf("%s/buckets_alloc/%07d", name.c_str(), static_cast<int>(bucket_size)); auto* buckets_alloc_dump = pmd->CreateAllocatorDump(dump_name); buckets_alloc_dump->AddScalar("count", "objects", stats.allocs_per_bucket_[i]); } } #endif // defined(PA_THREAD_CACHE_ALLOC_STATS) } } #endif // BUILDFLAG(USE_PARTITION_ALLOC) } // namespace trace_event } // namespace base
c++
code
19,031
3,017
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); // Complete the arrayManipulation function below. long arrayManipulation(int n, vector<vector<int>> queries) { long *arr = new long[n+2]{0}; long max_sum = 0, curr_sum = 0; for (const auto& q: queries) { arr[q[0]] += q[2]; arr[q[1]+1] -= q[2]; } for (int i = 1; i <= n ; i++) { curr_sum += arr[i]; max_sum = max(curr_sum, max_sum); } return max_sum; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string nm_temp; getline(cin, nm_temp); vector<string> nm = split_string(nm_temp); int n = stoi(nm[0]); int m = stoi(nm[1]); vector<vector<int>> queries(m); for (int i = 0; i < m; i++) { queries[i].resize(3); for (int j = 0; j < 3; j++) { cin >> queries[i][j]; } cin.ignore(numeric_limits<streamsize>::max(), '\n'); } long result = arrayManipulation(n, queries); fout << result << "\n"; cout << result << endl; fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
c++
code
1,867
528
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <array> #include "tensorflow/python/lib/core/bfloat16.h" #include "tensorflow/core/framework/numeric_types.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/python/lib/core/numpy.h" #include "tensorflow/python/lib/core/safe_ptr.h" namespace tensorflow { namespace { // Workarounds for Python 2 vs 3 API differences. #if PY_MAJOR_VERSION < 3 PyObject* MakePyString(const string& s) { return PyString_FromString(s.c_str()); } typedef long HashType; // NOLINT bool TfPyInt_Check(PyObject* object) { return PyInt_Check(object); } PyObject* TfPyInt_FromLong(long x) { // NOLINT return PyInt_FromLong(x); } long TfPyInt_AsLong(PyObject* x) { // NOLINT return PyInt_AsLong(x); } #else // PY_MAJOR_VERSION < 3 PyObject* MakePyString(const string& s) { return PyUnicode_FromString(s.c_str()); } bool TfPyInt_Check(PyObject* object) { if (!PyLong_Check(object)) { return 0; } int overflow = 0; PyLong_AsLongAndOverflow(object, &overflow); return (overflow == 0); } PyObject* TfPyInt_FromLong(long x) { // NOLINT return PyLong_FromLong(x); } long TfPyInt_AsLong(PyObject* x) { // NOLINT return PyLong_AsLong(x); } typedef Py_hash_t HashType; #endif // PY_MAJOR_VERSION < 3 // Forward declaration. extern PyTypeObject PyBfloat16_Type; // Representation of a Python bfloat16 object. struct PyBfloat16 { PyObject_HEAD; // Python object header bfloat16 value; }; // Returns true if 'object' is a PyBfloat16. bool PyBfloat16_Check(PyObject* object) { return PyObject_IsInstance(object, reinterpret_cast<PyObject*>(&PyBfloat16_Type)); } // Extracts the value of a PyBfloat16 object. bfloat16 PyBfloat16_Bfloat16(PyObject* object) { return reinterpret_cast<PyBfloat16*>(object)->value; } // Constructs a PyBfloat16 object from a bfloat16. Safe_PyObjectPtr PyBfloat16_FromBfloat16(bfloat16 x) { Safe_PyObjectPtr ref = make_safe(PyBfloat16_Type.tp_alloc(&PyBfloat16_Type, 0)); PyBfloat16* p = reinterpret_cast<PyBfloat16*>(ref.get()); if (p) { p->value = x; } return ref; } // Converts a Python object to a bfloat16 value. Returns true on success, // returns false and reports a Python error on failure. bool AsBfloat16(PyObject* arg, bfloat16* output) { if (PyBfloat16_Check(arg)) { *output = PyBfloat16_Bfloat16(arg); return true; } if (PyFloat_Check(arg)) { double d = PyFloat_AsDouble(arg); if (PyErr_Occurred()) { return false; } // TODO (phawkins): check for overflow id:3353 // https://github.com/imdone/tensorflow/issues/3352 *output = bfloat16(d); return true; } if (TfPyInt_Check(arg)) { long l = TfPyInt_AsLong(arg); // NOLINT if (PyErr_Occurred()) { return false; } // TODO (phawkins): check for overflow id:3350 // https://github.com/imdone/tensorflow/issues/3349 *output = bfloat16(static_cast<float>(l)); return true; } if (PyArray_IsScalar(arg, Float)) { float f; PyArray_ScalarAsCtype(arg, &f); *output = bfloat16(f); return true; } PyErr_Format(PyExc_TypeError, "expected number, got %s", arg->ob_type->tp_name); return false; } // Converts a PyBfloat16 into a PyFloat. PyObject* PyBfloat16_Float(PyObject* self) { bfloat16 x = PyBfloat16_Bfloat16(self); return PyFloat_FromDouble(static_cast<double>(x)); } // Converts a PyBfloat16 into a PyInt. PyObject* PyBfloat16_Int(PyObject* self) { bfloat16 x = PyBfloat16_Bfloat16(self); long y = static_cast<long>(x); // NOLINT return TfPyInt_FromLong(y); } // Negates a PyBfloat16. PyObject* PyBfloat16_Negative(PyObject* self) { bfloat16 x = PyBfloat16_Bfloat16(self); return PyBfloat16_FromBfloat16(-x).release(); } // Binary arithmetic operators on PyBfloat16 values. #define BFLOAT16_BINOP(name, op) \ PyObject* PyBfloat16_##name(PyObject* a, PyObject* b) { \ bfloat16 x, y; \ if (!AsBfloat16(a, &x) || !AsBfloat16(b, &y)) return nullptr; \ bfloat16 z = x op y; \ return PyBfloat16_FromBfloat16(z).release(); \ } BFLOAT16_BINOP(Add, +) BFLOAT16_BINOP(Subtract, -) BFLOAT16_BINOP(Multiply, *) BFLOAT16_BINOP(Divide, /) #undef BFLOAT16_BINOP // Python number methods for PyBfloat16 objects. PyNumberMethods PyBfloat16_AsNumber = { PyBfloat16_Add, // nb_add PyBfloat16_Subtract, // nb_subtract PyBfloat16_Multiply, // nb_multiply #if PY_MAJOR_VERSION < 3 PyBfloat16_Divide, // nb_divide #endif nullptr, // nb_remainder nullptr, // nb_divmod nullptr, // nb_power PyBfloat16_Negative, // nb_negative nullptr, // nb_positive nullptr, // nb_absolute nullptr, // nb_nonzero nullptr, // nb_invert nullptr, // nb_lshift nullptr, // nb_rshift nullptr, // nb_and nullptr, // nb_xor nullptr, // nb_or #if PY_MAJOR_VERSION < 3 nullptr, // nb_coerce #endif PyBfloat16_Int, // nb_int #if PY_MAJOR_VERSION < 3 PyBfloat16_Int, // nb_long #else nullptr, // reserved #endif PyBfloat16_Float, // nb_float #if PY_MAJOR_VERSION < 3 nullptr, // nb_oct nullptr, // nb_hex #endif nullptr, // nb_inplace_add nullptr, // nb_inplace_subtract nullptr, // nb_inplace_multiply #if PY_MAJOR_VERSION < 3 nullptr, // nb_inplace_divide #endif nullptr, // nb_inplace_remainder nullptr, // nb_inplace_power nullptr, // nb_inplace_lshift nullptr, // nb_inplace_rshift nullptr, // nb_inplace_and nullptr, // nb_inplace_xor nullptr, // nb_inplace_or nullptr, // nb_floor_divide PyBfloat16_Divide, // nb_true_divide nullptr, // nb_inplace_floor_divide nullptr, // nb_inplace_true_divide nullptr, // nb_index }; // Constructs a new PyBfloat16. PyObject* PyBfloat16_New(PyTypeObject* type, PyObject* args, PyObject* kwds) { if (kwds && PyDict_Size(kwds)) { PyErr_SetString(PyExc_TypeError, "constructor takes no keyword arguments"); return nullptr; } Py_ssize_t size = PyTuple_Size(args); if (size != 1) { PyErr_SetString(PyExc_TypeError, "expected number as argument to bfloat16 constructor"); return nullptr; } PyObject* arg = PyTuple_GetItem(args, 0); if (PyBfloat16_Check(arg)) { Py_INCREF(arg); return arg; } else { bfloat16 value; if (!AsBfloat16(arg, &value)) { return nullptr; } return PyBfloat16_FromBfloat16(value).release(); } } // Comparisons on PyBfloat16s. PyObject* PyBfloat16_RichCompare(PyObject* a, PyObject* b, int op) { bfloat16 x, y; if (!AsBfloat16(a, &x) || !AsBfloat16(b, &y)) return nullptr; bool result; switch (op) { case Py_LT: result = x < y; break; case Py_LE: result = x <= y; break; case Py_EQ: result = x == y; break; case Py_NE: result = x != y; break; case Py_GT: result = x > y; break; case Py_GE: result = x >= y; break; default: LOG(FATAL) << "Invalid op type " << op; } return PyBool_FromLong(result); } // Implementation of repr() for PyBfloat16. PyObject* PyBfloat16_Repr(PyObject* self) { bfloat16 x = reinterpret_cast<PyBfloat16*>(self)->value; string v = strings::StrCat("bfloat16(", static_cast<float>(x), ")"); return MakePyString(v); } // Implementation of str() for PyBfloat16. PyObject* PyBfloat16_Str(PyObject* self) { bfloat16 x = reinterpret_cast<PyBfloat16*>(self)->value; string v = strings::StrCat(static_cast<float>(x)); return MakePyString(v); } // Hash function for PyBfloat16. We use the identity function, which is a weak // hash function. HashType PyBfloat16_Hash(PyObject* self) { bfloat16 x = reinterpret_cast<PyBfloat16*>(self)->value; return x.value; } // Python type for PyBfloat16 objects. PyTypeObject PyBfloat16_Type = { #if PY_MAJOR_VERSION < 3 PyObject_HEAD_INIT(nullptr) 0, // ob_size #else PyVarObject_HEAD_INIT(nullptr, 0) #endif "bfloat16", // tp_name sizeof(PyBfloat16), // tp_basicsize 0, // tp_itemsize nullptr, // tp_dealloc nullptr, // tp_print nullptr, // tp_getattr nullptr, // tp_setattr nullptr, // tp_compare / tp_reserved PyBfloat16_Repr, // tp_repr &PyBfloat16_AsNumber, // tp_as_number nullptr, // tp_as_sequence nullptr, // tp_as_mapping PyBfloat16_Hash, // tp_hash nullptr, // tp_call PyBfloat16_Str, // tp_str nullptr, // tp_getattro nullptr, // tp_setattro nullptr, // tp_as_buffer Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags "bfloat16 floating-point values", // tp_doc nullptr, // tp_traverse nullptr, // tp_clear PyBfloat16_RichCompare, // tp_richcompare 0, // tp_weaklistoffset nullptr, // tp_iter nullptr, // tp_iternext nullptr, // tp_methods nullptr, // tp_members nullptr, // tp_getset nullptr, // tp_base nullptr, // tp_dict nullptr, // tp_descr_get nullptr, // tp_descr_set 0, // tp_dictoffset nullptr, // tp_init nullptr, // tp_alloc PyBfloat16_New, // tp_new nullptr, // tp_free nullptr, // tp_is_gc nullptr, // tp_bases nullptr, // tp_mro nullptr, // tp_cache nullptr, // tp_subclasses nullptr, // tp_weaklist nullptr, // tp_del 0, // tp_version_tag }; // Numpy support PyArray_ArrFuncs NPyBfloat16_ArrFuncs; PyArray_Descr NPyBfloat16_Descr = { PyObject_HEAD_INIT(nullptr) & PyBfloat16_Type, // typeobj // We must register bfloat16 with a kind other than "f", because numpy // considers two types with the same kind and size to be equal, but // float16 != bfloat16. 'V', // kind // TODO (phawkins): there doesn't seem to be a way of guaranteeing a type id:3821 // https://github.com/imdone/tensorflow/issues/3820 // character is unique. // 'E', // type // '=', // byteorder // NPY_NEEDS_PYAPI | NPY_USE_GETITEM | NPY_USE_SETITEM, // hasobject // 0, // type_num // sizeof(bfloat16), // elsize // alignof(bfloat16), // alignment // nullptr, // subarray // nullptr, // fields // nullptr, // names // &NPyBfloat16_ArrFuncs, // f }; // Registered numpy type ID. Global variable populated by the registration code. int npy_bfloat16_ = -1; // Implementations of NumPy array methods. PyObject* NPyBfloat16_GetItem(void* data, void* arr) { bfloat16 x; memcpy(&x, data, sizeof(bfloat16)); return PyBfloat16_FromBfloat16(x).release(); } int NPyBfloat16_SetItem(PyObject* item, void* data, void* arr) { bfloat16 x; if (!AsBfloat16(item, &x)) return -1; memcpy(data, &x, sizeof(bfloat16)); return 0; } void ByteSwap16(void* value) { char* p = reinterpret_cast<char*>(value); std::swap(p[0], p[1]); } void NPyBfloat16_CopySwapN(void* dstv, npy_intp dstride, void* srcv, npy_intp sstride, npy_intp n, int swap, void* arr) { char* dst = reinterpret_cast<char*>(dstv); char* src = reinterpret_cast<char*>(srcv); if (!src) { return; } if (swap) { for (npy_intp i = 0; i < n; i++) { char* r = dst + dstride * i; memcpy(r, src + sstride * i, sizeof(uint16_t)); ByteSwap16(r); } } else if (dstride == sizeof(uint16_t) && sstride == sizeof(uint16_t)) { memcpy(dst, src, n * sizeof(uint16_t)); } else { for (npy_intp i = 0; i < n; i++) { memcpy(dst + dstride * i, src + sstride * i, sizeof(uint16_t)); } } } void NPyBfloat16_CopySwap(void* dst, void* src, int swap, void* arr) { if (!src) { return; } memcpy(dst, src, sizeof(uint16_t)); if (swap) { ByteSwap16(dst); } } npy_bool NPyBfloat16_NonZero(void* data, void* arr) { bfloat16 x; memcpy(&x, data, sizeof(x)); return x != static_cast<bfloat16>(0); } // NumPy casts // Performs a NumPy array cast from type 'From' to 'To'. template <typename From, typename To> void NPyCast(void* from_void, void* to_void, npy_intp n, void* fromarr, void* toarr) { const From* from = reinterpret_cast<From*>(from_void); To* to = reinterpret_cast<To*>(to_void); for (npy_intp i = 0; i < n; ++i) { to[i] = static_cast<To>(from[i]); } } // Registers a cast between bfloat16 and type 'T'. 'numpy_type' is the NumPy // type corresponding to 'T'. If 'cast_is_safe', registers that bfloat16 can be // safely coerced to T. template <typename T> bool RegisterBfloat16Cast(int numpy_type, bool cast_is_safe) { if (PyArray_RegisterCastFunc(PyArray_DescrFromType(numpy_type), npy_bfloat16_, NPyCast<T, bfloat16>) < 0) { return false; } if (PyArray_RegisterCastFunc(&NPyBfloat16_Descr, numpy_type, NPyCast<bfloat16, T>) < 0) { return false; } if (cast_is_safe && PyArray_RegisterCanCast(&NPyBfloat16_Descr, numpy_type, NPY_NOSCALAR) < 0) { return false; } return true; } template <typename InType, typename OutType, typename Functor> void BinaryUFunc(char** args, npy_intp* dimensions, npy_intp* steps, void* data) { const char* i0 = args[0]; const char* i1 = args[1]; char* o = args[2]; for (npy_intp k = 0; k < *dimensions; k++) { InType x = *reinterpret_cast<const InType*>(i0); InType y = *reinterpret_cast<const InType*>(i1); *reinterpret_cast<OutType*>(o) = Functor()(x, y); i0 += steps[0]; i1 += steps[1]; o += steps[2]; } } template <typename Functor> void CompareUFunc(char** args, npy_intp* dimensions, npy_intp* steps, void* data) { BinaryUFunc<bfloat16, npy_bool, Functor>(args, dimensions, steps, data); } struct Bfloat16EqFunctor { npy_bool operator()(bfloat16 a, bfloat16 b) { return a == b; } }; struct Bfloat16NeFunctor { npy_bool operator()(bfloat16 a, bfloat16 b) { return a != b; } }; struct Bfloat16LtFunctor { npy_bool operator()(bfloat16 a, bfloat16 b) { return a < b; } }; struct Bfloat16GtFunctor { npy_bool operator()(bfloat16 a, bfloat16 b) { return a > b; } }; struct Bfloat16LeFunctor { npy_bool operator()(bfloat16 a, bfloat16 b) { return a <= b; } }; struct Bfloat16GeFunctor { npy_bool operator()(bfloat16 a, bfloat16 b) { return a >= b; } }; // Initializes the module. bool Initialize() { // It's critical to import umath to avoid crash in open source build. import_umath1(false); Safe_PyObjectPtr numpy_str = make_safe(MakePyString("numpy")); if (!numpy_str) { return false; } Safe_PyObjectPtr numpy = make_safe(PyImport_Import(numpy_str.get())); if (!numpy) { return false; } // We hit a mysterious crash if we haven't initialized numpy before this: PyBfloat16_Type.tp_base = &PyGenericArrType_Type; if (PyType_Ready(&PyBfloat16_Type) < 0) { return false; } // Initializes the NumPy descriptor. PyArray_InitArrFuncs(&NPyBfloat16_ArrFuncs); NPyBfloat16_ArrFuncs.getitem = NPyBfloat16_GetItem; NPyBfloat16_ArrFuncs.setitem = NPyBfloat16_SetItem; NPyBfloat16_ArrFuncs.copyswapn = NPyBfloat16_CopySwapN; NPyBfloat16_ArrFuncs.copyswap = NPyBfloat16_CopySwap; NPyBfloat16_ArrFuncs.nonzero = NPyBfloat16_NonZero; Py_TYPE(&NPyBfloat16_Descr) = &PyArrayDescr_Type; npy_bfloat16_ = PyArray_RegisterDataType(&NPyBfloat16_Descr); if (npy_bfloat16_ < 0) return false; // Support dtype(bfloat16) if (PyDict_SetItemString(PyBfloat16_Type.tp_dict, "dtype", reinterpret_cast<PyObject*>(&NPyBfloat16_Descr)) < 0) { return false; } // Register casts // We lie shamelessly and say that a cast from half to bfloat16 is safe. // Numpy frequently uses the smallest legal representation type for small // float constants (e.g., 1.0), which is often float16. Things break if these // cannot be converted transparently to bfloat16. if (!RegisterBfloat16Cast<Eigen::half>(NPY_HALF, /*cast_is_safe=*/true)) { return false; } if (!RegisterBfloat16Cast<float>(NPY_FLOAT, /*cast_is_safe=*/true)) { return false; } if (!RegisterBfloat16Cast<double>(NPY_DOUBLE, /*cast_is_safe=*/true)) { return false; } if (!RegisterBfloat16Cast<int32>(NPY_INT32, /*cast_is_safe=*/false)) { return false; } if (!RegisterBfloat16Cast<int64>(NPY_INT64, /*cast_is_safe=*/false)) { return false; } // Following the numpy convention. imag part is dropped when converting to // float. if (!RegisterBfloat16Cast<complex64>(NPY_COMPLEX64, /*cast_is_safe=*/true)) { return false; } if (!RegisterBfloat16Cast<complex128>(NPY_COMPLEX128, /*cast_is_safe=*/true)) { return false; } // Register ufuncs auto register_ufunc = [&](const char* name, PyUFuncGenericFunction fn, const std::array<int, 3>& types) { Safe_PyObjectPtr ufunc_obj = make_safe(PyObject_GetAttrString(numpy.get(), name)); if (!ufunc_obj) { return false; } PyUFuncObject* ufunc = reinterpret_cast<PyUFuncObject*>(ufunc_obj.get()); if (types.size() != ufunc->nargs) { PyErr_Format(PyExc_AssertionError,
c++
code
19,984
3,615
/** * Copyright 2014 Social Robotics Lab, University of Freiburg * * 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 Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \author Billy Okal <[email protected]> * \author Sven Wehner <[email protected]> */ #include <pedsim_simulator/agentstatemachine.h> #include <pedsim_simulator/config.h> #include <pedsim_simulator/element/agent.h> #include <pedsim_simulator/element/waypoint.h> #include <pedsim_simulator/force/force.h> #include <pedsim_simulator/scene.h> #include <pedsim_simulator/waypointplanner/waypointplanner.h> Agent::Agent() { // initialize Ped::Tagent::setType(Ped::Tagent::ADULT); Ped::Tagent::setForceFactorObstacle(CONFIG.forceObstacle); forceSigmaObstacle = CONFIG.sigmaObstacle; Ped::Tagent::setForceFactorSocial(CONFIG.forceSocial); // waypoints currentDestination = nullptr; waypointplanner = nullptr; // state machine stateMachine = new AgentStateMachine(this); // group group = nullptr; } Agent::~Agent() { // clean up foreach (Force* currentForce, forces) { delete currentForce; } } /// Calculates the desired force. Same as in lib, but adds graphical representation Ped::Tvector Agent::desiredForce() { Ped::Tvector force; if (!disabledForces.contains("Desired")) force = Tagent::desiredForce(); // inform users emit desiredForceChanged(force.x, force.y); return force; } /// Calculates the social force. Same as in lib, but adds graphical representation Ped::Tvector Agent::socialForce() const { Ped::Tvector force; if (!disabledForces.contains("Social")) force = Tagent::socialForce(); // inform users emit socialForceChanged(force.x, force.y); return force; } /// Calculates the obstacle force. Same as in lib, but adds graphical representation Ped::Tvector Agent::obstacleForce() const { Ped::Tvector force; if (!disabledForces.contains("Obstacle")) force = Tagent::obstacleForce(); // inform users emit obstacleForceChanged(force.x, force.y); return force; } Ped::Tvector Agent::myForce(Ped::Tvector desired) const { // run additional forces Ped::Tvector forceValue; foreach (Force* force, forces) { // skip disabled forces if (disabledForces.contains(force->getName())) { // update graphical representation emit additionalForceChanged(force->getName(), 0, 0); continue; } // add force to the total force Ped::Tvector currentForce = force->getForce(desired); // → sanity checks if (!currentForce.isValid()) { ROS_DEBUG("Invalid Force: %s", force->getName().toStdString().c_str()); currentForce = Ped::Tvector(); } forceValue += currentForce; // update graphical representation emit additionalForceChanged(force->getName(), currentForce.x, currentForce.y); } // inform users emit myForceChanged(forceValue.x, forceValue.y); return forceValue; } Ped::Twaypoint* Agent::getCurrentDestination() const { return currentDestination; } Ped::Twaypoint* Agent::updateDestination() { // assign new destination if (!destinations.isEmpty()) { if (currentDestination != nullptr) { // cycle through destinations Waypoint* previousDestination = destinations.takeFirst(); destinations.append(previousDestination); } currentDestination = destinations.first(); } return currentDestination; } void Agent::updateState() { // check state stateMachine->doStateTransition(); } void Agent::move(double h) { if (getType() == Ped::Tagent::ROBOT) { if (CONFIG.robot_mode == RobotMode::TELEOPERATION) { // NOTE: Moving is now done by setting x, y position directly in simulator.cpp // Robot's vx, vy will still be set for the social force model to work properly wrt. other agents. // FIXME: This is a very hacky way of making the robot "move" (=update position in hash tree) without actually moving it double vx = getvx(), vy = getvy(); setvx(0); setvy(0); Ped::Tagent::move(h); setvx(vx); setvy(vy); } else if (CONFIG.robot_mode == RobotMode::CONTROLLED) { if (SCENE.getTime() >= CONFIG.robot_wait_time) { Ped::Tagent::move(h); } } else if (CONFIG.robot_mode == RobotMode::SOCIAL_DRIVE) { Ped::Tagent::setForceFactorSocial(CONFIG.forceSocial * 0.7); Ped::Tagent::setForceFactorObstacle(35); Ped::Tagent::setForceFactorDesired(4.2); Ped::Tagent::setVmax(1.6); Ped::Tagent::SetRadius(0.4); Ped::Tagent::move(h); } } else { Ped::Tagent::move(h); } if (getType() == Ped::Tagent::ELDER) { // NOTE - only temporary for setting up a static scene Ped::Tagent::setVmax(0.0); } // inform users emit positionChanged(getx(), gety()); emit velocityChanged(getvx(), getvy()); emit accelerationChanged(getax(), getay()); } const QList<Waypoint*>& Agent::getWaypoints() const { return destinations; } bool Agent::setWaypoints(const QList<Waypoint*>& waypointsIn) { destinations = waypointsIn; return true; } bool Agent::addWaypoint(Waypoint* waypointIn) { destinations.append(waypointIn); return true; } bool Agent::removeWaypoint(Waypoint* waypointIn) { int removeCount = destinations.removeAll(waypointIn); return (removeCount > 0); } bool Agent::needNewDestination() const { if (waypointplanner == nullptr) return (!destinations.isEmpty()); else { // ask waypoint planner return waypointplanner->hasCompletedDestination(); } } Ped::Twaypoint* Agent::getCurrentWaypoint() const { // sanity checks if (waypointplanner == nullptr) return nullptr; // ask waypoint planner return waypointplanner->getCurrentWaypoint(); } bool Agent::isInGroup() const { return (group != nullptr); } AgentGroup* Agent::getGroup() const { return group; } void Agent::setGroup(AgentGroup* groupIn) { group = groupIn; } bool Agent::addForce(Force* forceIn) { forces.append(forceIn); // inform users emit forceAdded(forceIn->getName()); // report success return true; } bool Agent::removeForce(Force* forceIn) { int removeCount = forces.removeAll(forceIn); // inform users emit forceRemoved(forceIn->getName()); // report success if a Behavior has been removed return (removeCount >= 1); } AgentStateMachine* Agent::getStateMachine() const { return stateMachine; } WaypointPlanner* Agent::getWaypointPlanner() const { return waypointplanner; } void Agent::setWaypointPlanner(WaypointPlanner* plannerIn) { waypointplanner = plannerIn; } QList<const Agent*> Agent::getNeighbors() const { // upcast neighbors QList<const Agent*> output; for (const Ped::Tagent* neighbor : neighbors) { const Agent* upNeighbor = dynamic_cast<const Agent*>(neighbor); if (upNeighbor != nullptr) output.append(upNeighbor); } return output; } void Agent::disableForce(const QString& forceNameIn) { // disable force by adding it to the list of disabled forces disabledForces.append(forceNameIn); } void Agent::enableAllForces() { // remove all forces from disabled list disabledForces.clear(); } void Agent::setPosition(double xIn, double yIn) { // call super class' method Ped::Tagent::setPosition(xIn, yIn); // inform users emit positionChanged(xIn, yIn); } void Agent::setX(double xIn) { setPosition(xIn, gety()); } void Agent::setY(double yIn) { setPosition(getx(), yIn); } void Agent::setType(Ped::Tagent::AgentType typeIn) { // call super class' method Ped::Tagent::setType(typeIn); // inform users emit typeChanged(typeIn); } Ped::Tvector Agent::getDesiredDirection() const { return desiredforce; } Ped::Tvector Agent::getWalkingDirection() const { return v; } Ped::Tvector Agent::getSocialForce() const { return socialforce; } Ped::Tvector Agent::getObstacleForce() const { return obstacleforce; } Ped::Tvector Agent::getMyForce() const { return myforce; } QPointF Agent::getVisiblePosition() const { return QPointF(getx(), gety()); } void Agent::setVisiblePosition(const QPointF& positionIn) { // check and apply new position if (positionIn != getVisiblePosition()) setPosition(positionIn.x(), positionIn.y()); } QString Agent::toString() const { return tr("Agent %1 (@%2,%3)").arg(getId()).arg(getx()).arg(gety()); }
c++
code
10,242
2,150
/* * Copyright (c) 2018-2020, Andreas Kling <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <AK/NonnullRefPtrVector.h> #include <AK/Singleton.h> #include <AK/StringBuilder.h> #include <AK/StringView.h> #include <Kernel/API/InodeWatcherEvent.h> #include <Kernel/FileSystem/Custody.h> #include <Kernel/FileSystem/Inode.h> #include <Kernel/FileSystem/InodeWatcher.h> #include <Kernel/FileSystem/VirtualFileSystem.h> #include <Kernel/KBufferBuilder.h> #include <Kernel/Net/LocalSocket.h> #include <Kernel/VM/SharedInodeVMObject.h> namespace Kernel { static SpinLock s_all_inodes_lock; static AK::Singleton<InlineLinkedList<Inode>> s_list; SpinLock<u32>& Inode::all_inodes_lock() { return s_all_inodes_lock; } InlineLinkedList<Inode>& Inode::all_with_lock() { ASSERT(s_all_inodes_lock.is_locked()); return *s_list; } void Inode::sync() { NonnullRefPtrVector<Inode, 32> inodes; { ScopedSpinLock all_inodes_lock(s_all_inodes_lock); for (auto& inode : all_with_lock()) { if (inode.is_metadata_dirty()) inodes.append(inode); } } for (auto& inode : inodes) { ASSERT(inode.is_metadata_dirty()); inode.flush_metadata(); } } KResultOr<NonnullOwnPtr<KBuffer>> Inode::read_entire(FileDescription* description) const { KBufferBuilder builder; ssize_t nread; u8 buffer[4096]; off_t offset = 0; for (;;) { auto buf = UserOrKernelBuffer::for_kernel_buffer(buffer); nread = read_bytes(offset, sizeof(buffer), buf, description); if (nread < 0) return KResult(nread); ASSERT(nread <= (ssize_t)sizeof(buffer)); if (nread <= 0) break; builder.append((const char*)buffer, nread); offset += nread; if (nread < (ssize_t)sizeof(buffer)) break; } if (nread < 0) { klog() << "Inode::read_entire: ERROR: " << nread; return KResult(nread); } auto entire_file = builder.build(); if (!entire_file) return KResult(-ENOMEM); return entire_file.release_nonnull(); } KResultOr<NonnullRefPtr<Custody>> Inode::resolve_as_link(Custody& base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level) const { // The default implementation simply treats the stored // contents as a path and resolves that. That is, it // behaves exactly how you would expect a symlink to work. auto contents_or = read_entire(); if (contents_or.is_error()) return contents_or.error(); auto& contents = contents_or.value(); auto path = StringView(contents->data(), contents->size()); return VFS::the().resolve_path(path, base, out_parent, options, symlink_recursion_level); } Inode::Inode(FS& fs, unsigned index) : m_fs(fs) , m_index(index) { ScopedSpinLock all_inodes_lock(s_all_inodes_lock); all_with_lock().append(this); } Inode::~Inode() { ScopedSpinLock all_inodes_lock(s_all_inodes_lock); all_with_lock().remove(this); } void Inode::will_be_destroyed() { LOCKER(m_lock); if (m_metadata_dirty) flush_metadata(); } void Inode::inode_contents_changed(off_t offset, ssize_t size, const UserOrKernelBuffer& data) { LOCKER(m_lock); if (auto shared_vmobject = this->shared_vmobject()) shared_vmobject->inode_contents_changed({}, offset, size, data); } void Inode::inode_size_changed(size_t old_size, size_t new_size) { LOCKER(m_lock); if (auto shared_vmobject = this->shared_vmobject()) shared_vmobject->inode_size_changed({}, old_size, new_size); } int Inode::set_atime(time_t) { return -ENOTIMPL; } int Inode::set_ctime(time_t) { return -ENOTIMPL; } int Inode::set_mtime(time_t) { return -ENOTIMPL; } KResult Inode::increment_link_count() { return KResult(-ENOTIMPL); } KResult Inode::decrement_link_count() { return KResult(-ENOTIMPL); } void Inode::set_shared_vmobject(SharedInodeVMObject& vmobject) { LOCKER(m_lock); m_shared_vmobject = vmobject; } bool Inode::bind_socket(LocalSocket& socket) { LOCKER(m_lock); if (m_socket) return false; m_socket = socket; return true; } bool Inode::unbind_socket() { LOCKER(m_lock); if (!m_socket) return false; m_socket = nullptr; return true; } void Inode::register_watcher(Badge<InodeWatcher>, InodeWatcher& watcher) { LOCKER(m_lock); ASSERT(!m_watchers.contains(&watcher)); m_watchers.set(&watcher); } void Inode::unregister_watcher(Badge<InodeWatcher>, InodeWatcher& watcher) { LOCKER(m_lock); ASSERT(m_watchers.contains(&watcher)); m_watchers.remove(&watcher); } NonnullRefPtr<FIFO> Inode::fifo() { LOCKER(m_lock); ASSERT(metadata().is_fifo()); // FIXME: Release m_fifo when it is closed by all readers and writers if (!m_fifo) m_fifo = FIFO::create(metadata().uid); ASSERT(m_fifo); return *m_fifo; } void Inode::set_metadata_dirty(bool metadata_dirty) { LOCKER(m_lock); if (metadata_dirty) { // Sanity check. ASSERT(!fs().is_readonly()); } if (m_metadata_dirty == metadata_dirty) return; m_metadata_dirty = metadata_dirty; if (m_metadata_dirty) { // FIXME: Maybe we should hook into modification events somewhere else, I'm not sure where. // We don't always end up on this particular code path, for instance when writing to an ext2fs file. for (auto& watcher : m_watchers) { watcher->notify_inode_event({}, InodeWatcherEvent::Type::Modified); } } } void Inode::did_add_child(const InodeIdentifier& child_id) { LOCKER(m_lock); for (auto& watcher : m_watchers) { watcher->notify_child_added({}, child_id); } } void Inode::did_remove_child(const InodeIdentifier& child_id) { LOCKER(m_lock); for (auto& watcher : m_watchers) { watcher->notify_child_removed({}, child_id); } } KResult Inode::prepare_to_write_data() { // FIXME: It's a poor design that filesystems are expected to call this before writing out data. // We should funnel everything through an interface at the VFS layer so this can happen from a single place. LOCKER(m_lock); if (fs().is_readonly()) return KResult(-EROFS); auto metadata = this->metadata(); if (metadata.is_setuid() || metadata.is_setgid()) { dbgln("Inode::prepare_to_write_data(): Stripping SUID/SGID bits from {}", identifier()); return chmod(metadata.mode & ~(04000 | 02000)); } return KSuccess; } RefPtr<SharedInodeVMObject> Inode::shared_vmobject() const { LOCKER(m_lock); return m_shared_vmobject.strong_ref(); } bool Inode::is_shared_vmobject(const SharedInodeVMObject& other) const { LOCKER(m_lock); return m_shared_vmobject.unsafe_ptr() == &other; } }
c++
code
8,178
1,684
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // clang-format off #include "net.h" #include "masternodeconfig.h" #include "util.h" #include "ui_interface.h" #include "base58.h" // clang-format on CMasternodeConfig masternodeConfig; void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); entries.push_back(cme); } bool CMasternodeConfig::read(std::string& strErr) { int linenumber = 1; boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile(); boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile); if (!streamConfig.good()) { FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a"); if (configFile != NULL) { std::string strHeader = "# Masternode config file\n" "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" "# Example: mn1 127.0.0.2:19687 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile); fclose(configFile); } return true; // Nothing to read, so just return } for (std::string line; std::getline(streamConfig, line); linenumber++) { if (line.empty()) continue; std::istringstream iss(line); std::string comment, alias, ip, privKey, txHash, outputIndex; if (iss >> comment) { if (comment.at(0) == '#') continue; iss.str(line); iss.clear(); } if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { iss.str(line); iss.clear(); if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { strErr = _("Could not parse masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } } if (Params().NetworkID() == CBaseChainParams::MAIN) { if (CService(ip).GetPort() != 19687) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + _("(must be 19687 for mainnet)"); streamConfig.close(); return false; } } else if (CService(ip).GetPort() == 19687) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + _("(19687 could be used only on mainnet)"); streamConfig.close(); return false; } add(alias, ip, privKey, txHash, outputIndex); } streamConfig.close(); return true; } bool CMasternodeConfig::CMasternodeEntry::castOutputIndex(int &n) { try { n = std::stoi(outputIndex); } catch (const std::exception e) { LogPrintf("%s: %s on getOutputIndex\n", __func__, e.what()); return false; } return true; }
c++
code
3,587
778
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/hw/bcm/BcmPortUtils.h" #include "fboss/agent/FbossError.h" #include "fboss/agent/hw/bcm/BcmError.h" #include <folly/logging/xlog.h> #include <thrift/lib/cpp/util/EnumUtils.h> namespace facebook::fboss { const PortSpeed2TransmitterTechAndMode& getSpeedToTransmitterTechAndMode() { // This allows mapping from a speed and port transmission technology // to a broadcom supported interface static const PortSpeed2TransmitterTechAndMode kPortTypeMapping = { {cfg::PortSpeed::HUNDREDG, {{TransmitterTechnology::COPPER, BCM_PORT_IF_CR4}, {TransmitterTechnology::OPTICAL, BCM_PORT_IF_CAUI}, // What to default to {TransmitterTechnology::UNKNOWN, BCM_PORT_IF_CAUI}}}, {cfg::PortSpeed::FIFTYG, {{TransmitterTechnology::COPPER, BCM_PORT_IF_CR2}, {TransmitterTechnology::OPTICAL, BCM_PORT_IF_CAUI}, // What to default to {TransmitterTechnology::UNKNOWN, BCM_PORT_IF_CR2}}}, {cfg::PortSpeed::FORTYG, {{TransmitterTechnology::COPPER, BCM_PORT_IF_CR4}, {TransmitterTechnology::OPTICAL, BCM_PORT_IF_XLAUI}, // What to default to {TransmitterTechnology::UNKNOWN, BCM_PORT_IF_XLAUI}}}, {cfg::PortSpeed::TWENTYFIVEG, {{TransmitterTechnology::COPPER, BCM_PORT_IF_CR}, {TransmitterTechnology::OPTICAL, BCM_PORT_IF_CAUI}, // What to default to {TransmitterTechnology::UNKNOWN, BCM_PORT_IF_CR}}}, {cfg::PortSpeed::TWENTYG, {{TransmitterTechnology::COPPER, BCM_PORT_IF_CR}, // We don't expect 20G optics // What to default to {TransmitterTechnology::UNKNOWN, BCM_PORT_IF_CR}}}, {cfg::PortSpeed::XG, {{TransmitterTechnology::COPPER, BCM_PORT_IF_CR}, {TransmitterTechnology::OPTICAL, BCM_PORT_IF_SFI}, // What to default to {TransmitterTechnology::UNKNOWN, BCM_PORT_IF_CR}}}, {cfg::PortSpeed::GIGE, {{TransmitterTechnology::COPPER, BCM_PORT_IF_GMII}, // We don't expect 1G optics // What to default to {TransmitterTechnology::UNKNOWN, BCM_PORT_IF_GMII}}}}; return kPortTypeMapping; } uint32_t getDesiredPhyLaneConfig( TransmitterTechnology tech, cfg::PortSpeed speed) { // see shared/port.h for what these various shifts mean. I elide // them here simply because they are very verbose. if (tech == TransmitterTechnology::BACKPLANE) { if (speed == cfg::PortSpeed::FORTYG) { // DFE + BACKPLANE + NRZ return 0x8004; } else if (speed == cfg::PortSpeed::HUNDREDG) { // DFE + BACKPLANE + PAM4 + NS return 0x5004; } } else if (tech == TransmitterTechnology::COPPER) { if (speed == cfg::PortSpeed::FORTYG) { // DFE + COPPER + NRZ return 0x8024; } else if (speed == cfg::PortSpeed::HUNDREDG) { // DFE + COPPER + PAM4 + NS return 0x5024; } } // TODO: add more mappings + better error message throw std::runtime_error("Unsupported tech+speed in port_resource"); } } // namespace facebook::fboss namespace facebook::fboss::utility { bcm_port_phy_fec_t phyFecModeToBcmPortPhyFec(phy::FecMode fec) { switch (fec) { case phy::FecMode::NONE: return bcmPortPhyFecNone; case phy::FecMode::CL74: return bcmPortPhyFecBaseR; case phy::FecMode::CL91: return bcmPortPhyFecRsFec; case phy::FecMode::RS528: return bcmPortPhyFecRsFec; case phy::FecMode::RS544: return bcmPortPhyFecRs544; case phy::FecMode::RS544_2N: return bcmPortPhyFecRs544_2xN; }; throw facebook::fboss::FbossError( "Unsupported fec type: ", apache::thrift::util::enumNameSafe(fec)); } uint32_t getDesiredPhyLaneConfig(const phy::PortProfileConfig& profileCfg) { uint32_t laneConfig = 0; // PortResource setting needs interface mode from profile config uint32_t medium = 0; if (auto interfaceMode = profileCfg.get_iphy().interfaceMode_ref()) { switch (*interfaceMode) { case phy::InterfaceMode::KR: case phy::InterfaceMode::KR2: case phy::InterfaceMode::KR4: case phy::InterfaceMode::KR8: case phy::InterfaceMode::CAUI4_C2C: case phy::InterfaceMode::CAUI4_C2M: medium = BCM_PORT_RESOURCE_PHY_LANE_CONFIG_MEDIUM_BACKPLANE; break; case phy::InterfaceMode::CR: case phy::InterfaceMode::CR2: case phy::InterfaceMode::CR4: medium = BCM_PORT_RESOURCE_PHY_LANE_CONFIG_MEDIUM_COPPER_CABLE; break; case phy::InterfaceMode::SR: case phy::InterfaceMode::SR4: medium = BCM_PORT_RESOURCE_PHY_LANE_CONFIG_MEDIUM_OPTICS; break; default: throw facebook::fboss::FbossError( "Unsupported interface mode: ", apache::thrift::util::enumNameSafe(*interfaceMode)); } } else { throw facebook::fboss::FbossError( "No iphy interface mode in profileCfg for speed: ", apache::thrift::util::enumNameSafe(profileCfg.get_speed())); } BCM_PORT_RESOURCE_PHY_LANE_CONFIG_MEDIUM_SET(laneConfig, medium); switch (profileCfg.get_iphy().get_modulation()) { case phy::IpModulation::PAM4: // PAM4 + NS BCM_PORT_RESOURCE_PHY_LANE_CONFIG_FORCE_PAM4_SET(laneConfig); BCM_PORT_RESOURCE_PHY_LANE_CONFIG_FORCE_NS_SET(laneConfig); break; case phy::IpModulation::NRZ: // NRZ BCM_PORT_RESOURCE_PHY_LANE_CONFIG_FORCE_NRZ_SET(laneConfig); break; }; // always enable DFE BCM_PORT_RESOURCE_PHY_LANE_CONFIG_DFE_SET(laneConfig); return laneConfig; } bcm_gport_t getPortGport(int unit, int port) { bcm_gport_t portGport; auto rv = bcm_port_gport_get(unit, port, &portGport); facebook::fboss::bcmCheckError(rv, "failed to get gport for port"); return portGport; } bcm_port_loopback_t fbToBcmLoopbackMode(cfg::PortLoopbackMode inMode) { switch (inMode) { case cfg::PortLoopbackMode::NONE: return BCM_PORT_LOOPBACK_NONE; case cfg::PortLoopbackMode::PHY: return BCM_PORT_LOOPBACK_PHY; case cfg::PortLoopbackMode::MAC: return BCM_PORT_LOOPBACK_MAC; } CHECK(0) << "Should never reach here"; return BCM_PORT_LOOPBACK_NONE; } } // namespace facebook::fboss::utility
c++
code
6,507
1,212
#include <hdlConvertor/notImplementedLogger.h> #include <hdlConvertor/hdlObjects/hdlCall.h> #include <hdlConvertor/hdlObjects/hdlStm_others.h> #include <hdlConvertor/vhdlConvertor/archParser.h> #include <hdlConvertor/vhdlConvertor/designFileParser.h> #include <hdlConvertor/vhdlConvertor/entityParser.h> #include <hdlConvertor/vhdlConvertor/packageHeaderParser.h> #include <hdlConvertor/vhdlConvertor/packageParser.h> #include <hdlConvertor/vhdlConvertor/referenceParser.h> namespace hdlConvertor { namespace vhdl { using vhdlParser = vhdl_antlr::vhdlParser; using namespace hdlConvertor::hdlObjects; VhdlDesignFileParser::VhdlDesignFileParser(antlr4::TokenStream &tokens, HdlContext &ctx, bool _hierarchyOnly) : BaseHdlParser(tokens, ctx, _hierarchyOnly), commentParser(tokens) { } void VhdlDesignFileParser::visitDesign_file( vhdlParser::Design_fileContext *ctx) { if (!ctx) return; // design_file // : ( design_unit )* EOF // ; for (auto u : ctx->design_unit()) { VhdlDesignFileParser::visitDesign_unit(u); } } void VhdlDesignFileParser::visitDesign_unit( vhdlParser::Design_unitContext *ctx) { if (!ctx) return; // design_unit // : context_clause library_unit // ; VhdlDesignFileParser::visitContext_clause(ctx->context_clause()); VhdlDesignFileParser::visitLibrary_unit(ctx->library_unit()); } void VhdlDesignFileParser::visitLibrary_unit( vhdlParser::Library_unitContext *ctx) { if (!ctx) return; // library_unit // : secondary_unit | primary_unit // ; VhdlDesignFileParser::visitSecondary_unit(ctx->secondary_unit()); VhdlDesignFileParser::visitPrimary_unit(ctx->primary_unit()); } void VhdlDesignFileParser::visitSecondary_unit( vhdlParser::Secondary_unitContext *ctx) { if (!ctx) return; // secondary_unit // : architecture_body // | package_body // ; auto arch = ctx->architecture_body(); if (arch) { VhdlArchParser aparser(hierarchyOnly); auto a = aparser.visitArchitecture_body(arch); context.objs.push_back(move(a)); } auto pack = ctx->package_body(); if (pack) { VhdlPackageParser pparser(hierarchyOnly); auto p = pparser.visitPackage_body(pack); context.objs.push_back(move(p)); } } void VhdlDesignFileParser::visitContext_clause( vhdlParser::Context_clauseContext *ctx) { if (!ctx) return; // context_clause // : ( context_item )* // ; for (auto item : ctx->context_item()) { visitContext_item(item); } } void VhdlDesignFileParser::visitPrimary_unit( vhdlParser::Primary_unitContext *ctx) { if (!ctx) return; // primary_unit // : entity_declaration // | configuration_declaration // | package_declaration // ; auto ed = ctx->entity_declaration(); if (ed) { VhdlEntityParser eParser(commentParser, hierarchyOnly); auto e = eParser.visitEntity_declaration(ed); context.objs.push_back(move(e)); return; } auto cd = ctx->configuration_declaration(); if (cd) { NotImplementedLogger::print( "DesignFileParser.visitConfiguration_declaration", cd); return; } auto pd = ctx->package_declaration(); if (pd) { VhdlPackageHeaderParser php(hierarchyOnly); auto ph = php.visitPackage_declaration(pd); context.objs.push_back(std::move(ph)); } } void VhdlDesignFileParser::visitContext_item( vhdlParser::Context_itemContext *ctx) { // context_item // : library_clause // | use_clause // ; auto l = ctx->library_clause(); if (l) { NotImplementedLogger::print( "DesignFileParser.visitContext_item - library_clause", l); return; //libraries are ignored } auto u = ctx->use_clause(); if (u) { visitUse_clause(u, context.objs); } } void flatten_doted_expr(std::unique_ptr<iHdlExpr> e, std::vector<std::unique_ptr<iHdlExpr>> &arr) { auto o = dynamic_cast<HdlCall*>(e->data); if (o) { if (o->op == HdlOperatorType::DOT) { for (auto &_o : o->operands) { flatten_doted_expr(std::move(_o), arr); } o->operands.clear(); return; } } arr.push_back(move(e)); } void VhdlDesignFileParser::visitUse_clause(vhdlParser::Use_clauseContext *ctx, std::vector<std::unique_ptr<iHdlObj>> &res) { // use_clause: // USE selected_name (COMMA selected_name)* SEMI // ; auto sns = ctx->selected_name(); for (auto sn : sns) { auto r = VhdlReferenceParser::visitSelected_name(sn); std::vector<std::unique_ptr<iHdlExpr>> ref; flatten_doted_expr(move(r), ref); auto imp = std::make_unique<HdlStmImport>(ref); res.push_back(std::move(imp)); } } } }
c++
code
4,414
927
// // Created by Spud on 7/16/21. // #ifndef TUMBLRAPI_ASK_HPP #define TUMBLRAPI_ASK_HPP #include "layout.hpp" #include "npf/attribution.hpp" /** * TODO Documentation */ class Ask : public Layout { public: /** * TODO Documentation */ Ask() : Layout(layoutType::ask) {}; /** * If the ask is not anonymous, this will include information about the blog that submitted the ask. */ Attribution attribution; /** * TODO Documentation * @param array */ void populateBlocks(const JSON_ARRAY &array) override; /** * TODO Documentation * @param entry */ void populateNPF(JSON_OBJECT entry) override; }; #endif //TUMBLRAPI_ASK_HPP
c++
code
658
138
#include "CSerialPort.h" #include <Windows.h> #include <assert.h> CSerialPort::CSerialPort() : hCom(INVALID_HANDLE_VALUE) { } CSerialPort::~CSerialPort() { Close(); } bool CSerialPort::Open(const char* port_name) { assert(!IsOpen()); Close(); hCom = CreateFileA(port_name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hCom == INVALID_HANDLE_VALUE) { return FALSE; // Use GetLastError() to know the reason } DCB dcb; dcb.DCBlength = sizeof(dcb); GetCommState(hCom, &dcb); dcb.BaudRate = 38400; dcb.ByteSize = 8; dcb.StopBits = ONESTOPBIT; dcb.Parity = NOPARITY; dcb.fDsrSensitivity = 0; dcb.fOutxCtsFlow = 0; dcb.fOutxDsrFlow = 0; dcb.fInX = 0; dcb.fOutX = 0; dcb.fDtrControl = DTR_CONTROL_DISABLE; //DTR and RTS 0 dcb.fRtsControl = RTS_CONTROL_DISABLE; SetCommState(hCom, &dcb); COMMTIMEOUTS touts; touts.ReadIntervalTimeout = 0; touts.ReadTotalTimeoutMultiplier = 0; touts.ReadTotalTimeoutConstant = 100; touts.WriteTotalTimeoutConstant = 10; touts.WriteTotalTimeoutMultiplier = 0; SetCommTimeouts(hCom, &touts); //SetCommMask(hCom, EV_CTS | EV_DSR | EV_RING | EV_RLSD); PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR); return TRUE; } void CSerialPort::Close() { if (hCom != INVALID_HANDLE_VALUE) { CloseHandle(hCom); hCom = INVALID_HANDLE_VALUE; } } bool CSerialPort::IsOpen() { return (hCom != INVALID_HANDLE_VALUE); } unsigned long CSerialPort::Read(unsigned char *buff, unsigned long len) { DWORD count(0); if (hCom != INVALID_HANDLE_VALUE) { ReadFile(hCom, buff, len, &count, NULL); } return count; } unsigned long CSerialPort::Write(const unsigned char *buff, unsigned long len) { DWORD count(0); if (hCom != INVALID_HANDLE_VALUE) { WriteFile(hCom, buff, len, &count, NULL); } return count; } // //BOOL CSerialPort::Get_CD_State() //{ // if (hCom != INVALID_HANDLE_VALUE) // { // DWORD ModemStat; // if (GetCommModemStatus(hCom, &ModemStat)) // { // return (ModemStat & MS_RLSD_ON) > 0; //Not sure // } // else // { // return FALSE; // } // } // else // { // return FALSE; // } //} // //BOOL CSerialPort::Get_CTS_State() //{ // if (hCom != INVALID_HANDLE_VALUE) // { // DWORD ModemStat; // if (GetCommModemStatus(hCom, &ModemStat)) // { // return (ModemStat & MS_CTS_ON) > 0; // } // else // { // return FALSE; // } // } // else // { // return FALSE; // } //} // //BOOL CSerialPort::Get_DSR_State() //{ // if (hCom != INVALID_HANDLE_VALUE) // { // DWORD ModemStat; // if (GetCommModemStatus(hCom, &ModemStat)) // { // return (ModemStat & MS_DSR_ON) > 0; // } // else // { // return FALSE; // } // } // else // { // return FALSE; // } //} // //BOOL CSerialPort::Get_RI_State() //{ // if (hCom != INVALID_HANDLE_VALUE) // { // DWORD ModemStat; // if (GetCommModemStatus(hCom, &ModemStat)) // { // return (ModemStat & MS_RING_ON) > 0; // } // else // { // return FALSE; // } // } // else // { // return FALSE; // } //} // //void CSerialPort::Set_DTR_State(BOOL state) //{ // if (hCom != INVALID_HANDLE_VALUE) // { // EscapeCommFunction(hCom, (state ? SETDTR : CLRDTR)); // } //} // //void CSerialPort::Set_RTS_State(BOOL state) //{ // if (hCom != INVALID_HANDLE_VALUE) // { // EscapeCommFunction(hCom, (state ? SETRTS : CLRRTS)); // } //}
c++
code
3,300
785
// // Created by hao on 5/16/17. // #include "controller.h" #include "camera.h" bool Controller::bRecompile = false; bool Controller::bSave = false; double Controller::lastX = 0; double Controller::lastY = 0; bool Controller::firstMouse = true; bool Controller::keys[1024] = {false}; Camera *Controller::mainCamera = nullptr; void Controller::KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) keys[key] = true; else if (action == GLFW_RELEASE) keys[key] = false; } if (key == GLFW_KEY_R && action == GLFW_RELEASE) { bRecompile = true; } if (key == GLFW_KEY_P && action == GLFW_RELEASE) { bSave = true; } if (key == GLFW_KEY_L && action == GLFW_PRESS) { cout << "Log point" << endl; } if (key == GLFW_KEY_0 && action == GLFW_RELEASE) { if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } else { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } } } void Controller::MouseCallback(GLFWwindow *window, double xpos, double ypos) { #ifdef linux if (__glibc_unlikely(firstMouse)) { #else if (firstMouse) { #endif lastX = xpos; lastY = ypos; firstMouse = false; } mainCamera->ProcessMouseMovement((GLfloat)(xpos - lastX), (GLfloat)(lastY - ypos)); lastX = xpos; lastY = ypos; } void Controller::Movement(double deltaTime) { // Camera controls if (keys[GLFW_KEY_W]) mainCamera->ProcessKeyboard(CAM_FORWARD, deltaTime); if (keys[GLFW_KEY_S]) mainCamera->ProcessKeyboard(CAM_BACKWARD, deltaTime); if (keys[GLFW_KEY_A]) mainCamera->ProcessKeyboard(CAM_LEFT, deltaTime); if (keys[GLFW_KEY_D]) mainCamera->ProcessKeyboard(CAM_RIGHT, deltaTime); } void Controller::BindCamera(Camera *camera) { mainCamera = camera; }
c++
code
2,210
459
#include <precompiledapplication.h> #include <graphics/commondefinitions.h> #include <graphics/iapplication.h> #include <graphics/irenderer.h> #include <chrono> #include <thread> #include "box2dtests.h" //#define PROCESS_MULTI_PARAMS_STRING(FORMAT_VAR,STRING_NAME) va_list args;\ // va_start(args, FORMAT_VAR); \ // int length = _vscprintf(FORMAT_VAR, args) + 1; \ // char* buffer = new char[length]; \ // vsprintf_s(buffer, length, FORMAT_VAR, args); \ // STRING_NAME = std::string(buffer); \ // delete[] buffer; \ // va_end(args); int main( int argc, char* argv[] ) { auto graphicsPtr = puma::app::IApplication::create(); puma::app::Extent wExtent = { 1000,1000, 100, 100 }; graphicsPtr->init(); graphicsPtr->createWindow( wExtent, "PhysicsTest" ); //======================================================================== std::unique_ptr<Box2DTest> libTest = std::make_unique<Box2DTest>(); libTest->init( graphicsPtr.get() ); while ( !graphicsPtr->shouldQuit() ) { graphicsPtr->update(); libTest->update(); puma::app::IRenderer* renderer = graphicsPtr->getDefaultRenderer(); renderer->beginRender(); libTest->render(); renderer->endRender(); std::this_thread::sleep_for( std::chrono::milliseconds( 16 ) ); } return 0; }
c++
code
1,262
307
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/lighthouse/v20200324/model/DeleteSnapshotsRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Lighthouse::V20200324::Model; using namespace std; DeleteSnapshotsRequest::DeleteSnapshotsRequest() : m_snapshotIdsHasBeenSet(false) { } string DeleteSnapshotsRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_snapshotIdsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SnapshotIds"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_snapshotIds.begin(); itr != m_snapshotIds.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } vector<string> DeleteSnapshotsRequest::GetSnapshotIds() const { return m_snapshotIds; } void DeleteSnapshotsRequest::SetSnapshotIds(const vector<string>& _snapshotIds) { m_snapshotIds = _snapshotIds; m_snapshotIdsHasBeenSet = true; } bool DeleteSnapshotsRequest::SnapshotIdsHasBeenSet() const { return m_snapshotIdsHasBeenSet; }
c++
code
2,223
427
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2020 Intel Corporation #ifndef OPENCV_GAPI_VIDEO_HPP #define OPENCV_GAPI_VIDEO_HPP #include <utility> // std::tuple #include <opencv2/gapi/gkernel.hpp> /** \defgroup gapi_video G-API Video processing functionality */ namespace cv { namespace gapi { namespace video { using GBuildPyrOutput = std::tuple<GArray<GMat>, GScalar>; using GOptFlowLKOutput = std::tuple<cv::GArray<cv::Point2f>, cv::GArray<uchar>, cv::GArray<float>>; G_TYPED_KERNEL(GBuildOptFlowPyramid, <GBuildPyrOutput(GMat,Size,GScalar,bool,int,int,bool)>, "org.opencv.video.buildOpticalFlowPyramid") { static std::tuple<GArrayDesc,GScalarDesc> outMeta(GMatDesc,const Size&,GScalarDesc,bool,int,int,bool) { return std::make_tuple(empty_array_desc(), empty_scalar_desc()); } }; G_TYPED_KERNEL(GCalcOptFlowLK, <GOptFlowLKOutput(GMat,GMat,cv::GArray<cv::Point2f>,cv::GArray<cv::Point2f>,Size, GScalar,TermCriteria,int,double)>, "org.opencv.video.calcOpticalFlowPyrLK") { static std::tuple<GArrayDesc,GArrayDesc,GArrayDesc> outMeta(GMatDesc,GMatDesc,GArrayDesc, GArrayDesc,const Size&,GScalarDesc, const TermCriteria&,int,double) { return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); } }; G_TYPED_KERNEL(GCalcOptFlowLKForPyr, <GOptFlowLKOutput(cv::GArray<cv::GMat>,cv::GArray<cv::GMat>, cv::GArray<cv::Point2f>,cv::GArray<cv::Point2f>,Size,GScalar, TermCriteria,int,double)>, "org.opencv.video.calcOpticalFlowPyrLKForPyr") { static std::tuple<GArrayDesc,GArrayDesc,GArrayDesc> outMeta(GArrayDesc,GArrayDesc, GArrayDesc,GArrayDesc, const Size&,GScalarDesc, const TermCriteria&,int,double) { return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); } }; enum BackgroundSubtractorType { TYPE_BS_MOG2, TYPE_BS_KNN }; /** @brief Structure for the Background Subtractor operation's initialization parameters.*/ struct BackgroundSubtractorParams { //! Type of the Background Subtractor operation. BackgroundSubtractorType operation = TYPE_BS_MOG2; //! Length of the history. int history = 500; //! For MOG2: Threshold on the squared Mahalanobis distance between the pixel //! and the model to decide whether a pixel is well described by //! the background model. //! For KNN: Threshold on the squared distance between the pixel and the sample //! to decide whether a pixel is close to that sample. double threshold = 16; //! If true, the algorithm will detect shadows and mark them. bool detectShadows = true; //! The value between 0 and 1 that indicates how fast //! the background model is learnt. //! Negative parameter value makes the algorithm use some automatically //! chosen learning rate. double learningRate = -1; //! default constructor BackgroundSubtractorParams() {} /** Full constructor @param op MOG2/KNN Background Subtractor type. @param histLength Length of the history. @param thrshld For MOG2: Threshold on the squared Mahalanobis distance between the pixel and the model to decide whether a pixel is well described by the background model. For KNN: Threshold on the squared distance between the pixel and the sample to decide whether a pixel is close to that sample. @param detect If true, the algorithm will detect shadows and mark them. It decreases the speed a bit, so if you do not need this feature, set the parameter to false. @param lRate The value between 0 and 1 that indicates how fast the background model is learnt. Negative parameter value makes the algorithm to use some automatically chosen learning rate. */ BackgroundSubtractorParams(BackgroundSubtractorType op, int histLength, double thrshld, bool detect, double lRate) : operation(op), history(histLength), threshold(thrshld), detectShadows(detect), learningRate(lRate){} }; G_TYPED_KERNEL(GBackgroundSubtractor, <GMat(GMat, BackgroundSubtractorParams)>, "org.opencv.video.BackgroundSubtractor") { static GMatDesc outMeta(const GMatDesc& in, const BackgroundSubtractorParams& bsParams) { GAPI_Assert(bsParams.history >= 0); GAPI_Assert(bsParams.learningRate <= 1); return in.withType(CV_8U, 1); } }; } //namespace video //! @addtogroup gapi_video //! @{ /** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. @note Function textual ID is "org.opencv.video.buildOpticalFlowPyramid" @param img 8-bit input image. @param winSize window size of optical flow algorithm. Must be not less than winSize argument of calcOpticalFlowPyrLK. It is needed to calculate required padding for pyramid levels. @param maxLevel 0-based maximal pyramid level number. @param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is constructed without the gradients then calcOpticalFlowPyrLK will calculate them internally. @param pyrBorder the border mode for pyramid layers. @param derivBorder the border mode for gradients. @param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false to force data copying. @return output pyramid. @return number of levels in constructed pyramid. Can be less than maxLevel. */ GAPI_EXPORTS std::tuple<GArray<GMat>, GScalar> buildOpticalFlowPyramid(const GMat &img, const Size &winSize, const GScalar &maxLevel, bool withDerivatives = true, int pyrBorder = BORDER_REFLECT_101, int derivBorder = BORDER_CONSTANT, bool tryReuseInputImage = true); /** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids. See @cite Bouguet00 . @note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLK" @param prevImg first 8-bit input image (GMat) or pyramid (GArray<GMat>) constructed by buildOpticalFlowPyramid. @param nextImg second input image (GMat) or pyramid (GArray<GMat>) of the same size and the same type as prevImg. @param prevPts GArray of 2D points for which the flow needs to be found; point coordinates must be single-precision floating-point numbers. @param predPts GArray of 2D points initial for the flow search; make sense only when OPTFLOW_USE_INITIAL_FLOW flag is passed; in that case the vector must have the same size as in the input. @param winSize size of the search window at each pyramid level. @param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single level), if set to 1, two levels are used, and so on; if pyramids are passed to input then algorithm will use as many levels as pyramids have but no more than maxLevel. @param criteria parameter, specifying the termination criteria of the iterative search algorithm (after the specified maximum number of iterations criteria.maxCount or when the search window moves by less than criteria.epsilon). @param flags operation flags: - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is not set, then prevPts is copied to nextPts and is considered the initial estimate. - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see minEigThreshold description); if the flag is not set, then L1 distance between patches around the original and a moved point, divided by number of pixels in a window, is used as a error measure. @param minEigThresh the algorithm calculates the minimum eigen value of a 2x2 normal matrix of optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding feature is filtered out and its flow is not processed, so it allows to remove bad points and get a performance boost. @return GArray of 2D points (with single-precision floating-point coordinates) containing the calculated new positions of input features in the second image. @return status GArray (of unsigned chars); each element of the vector is set to 1 if the flow for the corresponding features has been found, otherwise, it is set to 0. @return GArray of errors (doubles); each element of the vector is set to an error for the corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't found then the error is not defined (use the status parameter to find such cases). */ GAPI_EXPORTS std::tuple<GArray<Point2f>, GArray<uchar>, GArray<float>> calcOpticalFlowPyrLK(const GMat &prevImg, const GMat &nextImg, const GArray<Point2f> &prevPts, const GArray<Point2f> &predPts, const Size &winSize = Size(21, 21), const GScalar &maxLevel = 3, const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | TermCriteria::EPS, 30, 0.01), int flags = 0, double minEigThresh = 1e-4); /** @overload @note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLKForPyr" */ GAPI_EXPORTS std::tuple<GArray<Point2f>, GArray<uchar>, GArray<float>> calcOpticalFlowPyrLK(const GArray<GMat> &prevPyr, const GArray<GMat> &nextPyr, const GArray<Point2f> &prevPts, const GArray<Point2f> &predPts, const Size &winSize = Size(21, 21), const GScalar &maxLevel = 3, const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | TermCriteria::EPS, 30, 0.01), int flags = 0, double minEigThresh = 1e-4); /** @brief Gaussian Mixture-based or K-nearest neighbours-based Background/Foreground Segmentation Algorithm. The operation generates a foreground mask. @return Output image is foreground mask, i.e. 8-bit unsigned 1-channel (binary) matrix @ref CV_8UC1. @note Functional textual ID is "org.opencv.video.BackgroundSubtractor" @param src input image: Floating point frame is used without scaling and should be in range [0,255]. @param bsParams Set of initialization parameters for Background Subtractor kernel. */ GAPI_EXPORTS GMat BackgroundSubtractor(const GMat& src, const cv::gapi::video::BackgroundSubtractorParams& bsParams); //! @} gapi_video } //namespace gapi } //namespace cv namespace cv { namespace detail { template<> struct CompileArgTag<cv::gapi::video::BackgroundSubtractorParams> { static const char* tag() { return "org.opencv.video.background_substractor_params"; } }; } // namespace detail } //namespace cv #endif // OPENCV_GAPI_VIDEO_HPP
c++
code
12,624
2,076
//================================================================================================= /*! // \file src/mathtest/dmatdmatadd/LDaDDb.cpp // \brief Source file for the LDaDDb dense matrix/dense matrix addition math test // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DiagonalMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/LowerMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatdmatadd/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'LDaDDb'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions typedef blaze::LowerMatrix< blaze::DynamicMatrix<TypeA> > LDa; typedef blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeB> > DDb; // Creator type definitions typedef blazetest::Creator<LDa> CLDa; typedef blazetest::Creator<DDb> CDDb; // Running tests with small matrices for( size_t i=0UL; i<=9UL; ++i ) { RUN_DMATDMATADD_OPERATION_TEST( CLDa( i ), CDDb( i ) ); } // Running tests with large matrices RUN_DMATDMATADD_OPERATION_TEST( CLDa( 67UL ), CDDb( 67UL ) ); RUN_DMATDMATADD_OPERATION_TEST( CLDa( 128UL ), CDDb( 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix addition:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
c++
code
4,028
1,008
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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 "open3d/core/linalg/Inverse.h" #include <unordered_map> #include "open3d/core/linalg/LinalgHeadersCPU.h" namespace open3d { namespace core { void Inverse(const Tensor &A, Tensor &output) { // Check devices Device device = A.GetDevice(); // Check dtypes Dtype dtype = A.GetDtype(); if (dtype != Dtype::Float32 && dtype != Dtype::Float64) { utility::LogError( "Only tensors with Float32 or Float64 are supported, but " "received {}.", dtype.ToString()); } // Check dimensions SizeVector A_shape = A.GetShape(); if (A_shape.size() != 2) { utility::LogError("Tensor must be 2D, but got {}D.", A_shape.size()); } if (A_shape[0] != A_shape[1]) { utility::LogError("Tensor must be square, but got {} x {}.", A_shape[0], A_shape[1]); } int64_t n = A_shape[0]; if (n == 0) { utility::LogError( "Tensor shapes should not contain dimensions with zero."); } if (device.GetType() == Device::DeviceType::CUDA) { #ifdef BUILD_CUDA_MODULE Tensor ipiv = Tensor::Zeros({n}, Dtype::Int32, device); void *ipiv_data = ipiv.GetDataPtr(); // cuSolver does not support getri, so we have to provide an identity // matrix. This matrix is modified in-place as output. Tensor A_T = A.T().Contiguous(); void *A_data = A_T.GetDataPtr(); output = Tensor::Eye(n, dtype, device); void *output_data = output.GetDataPtr(); InverseCUDA(A_data, ipiv_data, output_data, n, dtype, device); output = output.T(); #else utility::LogError("Unimplemented device."); #endif } else { Dtype ipiv_dtype; if (sizeof(OPEN3D_CPU_LINALG_INT) == 4) { ipiv_dtype = Dtype::Int32; } else if (sizeof(OPEN3D_CPU_LINALG_INT) == 8) { ipiv_dtype = Dtype::Int64; } else { utility::LogError("Unsupported OPEN3D_CPU_LINALG_INT type."); } Tensor ipiv = Tensor::Empty({n}, ipiv_dtype, device); void *ipiv_data = ipiv.GetDataPtr(); // LAPACKE supports getri, A is in-place modified as output. Tensor A_T = A.T().To(device, /*copy=*/true); void *A_data = A_T.GetDataPtr(); InverseCPU(A_data, ipiv_data, nullptr, n, dtype, device); output = A_T.T(); } } } // namespace core } // namespace open3d
c++
code
3,930
919
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "guiutil.h" #include "optionsmodel.h" #include "walletmodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget* parent) : QStackedWidget(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); setCurrentWidget(ui->SendCoins); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); #endif // normal blackbill address field GUIUtil::setupAddressWidget(ui->payTo, this); // just a label for displaying blackbill address(es) ui->payTo_is->setFont(GUIUtil::bitcoinAddressFont()); // Connect signals connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged())); connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked())); connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked())); connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked())); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if (!model) return; AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString& address) { updateLabel(address); } void SendCoinsEntry::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); clear(); } void SendCoinsEntry::clear() { // clear UI elements for normal payment ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->messageTextLabel->clear(); ui->messageTextLabel->hide(); ui->messageLabel->hide(); // clear UI elements for insecure payment request ui->payTo_is->clear(); ui->memoTextLabel_is->clear(); ui->payAmount_is->clear(); // clear UI elements for secure payment request ui->payTo_s->clear(); ui->memoTextLabel_s->clear(); ui->payAmount_s->clear(); // update the display unit, to not use the default ("BIL") updateDisplayUnit(); } void SendCoinsEntry::deleteClicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { if (!model) return false; // Check input validity bool retval = true; // Skip checks for payment request if (recipient.paymentRequest.IsInitialized()) return retval; if (!model->validateAddress(ui->payTo->text())) { ui->payTo->setValid(false); retval = false; } if (!ui->payAmount->validate()) { retval = false; } // Sending a zero amount is invalid if (ui->payAmount->value(0) <= 0) { ui->payAmount->setValid(false); retval = false; } // Reject dust outputs: if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) { ui->payAmount->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { // Payment request if (recipient.paymentRequest.IsInitialized()) return recipient; // Normal payment recipient.address = ui->payTo->text(); recipient.label = ui->addAsLabel->text(); recipient.amount = ui->payAmount->value(); recipient.message = ui->messageTextLabel->text(); return recipient; } QWidget* SendCoinsEntry::setupTabChain(QWidget* prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addAsLabel); QWidget* w = ui->payAmount->setupTabChain(ui->addAsLabel); QWidget::setTabOrder(w, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); return ui->deleteButton; } void SendCoinsEntry::setValue(const SendCoinsRecipient& value) { recipient = value; if (recipient.paymentRequest.IsInitialized()) // payment request { if (recipient.authenticatedMerchant.isEmpty()) // insecure { ui->payTo_is->setText(recipient.address); ui->memoTextLabel_is->setText(recipient.message); ui->payAmount_is->setValue(recipient.amount); ui->payAmount_is->setReadOnly(true); setCurrentWidget(ui->SendCoins_InsecurePaymentRequest); } else // secure { ui->payTo_s->setText(recipient.authenticatedMerchant); ui->memoTextLabel_s->setText(recipient.message); ui->payAmount_s->setValue(recipient.amount); ui->payAmount_s->setReadOnly(true); setCurrentWidget(ui->SendCoins_SecurePaymentRequest); } } else // normal payment { // message ui->messageTextLabel->setText(recipient.message); ui->messageTextLabel->setVisible(!recipient.message.isEmpty()); ui->messageLabel->setVisible(!recipient.message.isEmpty()); ui->addAsLabel->clear(); ui->payTo->setText(recipient.address); // this may set a label from addressbook if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, dont overwrite with an empty label ui->addAsLabel->setText(recipient.label); ui->payAmount->setValue(recipient.amount); } } void SendCoinsEntry::setAddress(const QString& address) { ui->payTo->setText(address); ui->payAmount->setFocus(); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if (model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } bool SendCoinsEntry::updateLabel(const QString& address) { if (!model) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if (!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; }
c++
code
7,390
1,711
// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/asmap.h> #include <test/fuzz/fuzz.h> #include <cstdint> #include <vector> #include <assert.h> void test_one_input(const std::vector<uint8_t>& buffer) { // Encoding: [asmap using 1 bit / byte] 0xFF [addr using 1 bit / byte] bool have_sep = false; size_t sep_pos; for (size_t pos = 0; pos < buffer.size(); ++pos) { uint8_t x = buffer[pos]; if ((x & 0xFE) == 0) continue; if (x == 0xFF) { if (have_sep) return; have_sep = true; sep_pos = pos; } else { return; } } if (!have_sep) return; // Needs exactly 1 separator if (buffer.size() - sep_pos - 1 > 128) return; // At most 128 bits in IP address // Checks on asmap std::vector<bool> asmap(buffer.begin(), buffer.begin() + sep_pos); if (SanityCheckASMap(asmap, buffer.size() - 1 - sep_pos)) { // Verify that for valid asmaps, no prefix (except up to 7 zero padding bits) is valid. std::vector<bool> asmap_prefix = asmap; while (!asmap_prefix.empty() && asmap_prefix.size() + 7 > asmap.size() && asmap_prefix.back() == false) asmap_prefix.pop_back(); while (!asmap_prefix.empty()) { asmap_prefix.pop_back(); assert(!SanityCheckASMap(asmap_prefix, buffer.size() - 1 - sep_pos)); } // No address input should trigger assertions in interpreter std::vector<bool> addr(buffer.begin() + sep_pos + 1, buffer.end()); (void)Interpret(asmap, addr); } }
c++
code
1,717
404
#include "detours.h" #if defined(DETOURS_X64) __asm__ (R"(.intel_syntax .globl Trampoline_ASM_x64 .globl trampoline_template_x64 .globl trampoline_data_x64 Trampoline_ASM_x64: NETIntro: .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 OldProc: .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 NewProc: .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 NETOutro: .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 IsExecutedPtr: .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 .byte 0 trampoline_template_x64: push %rsp push qword ptr [%rsp] and %rsp, 0xFFFFFFFFFFFFFFF0 mov %rax, %rsp push %rdi push %rsi push %rdx push %rcx push %r8 push %r9 sub %rsp, 8 * 16 ## space for SSE registers movups [%rsp + 7 * 16], %xmm0 movups [%rsp + 6 * 16], %xmm1 movups [%rsp + 5 * 16], %xmm2 movups [%rsp + 4 * 16], %xmm3 movups [%rsp + 3 * 16], %xmm4 movups [%rsp + 2 * 16], %xmm5 movups [%rsp + 1 * 16], %xmm6 movups [%rsp + 0 * 16], %xmm7 sub %rsp, 32## shadow space for method calls lea %rax, [%rip + IsExecutedPtr] mov %rax, [%rax] .byte 0xF0 ## interlocked increment execution counter inc qword ptr [%rax] ## is a user handler available? cmp qword ptr [%rip + NewProc], 0 .byte 0x3E ## branch usually taken jne call_net_entry ###################################################################################### call original method lea %rax, [%rip + IsExecutedPtr] mov %rax, [%rax] .byte 0xF0 ## interlocked decrement execution counter dec qword ptr [%rax] lea %rax, [%rip + OldProc] jmp trampoline_exit ###################################################################################### call hook handler or original method... call_net_entry: ## call NET intro lea %rdi, [%rip + IsExecutedPtr + 8] ## Hook handle (only a position hint) ## Here we are under the alignment trick. mov %rdx, [%rsp + 32 + 8 * 16 + 6 * 8 + 8] ## %rdx = original %rsp (address of return address) mov %rsi, [%rdx] ## return address (value stored in original %rsp) call qword ptr [%rip + NETIntro] ## Hook->NETIntro(Hook, RetAddr, InitialRSP)## ## should call original method? test %rax, %rax .byte 0x3E ## branch usually taken jne call_hook_handler ## call original method lea %rax, [%rip + IsExecutedPtr] mov %rax, [%rax] .byte 0xF0 ## interlocked decrement execution counter dec qword ptr [%rax] lea %rax, [%rip + OldProc] jmp trampoline_exit call_hook_handler: ## adjust return address lea %rax, [%rip + call_net_outro] ## Here we are under the alignment trick. mov %r9, [%rsp + 32 + 8 * 16 + 6 * 8 + 8] ## %r9 = original %rsp mov qword ptr [%r9], %rax ## call hook handler lea %rax, [%rip + NewProc] jmp trampoline_exit call_net_outro: ## this is where the handler returns... ## call NET outro ## Here we are NOT under the alignment trick. push 0 ## space for return address push %rax sub %rsp, 32 + 16## shadow space for method calls and SSE registers movups [%rsp + 32], %xmm0 lea %rdi, [%rip + IsExecutedPtr + 8] ## Param 1: Hook handle hint lea %rsi, [%rsp + 56] ## Param 2: Address of return address call qword ptr [%rip + NETOutro] ## Hook->NETOutro(Hook)## lea %rax, [%rip + IsExecutedPtr] mov %rax, [%rax] .byte 0xF0 ## interlocked decrement execution counter dec qword ptr [%rax] add %rsp, 32 + 16 movups %xmm0, [%rsp - 16] pop %rax ## restore return value of user handler... ## finally return to saved return address - the caller of this trampoline... ret ######################################################################################## generic outro for both cases... trampoline_exit: add %rsp, 32 + 16 * 8 movups %xmm7, [%rsp - 8 * 16] movups %xmm6, [%rsp - 7 * 16] movups %xmm5, [%rsp - 6 * 16] movups %xmm4, [%rsp - 5 * 16] movups %xmm3, [%rsp - 4 * 16] movups %xmm2, [%rsp - 3 * 16] movups %xmm1, [%rsp - 2 * 16] movups %xmm0, [%rsp - 1 * 16] pop %r9 pop %r8 pop %rcx pop %rdx pop %rsi pop %rdi ## Remove alignment trick: https://stackoverflow.com/a/9600102 mov %rsp, [%rsp + 8] jmp qword ptr [%rax] ## ATTENTION: In case of hook handler we will return to call_net_outro, otherwise to the caller... ## outro signature, to automatically determine code size trampoline_data_x64: .byte 0x78 .byte 0x56 .byte 0x34 .byte 0x12 )"); #endif
c++
code
4,817
1,327
/** 122. Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). **/ #include <iostream> #include "../utils.h" using namespace std; class Solution { public: int maxProfit(const vector<int>& prices) { int l = prices.size(); if (l <= 1) return 0; int pro = 0; for (int i = 1; i < l; ++i) { int diff = prices[i] - prices[i - 1]; if (diff > 0) pro += diff; } return pro; } }; int main() { Solution s; ASSERT s.maxProfit({1}) == 0; ASSERT s.maxProfit({1, 2}) == 1; ASSERT s.maxProfit({1, 2, 1}) == 1; return 0; }
c++
code
960
260
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <validation.h> #include <arith_uint256.h> #include <chain.h> #include <chainparams.h> #include <checkqueue.h> #include <consensus/consensus.h> #include <consensus/merkle.h> #include <consensus/tx_check.h> #include <consensus/tx_verify.h> #include <consensus/validation.h> #include <cuckoocache.h> #include <flatfile.h> #include <hash.h> #include <index/txindex.h> #include <logging.h> #include <logging/timer.h> #include <node/ui_interface.h> #include <optional.h> #include <policy/fees.h> #include <policy/policy.h> #include <policy/settings.h> #include <pow.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <pubkey.h> #include <random.h> #include <reverse_iterator.h> #include <script/script.h> #include <script/sigcache.h> #include <shutdown.h> #include <signet.h> #include <timedata.h> #include <tinyformat.h> #include <txdb.h> #include <txmempool.h> #include <uint256.h> #include <undo.h> #include <util/check.h> // For NDEBUG compile time check #include <util/moneystr.h> #include <util/rbf.h> #include <util/strencodings.h> #include <util/system.h> #include <util/translation.h> #include <validationinterface.h> #include <warnings.h> #include <kernel.h> #include <string> #include <boost/algorithm/string/replace.hpp> #define MICRO 0.000001 #define MILLI 0.001 /** * An extra transaction can be added to a package, as long as it only has one * ancestor and is no larger than this. Not really any reason to make this * configurable as it doesn't materially change DoS parameters. */ static const unsigned int EXTRA_DESCENDANT_TX_SIZE_LIMIT = 10000; /** Maximum kilobytes for transactions to store for processing during reorg */ static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000; /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */ static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */ static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB /** Time to wait between writing blocks/block index to disk. */ static constexpr std::chrono::hours DATABASE_WRITE_INTERVAL{1}; /** Time to wait between flushing chainstate to disk. */ static constexpr std::chrono::hours DATABASE_FLUSH_INTERVAL{24}; /** Maximum age of our tip for us to be considered current for fee estimation */ static constexpr std::chrono::hours MAX_FEE_ESTIMATION_TIP_AGE{3}; const std::vector<std::string> CHECKLEVEL_DOC { "level 0 reads the blocks from disk", "level 1 verifies block validity", "level 2 verifies undo data", "level 3 checks disconnection of tip blocks", "level 4 tries to reconnect the blocks", "each level includes the checks of the previous levels", }; bool CBlockIndexWorkComparator::operator()(const CBlockIndex *pa, const CBlockIndex *pb) const { // First sort by most total work, ... if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; // ... then by earliest time received, ... if (pa->nSequenceId < pb->nSequenceId) return false; if (pa->nSequenceId > pb->nSequenceId) return true; // Use pointer address as tie breaker (should only happen with blocks // loaded from disk, as those all have id 0). if (pa < pb) return false; if (pa > pb) return true; // Identical blocks. return false; } ChainstateManager g_chainman; CChainState& ChainstateActive() { LOCK(::cs_main); assert(g_chainman.m_active_chainstate); return *g_chainman.m_active_chainstate; } CChain& ChainActive() { LOCK(::cs_main); return ::ChainstateActive().m_chain; } /** * Mutex to guard access to validation specific variables, such as reading * or changing the chainstate. * * This may also need to be locked when updating the transaction pool, e.g. on * AcceptToMemoryPool. See CTxMemPool::cs comment for details. * * The transaction pool has a separate lock to allow reading from it and the * chainstate at the same time. */ RecursiveMutex cs_main; CBlockIndex *pindexBestHeader = nullptr; Mutex g_best_block_mutex; std::condition_variable g_best_block_cv; uint256 g_best_block; bool g_parallel_script_checks{false}; std::atomic_bool fImporting(false); std::atomic_bool fReindex(false); bool fHavePruned = false; bool fPruneMode = false; bool fRequireStandard = true; bool fCheckBlockIndex = false; bool fCheckpointsEnabled = DEFAULT_CHECKPOINTS_ENABLED; uint64_t nPruneTarget = 0; int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE; uint256 hashAssumeValid; arith_uint256 nMinimumChainWork; CFeeRate minRelayTxFee = CFeeRate(DEFAULT_MIN_RELAY_TX_FEE); CBlockPolicyEstimator feeEstimator; // Internal stuff namespace { CBlockIndex* pindexBestInvalid = nullptr; RecursiveMutex cs_LastBlockFile; std::vector<CBlockFileInfo> vinfoBlockFile; int nLastBlockFile = 0; /** Global flag to indicate we should check to see if there are * block/undo files that should be deleted. Set on startup * or if we allocate more file space when we're in prune mode */ bool fCheckForPruning = false; /** Dirty block index entries. */ std::set<CBlockIndex*> setDirtyBlockIndex; /** Dirty block file entries. */ std::set<int> setDirtyFileInfo; } // anon namespace CBlockIndex* LookupBlockIndex(const uint256& hash) { AssertLockHeld(cs_main); BlockMap::const_iterator it = g_chainman.BlockIndex().find(hash); return it == g_chainman.BlockIndex().end() ? nullptr : it->second; } CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) { AssertLockHeld(cs_main); // Find the latest block common to locator and chain - we expect that // locator.vHave is sorted descending by height. for (const uint256& hash : locator.vHave) { CBlockIndex* pindex = LookupBlockIndex(hash); if (pindex) { if (chain.Contains(pindex)) return pindex; if (pindex->GetAncestor(chain.Height()) == chain.Tip()) { return chain.Tip(); } } } return chain.Genesis(); } std::unique_ptr<CBlockTreeDB> pblocktree; bool CheckInputScripts(const CTransaction& tx, TxValidationState &state, const CCoinsViewCache &inputs, const CChain& chain, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks = nullptr); static FILE* OpenUndoFile(const FlatFilePos &pos, bool fReadOnly = false); static FlatFileSeq BlockFileSeq(); static FlatFileSeq UndoFileSeq(); bool CheckFinalTx(const CTransaction &tx, int flags) { AssertLockHeld(cs_main); // By convention a negative value for flags indicates that the // current network-enforced consensus rules should be used. In // a future soft-fork scenario that would mean checking which // rules would be enforced for the next block and setting the // appropriate flags. At the present time no soft-forks are // scheduled, so no flags are set. flags = std::max(flags, 0); // CheckFinalTx() uses ::ChainActive().Height()+1 to evaluate // nLockTime because when IsFinalTx() is called within // CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a // transaction can be part of the *next* block, we need to call // IsFinalTx() with one more than ::ChainActive().Height(). const int nBlockHeight = ::ChainActive().Height() + 1; // BIP113 requires that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. // When the next block is created its previous block will be the current // chain tip, so we use that to calculate the median time passed to // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set. const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? ::ChainActive().Tip()->GetMedianTimePast() : GetAdjustedTime(); return IsFinalTx(tx, nBlockHeight, nBlockTime); } bool TestLockPointValidity(const LockPoints* lp) { AssertLockHeld(cs_main); assert(lp); // If there are relative lock times then the maxInputBlock will be set // If there are no relative lock times, the LockPoints don't depend on the chain if (lp->maxInputBlock) { // Check whether ::ChainActive() is an extension of the block at which the LockPoints // calculation was valid. If not LockPoints are no longer valid if (!::ChainActive().Contains(lp->maxInputBlock)) { return false; } } // LockPoints still valid return true; } bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flags, LockPoints* lp, bool useExistingLockPoints) { AssertLockHeld(cs_main); AssertLockHeld(pool.cs); CBlockIndex* tip = ::ChainActive().Tip(); assert(tip != nullptr); CBlockIndex index; index.pprev = tip; // CheckSequenceLocks() uses ::ChainActive().Height()+1 to evaluate // height based locks because when SequenceLocks() is called within // ConnectBlock(), the height of the block *being* // evaluated is what is used. // Thus if we want to know if a transaction can be part of the // *next* block, we need to use one more than ::ChainActive().Height() index.nHeight = tip->nHeight + 1; std::pair<int, int64_t> lockPair; if (useExistingLockPoints) { assert(lp); lockPair.first = lp->height; lockPair.second = lp->time; } else { // CoinsTip() contains the UTXO set for ::ChainActive().Tip() CCoinsViewMemPool viewMemPool(&::ChainstateActive().CoinsTip(), pool); std::vector<int> prevheights; prevheights.resize(tx.vin.size()); for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; Coin coin; if (!viewMemPool.GetCoin(txin.prevout, coin)) { return error("%s: Missing input", __func__); } if (coin.nHeight == MEMPOOL_HEIGHT) { // Assume all mempool transaction confirm in the next block prevheights[txinIndex] = tip->nHeight + 1; } else { prevheights[txinIndex] = coin.nHeight; } } lockPair = CalculateSequenceLocks(tx, flags, prevheights, index); if (lp) { lp->height = lockPair.first; lp->time = lockPair.second; // Also store the hash of the block with the highest height of // all the blocks which have sequence locked prevouts. // This hash needs to still be on the chain // for these LockPoint calculations to be valid // Note: It is impossible to correctly calculate a maxInputBlock // if any of the sequence locked inputs depend on unconfirmed txs, // except in the special case where the relative lock time/height // is 0, which is equivalent to no sequence lock. Since we assume // input height of tip+1 for mempool txs and test the resulting // lockPair from CalculateSequenceLocks against tip+1. We know // EvaluateSequenceLocks will fail if there was a non-zero sequence // lock on a mempool input, so we can use the return value of // CheckSequenceLocks to indicate the LockPoints validity int maxInputHeight = 0; for (const int height : prevheights) { // Can ignore mempool inputs since we'll fail if they had non-zero locks if (height != tip->nHeight+1) { maxInputHeight = std::max(maxInputHeight, height); } } lp->maxInputBlock = tip->GetAncestor(maxInputHeight); } } return EvaluateSequenceLocks(index, lockPair); } // Returns the script flags which should be checked for a given block static unsigned int GetBlockScriptFlags(const CBlockIndex* pindex, const Consensus::Params& chainparams); static void LimitMempoolSize(CTxMemPool& pool, size_t limit, std::chrono::seconds age) EXCLUSIVE_LOCKS_REQUIRED(pool.cs, ::cs_main) { int expired = pool.Expire(GetTime<std::chrono::seconds>() - age); if (expired != 0) { LogPrint(BCLog::MEMPOOL, "Expired %i transactions from the memory pool\n", expired); } std::vector<COutPoint> vNoSpendsRemaining; pool.TrimToSize(limit, &vNoSpendsRemaining); for (const COutPoint& removed : vNoSpendsRemaining) ::ChainstateActive().CoinsTip().Uncache(removed); } static bool IsCurrentForFeeEstimation() EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); if (::ChainstateActive().IsInitialBlockDownload()) return false; if (::ChainActive().Tip()->GetBlockTime() < count_seconds(GetTime<std::chrono::seconds>() - MAX_FEE_ESTIMATION_TIP_AGE)) return false; if (::ChainActive().Height() < pindexBestHeader->nHeight - 1) return false; return true; } /* Make mempool consistent after a reorg, by re-adding or recursively erasing * disconnected block transactions from the mempool, and also removing any * other transactions from the mempool that are no longer valid given the new * tip/height. * * Note: we assume that disconnectpool only contains transactions that are NOT * confirmed in the current chain nor already in the mempool (otherwise, * in-mempool descendants of such transactions would be removed). * * Passing fAddToMempool=false will skip trying to add the transactions back, * and instead just erase from the mempool as needed. */ static void UpdateMempoolForReorg(CTxMemPool& mempool, DisconnectedBlockTransactions& disconnectpool, bool fAddToMempool) EXCLUSIVE_LOCKS_REQUIRED(cs_main, mempool.cs) { AssertLockHeld(cs_main); AssertLockHeld(mempool.cs); std::vector<uint256> vHashUpdate; // disconnectpool's insertion_order index sorts the entries from // oldest to newest, but the oldest entry will be the last tx from the // latest mined block that was disconnected. // Iterate disconnectpool in reverse, so that we add transactions // back to the mempool starting with the earliest transaction that had // been previously seen in a block. auto it = disconnectpool.queuedTx.get<insertion_order>().rbegin(); while (it != disconnectpool.queuedTx.get<insertion_order>().rend()) { // ignore validation errors in resurrected transactions TxValidationState stateDummy; if (!fAddToMempool || (*it)->IsCoinBase() || (*it)->IsCoinStake() || !AcceptToMemoryPool(mempool, stateDummy, *it, nullptr /* plTxnReplaced */, true /* bypass_limits */)) { // If the transaction doesn't make it in to the mempool, remove any // transactions that depend on it (which would now be orphans). mempool.removeRecursive(**it, MemPoolRemovalReason::REORG); } else if (mempool.exists((*it)->GetHash())) { vHashUpdate.push_back((*it)->GetHash()); } ++it; } disconnectpool.queuedTx.clear(); // AcceptToMemoryPool/addUnchecked all assume that new mempool entries have // no in-mempool children, which is generally not true when adding // previously-confirmed transactions back to the mempool. // UpdateTransactionsFromBlock finds descendants of any transactions in // the disconnectpool that were added back and cleans up the mempool state. mempool.UpdateTransactionsFromBlock(vHashUpdate); // We also need to remove any now-immature transactions mempool.removeForReorg(&::ChainstateActive().CoinsTip(), ::ChainActive().Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); // Re-limit mempool size, in case we added any transactions LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, std::chrono::hours{gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY)}); } // Used to avoid mempool polluting consensus critical paths if CCoinsViewMempool // were somehow broken and returning the wrong scriptPubKeys static bool CheckInputsFromMempoolAndCache(const CTransaction& tx, TxValidationState& state, const CCoinsViewCache& view, const CTxMemPool& pool, unsigned int flags, PrecomputedTransactionData& txdata) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); // pool.cs should be locked already, but go ahead and re-take the lock here // to enforce that mempool doesn't change between when we check the view // and when we actually call through to CheckInputScripts LOCK(pool.cs); assert(!tx.IsCoinBase() && !tx.IsCoinStake()); for (const CTxIn& txin : tx.vin) { const Coin& coin = view.AccessCoin(txin.prevout); // AcceptToMemoryPoolWorker has already checked that the coins are // available, so this shouldn't fail. If the inputs are not available // here then return false. if (coin.IsSpent()) return false; // Check equivalence for available inputs. const CTransactionRef& txFrom = pool.get(txin.prevout.hash); if (txFrom) { assert(txFrom->GetHash() == txin.prevout.hash); assert(txFrom->vout.size() > txin.prevout.n); assert(txFrom->vout[txin.prevout.n] == coin.out); } else { const Coin& coinFromDisk = ::ChainstateActive().CoinsTip().AccessCoin(txin.prevout); assert(!coinFromDisk.IsSpent()); assert(coinFromDisk.out == coin.out); } } // Call CheckInputScripts() to cache signature and script validity against current tip consensus rules. return CheckInputScripts(tx, state, view, ::ChainActive(), flags, /* cacheSigStore = */ true, /* cacheFullSciptStore = */ true, txdata); } namespace { class MemPoolAccept { public: MemPoolAccept(CTxMemPool& mempool) : m_pool(mempool), m_view(&m_dummy), m_viewmempool(&::ChainstateActive().CoinsTip(), m_pool), m_limit_ancestors(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT)), m_limit_ancestor_size(gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000), m_limit_descendants(gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT)), m_limit_descendant_size(gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000) {} // We put the arguments we're handed into a struct, so we can pass them // around easier. struct ATMPArgs { const CChainParams& m_chainparams; TxValidationState &m_state; const int64_t m_accept_time; std::list<CTransactionRef>* m_replaced_transactions; const bool m_bypass_limits; /* * Return any outpoints which were not previously present in the coins * cache, but were added as a result of validating the tx for mempool * acceptance. This allows the caller to optionally remove the cache * additions if the associated transaction ends up being rejected by * the mempool. */ std::vector<COutPoint>& m_coins_to_uncache; const bool m_test_accept; CAmount* m_fee_out; }; // Single transaction acceptance bool AcceptSingleTransaction(const CTransactionRef& ptx, ATMPArgs& args) EXCLUSIVE_LOCKS_REQUIRED(cs_main); private: // All the intermediate state that gets passed between the various levels // of checking a given transaction. struct Workspace { Workspace(const CTransactionRef& ptx) : m_ptx(ptx), m_hash(pt
c++
code
20,000
3,882
#include <fstream> #include <ShlObj.h> #include "json/json.h" #include "Config.h" Config::Config(const char* name) noexcept { PWSTR pathToDocuments; if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &pathToDocuments))) { path = pathToDocuments; path /= name; CoTaskMemFree(pathToDocuments); } if (!std::filesystem::is_directory(path)) { std::filesystem::remove(path); std::filesystem::create_directory(path); } std::transform(std::filesystem::directory_iterator{ path }, std::filesystem::directory_iterator{ }, std::back_inserter(configs), [](const auto& entry) { return entry.path().filename().string(); }); } void Config::load(size_t id) noexcept { if (!std::filesystem::is_directory(path)) { std::filesystem::remove(path); std::filesystem::create_directory(path); } std::ifstream in{ path / configs[id] }; if (!in.good()) return; Json::Value json; in >> json; in.close(); for (size_t i = 0; i < aimbot.size(); i++) { const auto& aimbotJson = json["Aimbot"][i]; auto& aimbotConfig = aimbot[i]; if (aimbotJson.isMember("Enabled")) aimbotConfig.enabled = aimbotJson["Enabled"].asBool(); if (aimbotJson.isMember("On key")) aimbotConfig.onKey = aimbotJson["On key"].asBool(); if (aimbotJson.isMember("Key")) aimbotConfig.key = aimbotJson["Key"].asInt(); if (aimbotJson.isMember("Key mode")) aimbotConfig.keyMode = aimbotJson["Key mode"].asInt(); if (aimbotJson.isMember("Aimlock")) aimbotConfig.aimlock = aimbotJson["Aimlock"].asBool(); if (aimbotJson.isMember("Silent")) aimbotConfig.silent = aimbotJson["Silent"].asBool(); if (aimbotJson.isMember("Friendly fire")) aimbotConfig.friendlyFire = aimbotJson["Friendly fire"].asBool(); if (aimbotJson.isMember("Visible only")) aimbotConfig.visibleOnly = aimbotJson["Visible only"].asBool(); if (aimbotJson.isMember("Scoped only")) aimbotConfig.scopedOnly = aimbotJson["Scoped only"].asBool(); if (aimbotJson.isMember("Ignore flash")) aimbotConfig.ignoreFlash = aimbotJson["Ignore flash"].asBool(); if (aimbotJson.isMember("Ignore smoke")) aimbotConfig.ignoreSmoke = aimbotJson["Ignore smoke"].asBool(); if (aimbotJson.isMember("Auto shot")) aimbotConfig.autoShot = aimbotJson["Auto shot"].asBool(); if (aimbotJson.isMember("Recoil-based fov")) aimbotConfig.recoilbasedFov = aimbotJson["Recoil-based fov"].asBool(); if (aimbotJson.isMember("Fov")) aimbotConfig.fov = aimbotJson["Fov"].asFloat(); if (aimbotJson.isMember("Max angle delta")) aimbotConfig.maxAngleDelta = aimbotJson["Max angle delta"].asFloat(); if (aimbotJson.isMember("Smooth")) aimbotConfig.smooth = aimbotJson["Smooth"].asFloat(); if (aimbotJson.isMember("Bone")) aimbotConfig.bone = aimbotJson["Bone"].asInt(); if (aimbotJson.isMember("Recoil control X")) aimbotConfig.recoilControlX = aimbotJson["Recoil control X"].asFloat(); if (aimbotJson.isMember("Recoil control Y")) aimbotConfig.recoilControlY = aimbotJson["Recoil control Y"].asFloat(); } for (size_t i = 0; i < triggerbot.size(); i++) { const auto& triggerbotJson = json["Triggerbot"][i]; auto& triggerbotConfig = triggerbot[i]; if (triggerbotJson.isMember("Enabled")) triggerbotConfig.enabled = triggerbotJson["Enabled"].asBool(); if (triggerbotJson.isMember("On key")) triggerbotConfig.onKey = triggerbotJson["On key"].asBool(); if (triggerbotJson.isMember("Key")) triggerbotConfig.key = triggerbotJson["Key"].asInt(); if (triggerbotJson.isMember("Friendly fire")) triggerbotConfig.friendlyFire = triggerbotJson["Friendly fire"].asBool(); if (triggerbotJson.isMember("Scoped only")) triggerbotConfig.scopedOnly = triggerbotJson["Scoped only"].asBool(); if (triggerbotJson.isMember("Ignore flash")) triggerbotConfig.ignoreFlash = triggerbotJson["Ignore flash"].asBool(); if (triggerbotJson.isMember("Ignore smoke")) triggerbotConfig.ignoreSmoke = triggerbotJson["Ignore smoke"].asBool(); if (triggerbotJson.isMember("Hitgroup")) triggerbotConfig.hitgroup = triggerbotJson["Hitgroup"].asInt(); if (triggerbotJson.isMember("Shot delay")) triggerbotConfig.shotDelay = triggerbotJson["Shot delay"].asInt(); } { const auto& backtrackJson = json["Backtrack"]; if (backtrackJson.isMember("Enabled")) backtrack.enabled = backtrackJson["Enabled"].asBool(); if (backtrackJson.isMember("Ignore smoke")) backtrack.ignoreSmoke = backtrackJson["Ignore smoke"].asBool(); if (backtrackJson.isMember("Time limit")) backtrack.timeLimit = backtrackJson["Time limit"].asInt(); } { const auto& antiAimJson = json["Anti aim"]; if (antiAimJson.isMember("Enabled")) antiAim.enabled = antiAimJson["Enabled"].asBool(); } for (size_t i = 0; i < glow.size(); i++) { const auto& glowJson = json["glow"][i]; auto& glowConfig = glow[i]; if (glowJson.isMember("Enabled")) glowConfig.enabled = glowJson["Enabled"].asBool(); if (glowJson.isMember("healthBased")) glowConfig.healthBased = glowJson["healthBased"].asBool(); if (glowJson.isMember("rainbow")) glowConfig.rainbow = glowJson["rainbow"].asBool(); if (glowJson.isMember("thickness")) glowConfig.thickness = glowJson["thickness"].asFloat(); if (glowJson.isMember("alpha")) glowConfig.alpha = glowJson["alpha"].asFloat(); if (glowJson.isMember("style")) glowConfig.style = glowJson["style"].asInt(); if (glowJson.isMember("color")) { glowConfig.color[0] = glowJson["color"][0].asFloat(); glowConfig.color[1] = glowJson["color"][1].asFloat(); glowConfig.color[2] = glowJson["color"][2].asFloat(); } } for (size_t i = 0; i < chams.size(); i++) { const auto& chamsJson = json["chams"][i]; auto& chamsConfig = chams[i]; if (chamsJson.isMember("Enabled")) chamsConfig.enabled = chamsJson["Enabled"].asBool(); if (chamsJson.isMember("healthBased")) chamsConfig.healthBased = chamsJson["healthBased"].asBool(); if (chamsJson.isMember("rainbow")) chamsConfig.rainbow = chamsJson["rainbow"].asBool(); if (chamsJson.isMember("blinking")) chamsConfig.blinking = chamsJson["blinking"].asBool(); if (chamsJson.isMember("material")) chamsConfig.material = chamsJson["material"].asInt(); if (chamsJson.isMember("wireframe")) chamsConfig.wireframe = chamsJson["wireframe"].asBool(); if (chamsJson.isMember("color")) { chamsConfig.color[0] = chamsJson["color"][0].asFloat(); chamsConfig.color[1] = chamsJson["color"][1].asFloat(); chamsConfig.color[2] = chamsJson["color"][2].asFloat(); } if (chamsJson.isMember("alpha")) chamsConfig.alpha = chamsJson["alpha"].asFloat(); } for (size_t i = 0; i < esp.size(); i++) { const auto& espJson = json["esp"][i]; auto& espConfig = esp[i]; if (espJson.isMember("Enabled")) espConfig.enabled = espJson["Enabled"].asBool(); if (espJson.isMember("Font")) espConfig.font = espJson["Font"].asInt(); if (espJson.isMember("snaplines")) espConfig.snaplines = espJson["snaplines"].asBool(); if (espJson.isMember("snaplinesColor")) { espConfig.snaplinesColor[0] = espJson["snaplinesColor"][0].asFloat(); espConfig.snaplinesColor[1] = espJson["snaplinesColor"][1].asFloat(); espConfig.snaplinesColor[2] = espJson["snaplinesColor"][2].asFloat(); } if (espJson.isMember("Eye traces")) espConfig.eyeTraces = espJson["Eye traces"].asBool(); if (espJson.isMember("Eye traces color")) { espConfig.eyeTracesColor[0] = espJson["Eye traces color"][0].asFloat(); espConfig.eyeTracesColor[1] = espJson["Eye traces color"][1].asFloat(); espConfig.eyeTracesColor[2] = espJson["Eye traces color"][2].asFloat(); } if (espJson.isMember("box")) espConfig.box = espJson["box"].asBool(); if (espJson.isMember("boxColor")) { espConfig.boxColor[0] = espJson["boxColor"][0].asFloat(); espConfig.boxColor[1] = espJson["boxColor"][1].asFloat(); espConfig.boxColor[2] = espJson["boxColor"][2].asFloat(); } if (espJson.isMember("name")) espConfig.name = espJson["name"].asBool(); if (espJson.isMember("nameColor")) { espConfig.nameColor[0] = espJson["nameColor"][0].asFloat(); espConfig.nameColor[1] = espJson["nameColor"][1].asFloat(); espConfig.nameColor[2] = espJson["nameColor"][2].asFloat(); } if (espJson.isMember("health")) espConfig.health = espJson["health"].asBool(); if (espJson.isMember("healthColor")) { espConfig.healthColor[0] = espJson["healthColor"][0].asFloat(); espConfig.healthColor[1] = espJson["healthColor"][1].asFloat(); espConfig.healthColor[2] = espJson["healthColor"][2].asFloat(); } if (espJson.isMember("healthBar")) espConfig.healthBar = espJson["healthBar"].asBool(); if (espJson.isMember("healthBarColor")) { espConfig.healthBarColor[0] = espJson["healthBarColor"][0].asFloat(); espConfig.healthBarColor[1] = espJson["healthBarColor"][1].asFloat(); espConfig.healthBarColor[2] = espJson["healthBarColor"][2].asFloat(); } if (espJson.isMember("armor")) espConfig.armor = espJson["armor"].asBool(); if (espJson.isMember("armorColor")) { espConfig.armorColor[0] = espJson["armorColor"][0].asFloat(); espConfig.armorColor[1] = espJson["armorColor"][1].asFloat(); espConfig.armorColor[2] = espJson["armorColor"][2].asFloat(); } if (espJson.isMember("armorBar")) espConfig.armorBar = espJson["armorBar"].asBool(); if (espJson.isMember("armorBarColor")) { espConfig.armorBarColor[0] = espJson["armorBarColor"][0].asFloat(); espConfig.armorBarColor[1] = espJson["armorBarColor"][1].asFloat(); espConfig.armorBarColor[2] = espJson["armorBarColor"][2].asFloat(); } if (espJson.isMember("money")) espConfig.money = espJson["money"].asBool(); if (espJson.isMember("moneyColor")) { espConfig.moneyColor[0] = espJson["moneyColor"][0].asFloat(); espConfig.moneyColor[1] = espJson["moneyColor"][1].asFloat(); espConfig.moneyColor[2] = espJson["moneyColor"][2].asFloat(); } if (espJson.isMember("headDot")) espConfig.headDot = espJson["headDot"].asBool(); if (espJson.isMember("headDotColor")) { espConfig.headDotColor[0] = espJson["headDotColor"][0].asFloat(); espConfig.headDotColor[1] = espJson["headDotColor"][1].asFloat(); espConfig.headDotColor[2] = espJson["headDotColor"][2].asFloat(); } } { const auto& visualsJson = json["visuals"]; if (visualsJson.isMember("disablePostProcessing")) visuals.disablePostProcessing = visualsJson["disablePostProcessing"].asBool(); if (visualsJson.isMember("inverseRagdollGravity")) visuals.inverseRagdollGravity = visualsJson["inverseRagdollGravity"].asBool(); if (visualsJson.isMember("noFog")) visuals.noFog = visualsJson["noFog"].asBool(); if (visualsJson.isMember("no3dSky")) visuals.no3dSky = visualsJson["no3dSky"].asBool(); if (visualsJson.isMember("noVisualRecoil")) visuals.noVisualRecoil = visualsJson["noVisualRecoil"].asBool(); if (visualsJson.isMember("noHands")) visuals.noHands = visualsJson["noHands"].asBool(); if (visualsJson.isMember("noSleeves")) visuals.noSleeves = visualsJson["noSleeves"].asBool(); if (visualsJson.isMember("noWeapons")) visuals.noWeapons = visualsJson["noWeapons"].asBool(); if (visualsJson.isMember("noSmoke")) visuals.noSmoke = visualsJson["noSmoke"].asBool(); if (visualsJson.isMember("noBlur")) visuals.noBlur = visualsJson["noBlur"].asBool(); if (visualsJson.isMember("noScopeOverlay")) visuals.noScopeOverlay = visualsJson["noScopeOverlay"].asBool(); if (visualsJson.isMember("noGrass")) visuals.noGrass = visualsJson["noGrass"].asBool(); if (visualsJson.isMember("noShadows")) visuals.noShadows = visualsJson["noShadows"].asBool(); if (visualsJson.isMember("wireframeSmoke")) visuals.wireframeSmoke = visualsJson["wireframeSmoke"].asBool(); if (visualsJson.isMember("Zoom")) visuals.zoom = visualsJson["Zoom"].asBool(); if (visualsJson.isMember("Zoom key")) visuals.zoomKey = visualsJson["Zoom key"].asInt(); if (visualsJson.isMember("thirdperson")) visuals.thirdperson = visualsJson["thirdperson"].asBool(); if (visualsJson.isMember("thirdpersonKey")) visuals.thirdpersonKey = visualsJson["thirdpersonKey"].asInt(); if (visualsJson.isMember("thirdpersonDistance")) visuals.thirdpersonDistance = visualsJson["thirdpersonDistance"].asInt(); if (visualsJson.isMember("viewmodelFov")) visuals.viewmodelFov = visualsJson["viewmodelFov"].asInt(); if (visualsJson.isMember("Fov")) visuals.fov = visualsJson["Fov"].asInt(); if (visualsJson.isMember("farZ")) visuals.farZ = visualsJson["farZ"].asInt(); if (visualsJson.isMember("flashReduction")) visuals.flashReduction = visualsJson["flashReduction"].asInt(); if (visualsJson.isMember("brightness")) visuals.brightness = visualsJson["brightness"].asFloat(); if (visualsJson.isMember("skybox")) visuals.skybox = visualsJson["skybox"].asInt(); if (visualsJson.isMember("worldColor")) { visuals.worldColor[0] = visualsJson["worldColor"][0].asFloat(); visuals.worldColor[1] = visualsJson["worldColor"][1].asFloat(); visuals.worldColor[2] = visualsJson["worldColor"][2].asFloat(); } if (visualsJson.isMember("Deagle spinner")) visuals.deagleSpinner = visualsJson["Deagle spinner"].asBool(); if (visualsJson.isMember("Screen effect")) visuals.screenEffect = visualsJson["Screen effect"].asInt(); if (visualsJson.isMember("Hit marker")) visuals.hitMarker = visualsJson["Hit marker"].asInt(); if (visualsJson.isMember("Hit marker time")) visuals.hitMarkerTime = visualsJson["Hit marker time"].asFloat(); } for (size_t i = 0; i < skinChanger.size(); i++) { const auto& skinChangerJson = json["skinChanger"][i]; auto& skinChangerConfig = skinChanger[i]; if (skinChangerJson.isMember("Enabled")) skinChangerConfig.enabled = skinChangerJson["Enabled"].asBool(); if (skinChangerJson.isMember("definition_vector_index")) skinChangerConfig.definition_vector_index = skinChangerJson["definition_vector_index"].asInt(); if (skinChangerJson.isMember("definition_index")) skinChangerConfig.definition_index = skinChangerJson["definition_index"].asInt(); if (skinChangerJson.isMember("entity_quality_vector_index")) skinChangerConfig.entity_quality_vector_index = skinChangerJson["entity_quality_vector_index"].asInt(); if (skinChangerJson.isMember("entity_quality_index")) skinChangerConfig.entity_quality_index = skinChangerJson["entity_quality_index"].asInt(); if (skinChangerJson.isMember("paint_kit_vector_index")) skinChangerConfig.paint_kit_vector_index = skinChangerJson["paint_kit_vector_index"].asInt(); if (skinChangerJson.isMember("paint_kit_index")) skinChangerConfig.paint_kit_index = skinChangerJson["paint_kit_index"].asInt(); if (skinChangerJson.isMember("definition_override_vector_index")) skinChangerConfig.definition_override_vector_index = skinChangerJson["definition_override_vector_index"].asInt(); if (skinChangerJson.isMember("definition_override_index")) skinChangerConfig.definition_override_index = skinChangerJson["definition_override_index"].asInt(); if (skinChangerJson.isMember("seed")) skinChangerConfig.seed = skinChangerJson["seed"].asInt(); if (skinChangerJson.isMember("stat_trak")) skinChangerConfig.stat_trak = skinChangerJson["stat_trak"].asInt(); if (skinChangerJson.isMember("wear")) skinChangerConfig.wear = skinChangerJson["wear"].asFloat(); if (skinChangerJson.isMember("custom_name")) strcpy_s(skinChangerConfig.custom_name, 32, skinChangerJson["custom_name"].asCString()); if (skinChangerJson.isMember("stickers")) { for (size_t j = 0; j < skinChangerConfig.stickers.size(); j++) { const auto& stickerJson = skinChangerJson["stickers"][j]; auto& stickerConfig = skinChangerConfig.stickers[j]; if (stickerJson.isMember("kit")) stickerConfig.kit = stickerJson["kit"].asInt(); if (stickerJson.isMember("kit_vector_index")) stickerConfig.kit_vector_index = stickerJson["kit_vector_index"].asInt(); if (stickerJson.isMember("wear")) stickerConfig.wear = stickerJson["wear"].asFloat(); if (stickerJson.isMember("scale")) stickerConfig.scale = stickerJson["scale"].asFloat(); if (stickerJson.isMember("rotation")) stickerConfig.rotation = stickerJson["rotation"].asFloat(); } } } { const auto& soundJson = json["Sound"]; if (soundJson.isMember("Chicken volume")) sound.chickenVolume = soundJson["Chicken volume"].asInt(); if (soundJson.isMember("Players")) { for (size_t i = 0; i < sound.players.size(); i++) { const auto& playerJson = soundJson["Players"][i]; auto& playerConfig = sound.players[i]; if (playerJson.isMember("Master volume")) playerConfig.masterVolume = playerJson["Master volume"].asInt(); if (playerJson.isMember("Headshot volume")) playerConfig.headshotVolume = playerJson["Headshot volume"].asInt(); if (playerJson.isMember("Weapon volume")) playerConfig.weaponVolume = playerJson["Weapon volume"].asInt(); if (playerJson.isMember("Footstep volume")) playerConfig.footstepVolume = playerJson["Footstep volume"].asInt(); } } } { const auto& miscJson = json["Misc"]; if (miscJson.isMember("Menu key")) misc.menuKey = miscJson["Menu key"].asInt(); if (miscJson.isMember("Menu style")) misc.menuStyle = miscJson["Menu style"].asInt(); if (miscJson.isMember("Menu colors")) misc.menuColors = miscJson["Menu colors"].asInt(); if (miscJson.isMember("Anti AFK kick")) misc.antiAfkKick = miscJson["Anti AFK kick"].asBool(); if (miscJson.isMember("Auto strafe")) misc.autoStrafe = miscJson["Auto strafe"].asBool(); if (miscJson.isMember("Bunny hop")) misc.bunnyHop = miscJson["Bunny hop"].asBool(); if (miscJson.isMember("Custom clan tag")) misc.customClanTag = miscJson["Custom clan tag"].asBool(); if (miscJson.isMember("Clan tag")) strcpy_s(misc.clanTag, 16, miscJson["Clan tag"].asCString()); if (miscJson.isMember("Animated clan tag")) misc.animatedClanTag = miscJson["Animated clan tag"].asBool(); if (miscJson.isMember("Fast duck")) misc.fastDuck = miscJson["Fast duck"].asBool(); if (miscJson.isMember("Sniper crosshair")) misc.sniperCrosshair = miscJson["Sniper crosshair"].asBool(); if (miscJson.isMember("Recoil crosshair")) misc.recoilCrosshair = miscJson["Recoil crosshair"].asBool(); if (miscJson.isMember("Auto pistol")) misc.autoPistol = miscJson["Auto pistol"].asBool(); if (miscJson.isMember("Auto reload")) misc.autoReload = miscJson["Auto reload"].asBool(); if (miscJson.isMember("Auto accept")) misc.autoAccept = miscJson["Auto accept"].asBool(); if (miscJson.isMember("Radar ha
c++
code
20,000
5,068
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "common.h" #include "gcheaputilities.h" #include "gcenv.ee.h" #include "appdomain.hpp" // These globals are variables used within the GC and maintained // by the EE for use in write barriers. It is the responsibility // of the GC to communicate updates to these globals to the EE through // GCToEEInterface::StompWriteBarrierResize and GCToEEInterface::StompWriteBarrierEphemeral. GPTR_IMPL_INIT(uint32_t, g_card_table, nullptr); GPTR_IMPL_INIT(uint8_t, g_lowest_address, nullptr); GPTR_IMPL_INIT(uint8_t, g_highest_address, nullptr); GVAL_IMPL_INIT(GCHeapType, g_heap_type, GC_HEAP_INVALID); uint8_t* g_ephemeral_low = (uint8_t*)1; uint8_t* g_ephemeral_high = (uint8_t*)~0; #ifdef FEATURE_MANUALLY_MANAGED_CARD_BUNDLES uint32_t* g_card_bundle_table = nullptr; #endif // This is the global GC heap, maintained by the VM. GPTR_IMPL(IGCHeap, g_pGCHeap); GcDacVars g_gc_dac_vars; GPTR_IMPL(GcDacVars, g_gcDacGlobals); #ifdef FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP uint8_t* g_sw_ww_table = nullptr; bool g_sw_ww_enabled_for_gc_heap = false; #endif // FEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP GVAL_IMPL_INIT(gc_alloc_context, g_global_alloc_context, {}); enum GC_LOAD_STATUS { GC_LOAD_STATUS_BEFORE_START, GC_LOAD_STATUS_START, GC_LOAD_STATUS_DONE_LOAD, GC_LOAD_STATUS_GET_VERSIONINFO, GC_LOAD_STATUS_CALL_VERSIONINFO, GC_LOAD_STATUS_DONE_VERSION_CHECK, GC_LOAD_STATUS_GET_INITIALIZE, GC_LOAD_STATUS_LOAD_COMPLETE }; // Load status of the GC. If GC loading fails, the value of this // global indicates where the failure occured. GC_LOAD_STATUS g_gc_load_status = GC_LOAD_STATUS_BEFORE_START; // The version of the GC that we have loaded. VersionInfo g_gc_version_info; // The module that contains the GC. PTR_VOID g_gc_module_base; bool GCHeapUtilities::s_useThreadAllocationContexts; // GC entrypoints for the the linked-in GC. These symbols are invoked // directly if we are not using a standalone GC. extern "C" void GC_VersionInfo(/* Out */ VersionInfo* info); extern "C" HRESULT GC_Initialize( /* In */ IGCToCLR* clrToGC, /* Out */ IGCHeap** gcHeap, /* Out */ IGCHandleManager** gcHandleManager, /* Out */ GcDacVars* gcDacVars ); #ifndef DACCESS_COMPILE PTR_VOID GCHeapUtilities::GetGCModuleBase() { assert(g_gc_module_base); return g_gc_module_base; } namespace { // This block of code contains all of the state necessary to handle incoming // EtwCallbacks before the GC has been initialized. This is a tricky problem // because EtwCallbacks can appear at any time, even when we are just about // finished initializing the GC. // // The below lock is taken by the "main" thread (the thread in EEStartup) and // the "ETW" thread, the one calling EtwCallback. EtwCallback may or may not // be called on the main thread. DangerousNonHostedSpinLock g_eventStashLock; GCEventLevel g_stashedLevel = GCEventLevel_None; GCEventKeyword g_stashedKeyword = GCEventKeyword_None; GCEventLevel g_stashedPrivateLevel = GCEventLevel_None; GCEventKeyword g_stashedPrivateKeyword = GCEventKeyword_None; BOOL g_gcEventTracingInitialized = FALSE; // FinalizeLoad is called by the main thread to complete initialization of the GC. // At this point, the GC has provided us with an IGCHeap instance and we are preparing // to "publish" it by assigning it to g_pGCHeap. // // This function can proceed concurrently with StashKeywordAndLevel below. void FinalizeLoad(IGCHeap* gcHeap, IGCHandleManager* handleMgr, PTR_VOID pGcModuleBase) { g_pGCHeap = gcHeap; { DangerousNonHostedSpinLockHolder lockHolder(&g_eventStashLock); // Ultimately, g_eventStashLock ensures that no two threads call ControlEvents at any // point in time. g_pGCHeap->ControlEvents(g_stashedKeyword, g_stashedLevel); g_pGCHeap->ControlPrivateEvents(g_stashedPrivateKeyword, g_stashedPrivateLevel); g_gcEventTracingInitialized = TRUE; } g_pGCHandleManager = handleMgr; g_gcDacGlobals = &g_gc_dac_vars; g_gc_load_status = GC_LOAD_STATUS_LOAD_COMPLETE; g_gc_module_base = pGcModuleBase; LOG((LF_GC, LL_INFO100, "GC load successful\n")); StressLog::AddModule((uint8_t*)pGcModuleBase); } void StashKeywordAndLevel(bool isPublicProvider, GCEventKeyword keywords, GCEventLevel level) { DangerousNonHostedSpinLockHolder lockHolder(&g_eventStashLock); if (!g_gcEventTracingInitialized) { if (isPublicProvider) { g_stashedKeyword = keywords; g_stashedLevel = level; } else { g_stashedPrivateKeyword = keywords; g_stashedPrivateLevel = level; } } else { if (isPublicProvider) { g_pGCHeap->ControlEvents(keywords, level); } else { g_pGCHeap->ControlPrivateEvents(keywords, level); } } } #ifdef FEATURE_STANDALONE_GC HMODULE LoadStandaloneGc(LPCWSTR libFileName) { LIMITED_METHOD_CONTRACT; // Look for the standalone GC module next to the clr binary PathString libPath = GetInternalSystemDirectory(); libPath.Append(libFileName); LPCWSTR libraryName = libPath.GetUnicode(); LOG((LF_GC, LL_INFO100, "Loading standalone GC from path %S\n", libraryName)); return CLRLoadLibrary(libraryName); } #endif // FEATURE_STANDALONE_GC // Loads and initializes a standalone GC, given the path to the GC // that we should load. Returns S_OK on success and the failed HRESULT // on failure. // // See Documentation/design-docs/standalone-gc-loading.md for details // on the loading protocol in use here. HRESULT LoadAndInitializeGC(LPWSTR standaloneGcLocation) { LIMITED_METHOD_CONTRACT; #ifndef FEATURE_STANDALONE_GC LOG((LF_GC, LL_FATALERROR, "EE not built with the ability to load standalone GCs")); return E_FAIL; #else HMODULE hMod = LoadStandaloneGc(standaloneGcLocation); if (!hMod) { HRESULT err = GetLastError(); LOG((LF_GC, LL_FATALERROR, "Load of %S failed\n", standaloneGcLocation)); return __HRESULT_FROM_WIN32(err); } // a standalone GC dispatches virtually on GCToEEInterface, so we must instantiate // a class for the GC to use. IGCToCLR* gcToClr = new (nothrow) standalone::GCToEEInterface(); if (!gcToClr) { return E_OUTOFMEMORY; } g_gc_load_status = GC_LOAD_STATUS_DONE_LOAD; GC_VersionInfoFunction versionInfo = (GC_VersionInfoFunction)GetProcAddress(hMod, "GC_VersionInfo"); if (!versionInfo) { HRESULT err = GetLastError(); LOG((LF_GC, LL_FATALERROR, "Load of `GC_VersionInfo` from standalone GC failed\n")); return __HRESULT_FROM_WIN32(err); } g_gc_load_status = GC_LOAD_STATUS_GET_VERSIONINFO; versionInfo(&g_gc_version_info); g_gc_load_status = GC_LOAD_STATUS_CALL_VERSIONINFO; if (g_gc_version_info.MajorVersion != GC_INTERFACE_MAJOR_VERSION) { LOG((LF_GC, LL_FATALERROR, "Loaded GC has incompatible major version number (expected %d, got %d)\n", GC_INTERFACE_MAJOR_VERSION, g_gc_version_info.MajorVersion)); return E_FAIL; } if (g_gc_version_info.MinorVersion < GC_INTERFACE_MINOR_VERSION) { LOG((LF_GC, LL_INFO100, "Loaded GC has lower minor version number (%d) than EE was compiled against (%d)\n", g_gc_version_info.MinorVersion, GC_INTERFACE_MINOR_VERSION)); } LOG((LF_GC, LL_INFO100, "Loaded GC identifying itself with name `%s`\n", g_gc_version_info.Name)); g_gc_load_status = GC_LOAD_STATUS_DONE_VERSION_CHECK; GC_InitializeFunction initFunc = (GC_InitializeFunction)GetProcAddress(hMod, "GC_Initialize"); if (!initFunc) { HRESULT err = GetLastError(); LOG((LF_GC, LL_FATALERROR, "Load of `GC_Initialize` from standalone GC failed\n")); return __HRESULT_FROM_WIN32(err); } g_gc_load_status = GC_LOAD_STATUS_GET_INITIALIZE; IGCHeap* heap; IGCHandleManager* manager; HRESULT initResult = initFunc(gcToClr, &heap, &manager, &g_gc_dac_vars); if (initResult == S_OK) { PTR_VOID pGcModuleBase; #if TARGET_WINDOWS pGcModuleBase = (PTR_VOID)hMod; #else pGcModuleBase = (PTR_VOID)PAL_GetSymbolModuleBase((PVOID)initFunc); #endif FinalizeLoad(heap, manager, pGcModuleBase); } else { LOG((LF_GC, LL_FATALERROR, "GC initialization failed with HR = 0x%X\n", initResult)); } return initResult; #endif // FEATURE_STANDALONE_GC } // Initializes a non-standalone GC. The protocol for initializing a non-standalone GC // is similar to loading a standalone one, except that the GC_VersionInfo and // GC_Initialize symbols are linked to directory and thus don't need to be loaded. // // The major and minor versions are still checked in debug builds - it must be the case // that the GC and EE agree on a shared version number because they are built from // the same sources. HRESULT InitializeDefaultGC() { LIMITED_METHOD_CONTRACT; LOG((LF_GC, LL_INFO100, "Standalone GC location not provided, using provided GC\n")); g_gc_load_status = GC_LOAD_STATUS_DONE_LOAD; GC_VersionInfo(&g_gc_version_info); g_gc_load_status = GC_LOAD_STATUS_CALL_VERSIONINFO; // the default GC builds with the rest of the EE. By definition, it must have been // built with the same interface version. assert(g_gc_version_info.MajorVersion == GC_INTERFACE_MAJOR_VERSION); assert(g_gc_version_info.MinorVersion == GC_INTERFACE_MINOR_VERSION); g_gc_load_status = GC_LOAD_STATUS_DONE_VERSION_CHECK; IGCHeap* heap; IGCHandleManager* manager; HRESULT initResult = GC_Initialize(nullptr, &heap, &manager, &g_gc_dac_vars); if (initResult == S_OK) { FinalizeLoad(heap, manager, GetClrModuleBase()); } else { LOG((LF_GC, LL_FATALERROR, "GC initialization failed with HR = 0x%X\n", initResult)); } return initResult; } } // anonymous namespace // Loads (if necessary) and initializes the GC. If using a standalone GC, // it loads the library containing it and dynamically loads the GC entry point. // If using a non-standalone GC, it invokes the GC entry point directly. HRESULT GCHeapUtilities::LoadAndInitialize() { LIMITED_METHOD_CONTRACT; // When running on a single-proc Intel system, it's more efficient to use a single global // allocation context for SOH allocations than to use one for every thread. #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && !defined(TARGET_UNIX) #if DEBUG bool useGlobalAllocationContext = (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_GCUseGlobalAllocationContext) != 0); #else bool useGlobalAllocationContext = false; #endif s_useThreadAllocationContexts = !useGlobalAllocationContext && (IsServerHeap() || ::g_SystemInfo.dwNumberOfProcessors != 1 || CPUGroupInfo::CanEnableGCCPUGroups()); #else s_useThreadAllocationContexts = true; #endif // we should only call this once on startup. Attempting to load a GC // twice is an error. assert(g_pGCHeap == nullptr); // we should not have attempted to load a GC already. Attempting a // load after the first load already failed is an error. assert(g_gc_load_status == GC_LOAD_STATUS_BEFORE_START); g_gc_load_status = GC_LOAD_STATUS_START; LPWSTR standaloneGcLocation = nullptr; CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_GCName, &standaloneGcLocation); if (!standaloneGcLocation) { return InitializeDefaultGC(); } else { return LoadAndInitializeGC(standaloneGcLocation); } } void GCHeapUtilities::RecordEventStateChange(bool isPublicProvider, GCEventKeyword keywords, GCEventLevel level) { CONTRACTL { MODE_ANY; NOTHROW; GC_NOTRIGGER; CAN_TAKE_LOCK; } CONTRACTL_END; StashKeywordAndLevel(isPublicProvider, keywords, level); } #endif // DACCESS_COMPILE
c++
code
12,113
2,006
/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * mir/check.cpp * - MIR Correctness validation */ #include "main_bindings.hpp" #include "mir.hpp" #include <hir/visitor.hpp> #include <hir_typeck/static.hpp> #include <mir/helpers.hpp> #include <mir/visit_crate_mir.hpp> namespace { ::HIR::TypeRef get_metadata_type(const ::MIR::TypeResolve& state, const ::HIR::TypeRef& unsized_ty) { static Span sp; if( const auto* tep = unsized_ty.m_data.opt_TraitObject() ) { const auto& trait_path = tep->m_trait; if( trait_path.m_path.m_path == ::HIR::SimplePath() ) { return ::HIR::TypeRef::new_unit(); } else { const auto& trait = *tep->m_trait.m_trait_ptr; const auto& vtable_ty_spath = trait.m_vtable_path; MIR_ASSERT(state, vtable_ty_spath != ::HIR::SimplePath(), "Trait with no vtable - " << trait_path); const auto& vtable_ref = state.m_resolve.m_crate.get_struct_by_path(state.sp, vtable_ty_spath); // Copy the param set from the trait in the trait object ::HIR::PathParams vtable_params = trait_path.m_path.m_params.clone(); // - Include associated types for(const auto& ty_b : trait_path.m_type_bounds) { auto idx = trait.m_type_indexes.at(ty_b.first); if(vtable_params.m_types.size() <= idx) vtable_params.m_types.resize(idx+1); vtable_params.m_types[idx] = ty_b.second.clone(); } // TODO: This should be a pointer return ::HIR::TypeRef::new_path( ::HIR::GenericPath(vtable_ty_spath, mv$(vtable_params)), &vtable_ref ); } } else if( unsized_ty.m_data.is_Slice() ) { return ::HIR::CoreType::Usize; } else if( const auto* tep = unsized_ty.m_data.opt_Path() ) { if( tep->binding.is_Struct() ) { switch( tep->binding.as_Struct()->m_struct_markings.dst_type ) { case ::HIR::StructMarkings::DstType::None: return ::HIR::TypeRef(); case ::HIR::StructMarkings::DstType::Possible: { const auto& path = tep->path.m_data.as_Generic(); const auto& str = *tep->binding.as_Struct(); auto monomorph = [&](const auto& tpl) { auto rv = monomorphise_type(state.sp, str.m_params, path.m_params, tpl); state.m_resolve.expand_associated_types(sp, rv); return rv; }; TU_MATCHA( (str.m_data), (se), (Unit, MIR_BUG(state, "Unit-like struct with DstType::Possible - " << unsized_ty ); ), (Tuple, return get_metadata_type( state, monomorph(se.back().ent) ); ), (Named, return get_metadata_type( state, monomorph(se.back().second.ent) ); ) ) throw ""; } case ::HIR::StructMarkings::DstType::Slice: return ::HIR::CoreType::Usize; case ::HIR::StructMarkings::DstType::TraitObject: return ::HIR::TypeRef::new_unit(); // TODO: Get the actual inner metadata type? } } return ::HIR::TypeRef(); } else { return ::HIR::TypeRef(); } } } //template<typename T> //::std::ostream& operator<<(::std::ostream& os, const T& v) { // v.fmt(os); // return os; //} // [ValState] = Value state tracking (use after move, uninit, ...) // - [ValState] No drops or usage of uninitalised values (Uninit, Moved, or Dropped) // - [ValState] Temporaries are write-once. // - Requires maintaining state information for all variables/temporaries with support for loops void MIR_Validate_ValState(::MIR::TypeResolve& state, const ::MIR::Function& fcn) { TRACE_FUNCTION; // > Iterate through code, creating state maps. Save map at the start of each bb. struct ValStates { enum class State { Invalid, Either, Valid, }; State ret_state = State::Invalid; ::std::vector<State> args; ::std::vector<State> locals; ValStates() {} ValStates(size_t n_args, size_t n_locals): args(n_args, State::Valid), locals(n_locals) { } explicit ValStates(const ValStates& v) = default; ValStates(ValStates&& v) = default; ValStates& operator=(const ValStates& v) = delete; ValStates& operator=(ValStates&& v) = default; void fmt(::std::ostream& os) { os << "ValStates { "; switch(ret_state) { case State::Invalid: break; case State::Either: os << "?"; case State::Valid: os << "rv, "; break; } auto fmt_val_range = [&](const char* prefix, const auto& list) { for(auto range : runs(list)) { switch(list[range.first]) { case State::Invalid: continue; case State::Either: os << "?"; break; case State::Valid: break; } if( range.first == range.second ) { os << prefix << range.first << ", "; } else { os << prefix << range.first << "-" << prefix << range.second << ", "; } } }; fmt_val_range("a", this->args); fmt_val_range("_", this->locals); os << "}"; } bool operator==(const ValStates& x) const { if( ret_state != x.ret_state ) return false; if( args != x.args ) return false; if( locals != x.locals ) return false; return true; } bool empty() const { return locals.empty() && args.empty(); } // NOTE: Moves if this state is empty bool merge(unsigned bb_idx, ValStates& other) { DEBUG("bb" << bb_idx << " this=" << FMT_CB(ss,this->fmt(ss);) << ", other=" << FMT_CB(ss,other.fmt(ss);)); if( this->empty() ) { *this = ValStates(other); return true; } else if( *this == other ) { return false; } else { bool rv = false; rv |= ValStates::merge_state(this->ret_state, other.ret_state); rv |= ValStates::merge_lists(this->args , other.args ); rv |= ValStates::merge_lists(this->locals, other.locals); return rv; } } void mark_validity(const ::MIR::TypeResolve& state, const ::MIR::LValue& lv, bool is_valid) { if( !lv.m_wrappers.empty()) { return ; } TU_MATCHA( (lv.m_root), (e), (Return, ret_state = is_valid ? State::Valid : State::Invalid; ), (Argument, MIR_ASSERT(state, e < this->args.size(), "Argument index out of range " << lv); DEBUG("arg$" << e << " = " << (is_valid ? "Valid" : "Invalid")); this->args[e] = is_valid ? State::Valid : State::Invalid; ), (Local, MIR_ASSERT(state, e < this->locals.size(), "Local index out of range - " << lv); DEBUG("_" << e << " = " << (is_valid ? "Valid" : "Invalid")); this->locals[e] = is_valid ? State::Valid : State::Invalid; ), (Static, ) ) } void ensure_valid(const ::MIR::TypeResolve& state, const ::MIR::LValue& lv) { TU_MATCHA( (lv.m_root), (e), (Return, if( this->ret_state != State::Valid ) MIR_BUG(state, "Use of non-valid lvalue - " << lv); ), (Argument, MIR_ASSERT(state, e < this->args.size(), "Arg index out of range"); if( this->args[e] != State::Valid ) MIR_BUG(state, "Use of non-valid lvalue - " << lv); ), (Local, MIR_ASSERT(state, e < this->locals.size(), "Local index out of range"); if( this->locals[e] != State::Valid ) MIR_BUG(state, "Use of non-valid lvalue - " << lv); ), (Static, ) ) for(const auto& w : lv.m_wrappers) { if( w.is_Index() ) { if( this->locals[w.as_Index()] != State::Valid ) MIR_BUG(state, "Use of non-valid lvalue - " << ::MIR::LValue::new_Local(w.as_Index())); } } } void move_val(const ::MIR::TypeResolve& state, const ::MIR::LValue& lv) { ensure_valid(state, lv); if( ! state.lvalue_is_copy(lv) ) { mark_validity(state, lv, false); } } void move_val(const ::MIR::TypeResolve& state, const ::MIR::Param& p) { if( const auto* e = p.opt_LValue() ) { move_val(state, *e); } } private: static bool merge_state(State& a, State& b) { bool rv = false; if( a != b ) { // NOTE: This is an attempted optimisation to avoid re-running a block when it's not a new state. if( a == State::Either /*|| b == State::Either*/ ) { } else { rv = true; } a = State::Either; b = State::Either; } return rv; } static bool merge_lists(::std::vector<State>& a, ::std::vector<State>& b) { bool rv = false; assert( a.size() == b.size() ); // TODO: This is a really hot bit of code (according to valgrind), need to find a way of cooling it for(unsigned int i = 0; i < a.size(); i++) { rv |= merge_state(a[i], b[i]); } return rv; } }; ::std::vector< ValStates> block_start_states( fcn.blocks.size() ); struct ToVisit { unsigned int bb; ::std::vector<unsigned int> path; ValStates state; }; // TODO: Remove this? The path is useful, but the cloned states are really expensive // - Option: Keep the paths, but only ever use the pre-set entry state? ::std::vector<ToVisit> to_visit_blocks; // TODO: Check that all used locals are also set (anywhere at all) auto add_to_visit = [&](unsigned int idx, ::std::vector<unsigned int> src_path, ValStates& vs, bool can_move) { for(const auto& b : to_visit_blocks) if( b.bb == idx && b.state == vs) return ; if( block_start_states.at(idx) == vs ) return ; src_path.push_back(idx); // TODO: Update the target block, and only visit if we've induced a change to_visit_blocks.push_back( ToVisit { idx, mv$(src_path), (can_move ? mv$(vs) : ValStates(vs)) } ); }; auto add_to_visit_move = [&](unsigned int idx, ::std::vector<unsigned int> src_path, ValStates vs) { add_to_visit(idx, mv$(src_path), vs, true); }; auto add_to_visit_copy = [&](unsigned int idx, ::std::vector<unsigned int> src_path, ValStates& vs) { add_to_visit(idx, mv$(src_path), vs, false); }; add_to_visit_move( 0, {}, ValStates { state.m_args.size(), fcn.locals.size() } ); while( to_visit_blocks.size() > 0 ) { auto block = to_visit_blocks.back().bb; auto path = mv$(to_visit_blocks.back().path); auto val_state = mv$( to_visit_blocks.back().state ); to_visit_blocks.pop_back(); assert(block < fcn.blocks.size()); // 1. Apply current state to `block_start_states` (merging if needed) // - If no change happened, skip. if( ! block_start_states.at(block).merge(block, val_state) ) { DEBUG("BB" << block << " via [" << path << "] nochange " << FMT_CB(ss,val_state.fmt(ss);)); continue ; } ASSERT_BUG(Span(), val_state.locals.size() == fcn.locals.size(), ""); DEBUG("BB" << block << " via [" << path << "] " << FMT_CB(ss,val_state.fmt(ss);)); // 2. Using the newly merged state, iterate statements checking the usage and updating state. const auto& bb = fcn.blocks[block]; for(unsigned int stmt_idx = 0; stmt_idx < bb.statements.size(); stmt_idx ++) { const auto& stmt = bb.statements[stmt_idx]; state.set_cur_stmt(block, stmt_idx); DEBUG(state << stmt); switch( stmt.tag() ) { case ::MIR::Statement::TAGDEAD: throw ""; case ::MIR::Statement::TAG_SetDropFlag: break; case ::MIR::Statement::TAG_Drop: // Invalidate the slot if( stmt.as_Drop().flag_idx == ~0u ) { val_state.ensure_valid(state, stmt.as_Drop().slot); } val_state.mark_validity( state, stmt.as_Drop().slot, false ); break; case ::MIR::Statement::TAG_Asm: for(const auto& v : stmt.as_Asm().inputs) val_state.ensure_valid(state, v.second); for(const auto& v : stmt.as_Asm().outputs) val_state.mark_validity( state, v.second, true ); break; case ::MIR::Statement::TAG_Assign: // Destination must be valid for(const auto& w : stmt.as_Assign().dst.m_wrappers) { if( w.is_Deref() ) { // TODO: Check validity of the rest of the wrappers. } if( w.is_Index() ) { if( val_state.locals[w.as_Index()] != ValStates::State::Valid ) MIR_BUG(state, "Use of non-valid lvalue - " << ::MIR::LValue::new_Local(w.as_Index())); } } // Check source (and invalidate sources) TU_MATCH( ::MIR::RValue, (stmt.as_Assign().src), (se), (Use, val_state.move_val(state, se); ), (Constant, //(void)state.get_const_type(se); ), (SizedArray, val_state.move_val(state, se.val); ), (Borrow, val_state.ensure_valid(state, se.val); ), (Cast, // Well.. it's not exactly moved... val_state.ensure_valid(state, se.val); //val_state.move_val(state, se.val); ), (BinOp, val_state.move_val(state, se.val_l); val_state.move_val(state, se.val_r); ), (UniOp, val_state.move_val(state, se.val); ), (DstMeta, val_state.ensure_valid(state, se.val); ), (DstPtr, val_state.ensure_valid(state, se.val); ), (MakeDst, //val_state.move_val(state, se.ptr_val); if( const auto* e = se.ptr_val.opt_LValue() ) val_state.ensure_valid(state, *e); val_state.move_val(state, se.meta_val); ), (Tuple, for(const auto& v : se.vals) val_state.move_val(state, v); ), (Array, for(const auto& v : se.vals) val_state.move_val(state, v); ), (Variant, val_state.move_val(state, se.val); ), (Struct, for(const auto& v : se.vals) val_state.move_val(state, v); ) ) // Mark destination as valid val_state.mark_validity( state, stmt.as_Assign().dst, true ); break; case ::MIR::Statement::TAG_ScopeEnd: //for(auto idx : stmt.as_ScopeEnd().vars) // val_state.mark_validity(state, ::MIR::LValue::make_Variable(idx), false); //for(auto idx : stmt.as_ScopeEnd().tmps) // val_state.mark_validity(state, ::MIR::LValue::make_Temporary({idx}), false); break; } } // 3. Pass new state on to destination blocks state.set_cur_stmt_term(block); DEBUG(state << bb.terminator); TU_MATCH_HDRA( (bb.terminator), { ) TU_ARMA(Incomplete, e) { // Should be impossible here. } TU_ARMA(Return, e) { // Check if the return value has been set val_state.ensure_valid( state, ::MIR::LValue::new_Return() ); // Ensure that no other non-Copy values are valid for(unsigned int i = 0; i < val_state.locals.size(); i ++) { if( val_state.locals[i] == ValStates::State::Invalid ) { } else if( state.m_resolve.type_is_copy(state.sp, fcn.locals[i]) ) { } else { // TODO: Error, becuase this has just been leaked } } } TU_ARMA(Diverge, e) { // TODO: Ensure that cleanup has been performed. } TU_ARMA(Goto, e) { // Push block with the new state add_to_visit_move( e, mv$(path), mv$(val_state) ); } TU_ARMA(Panic, e) { // What should be done here? } TU_ARMA(If, e) { // Push blocks val_state.ensure_valid( state, e.cond ); add_to_visit_copy( e.bb0, path, val_state ); add_to_visit_move( e.bb1, mv$(path), mv$(val_state) ); } TU_ARMA(Switch, e) { val_state.ensure_valid( state, e.val ); for(const auto& tgt : e.targets) { add_to_visit( tgt, path, val_state, (&tgt == &e.targets.back()) ); } } TU_ARMA(SwitchValue, e) { val_state.ensure_valid( state, e.val ); for(const auto& tgt : e.targets) { add_to_visit_copy( tgt, path, val_state ); } add_to_visit_move( e.def_target, path, mv$(val_state) ); } TU_ARMA(Call, e) { if( e.fcn.is_Value() ) val_state.ensure_valid( state, e.fcn.as_Value() ); for(const auto& arg : e.args) val_state.move_val( state, arg ); // Push blocks (with return valid only in one) add_to_visit_copy(e.panic_block, path, val_state); // TODO: If the function returns
c++
code
19,999
4,149
/* Copyright (c) 2018 Big Ladder Software LLC. All rights reserved. * See the LICENSE file for additional terms and conditions. */ // Standard #include "gmock/gmock.h" #include "gtest/gtest.h" #include <chrono> #include <iostream> // btwxt #include "fixtures.hpp" #include <btwxt.h> #include <error.h> #include <griddeddata.h> using namespace Btwxt; TEST_F(TwoDFixture, construct_from_gridded_data) { Btwxt::LOG_LEVEL = 0; RegularGridInterpolator rgi_from_grid(test_gridded_data); std::size_t ndims = rgi_from_grid.get_ndims(); EXPECT_EQ(ndims, 2u); Btwxt::LOG_LEVEL = 1; } TEST_F(TwoDFixture, target_undefined) { std::vector<double> returned_target; std::vector<std::size_t> bad_floor; double bad_result; std::string TargetExpectedOut = " WARNING: The current target was requested, but no target has been set.\n"; std::string ResultsExpectedOut = " WARNING: Results were requested, but no target has been set.\n"; // The test fixture does not instantiate a GridPoint. EXPECT_STDOUT(returned_target = test_rgi.get_current_target();, TargetExpectedOut); std::vector<double> expected_result = {0, 0}; EXPECT_EQ(returned_target, expected_result); EXPECT_STDOUT(bad_result = test_rgi.get_value_at_target(0);, ResultsExpectedOut); EXPECT_EQ(bad_result, 0); // Define the target; make sure it works now. test_rgi.set_new_target(target); std::string EmptyOut = ""; EXPECT_STDOUT(returned_target = test_rgi.get_current_target();, EmptyOut); expected_result = {12, 5}; EXPECT_EQ(returned_target, expected_result); // Clear the target; see that it reverts to warnings. test_rgi.clear_current_target(); EXPECT_STDOUT(returned_target = test_rgi.get_current_target();, TargetExpectedOut); expected_result = {0, 0}; EXPECT_EQ(returned_target, expected_result); EXPECT_STDOUT(bad_result = test_rgi.get_value_at_target(0);, ResultsExpectedOut); EXPECT_EQ(bad_result, 0); } TEST_F(CubicFixture, spacing_multiplier) { double result; result = test_gridded_data.get_axis_spacing_mult(0, 0, 0); EXPECT_DOUBLE_EQ(result, 1.0); result = test_gridded_data.get_axis_spacing_mult(0, 1, 0); EXPECT_DOUBLE_EQ(result, (10 - 6) / (15.0 - 6.0)); result = test_gridded_data.get_axis_spacing_mult(0, 0, 1); EXPECT_DOUBLE_EQ(result, (15 - 10) / (15.0 - 6.0)); result = test_gridded_data.get_axis_spacing_mult(0, 1, 2); EXPECT_DOUBLE_EQ(result, 1.0); result = test_gridded_data.get_axis_spacing_mult(1, 0, 0); EXPECT_DOUBLE_EQ(result, 0.0); } TEST_F(CubicFixture, interpolate) { test_rgi.set_new_target(target); Btwxt::LOG_LEVEL = 0; auto start = std::chrono::high_resolution_clock::now(); std::vector<double> result = test_rgi.get_values_at_target(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); showMessage(MsgLevel::MSG_INFO, stringify("Time to do cubic interpolation: ", duration.count(), " microseconds")); Btwxt::LOG_LEVEL = 1; EXPECT_THAT(result, testing::ElementsAre(testing::DoubleEq(4.158), testing::DoubleEq(11.836))); } TEST_F(TwoDFixture, interpolate) { Btwxt::LOG_LEVEL = 0; test_rgi.set_new_target(target); // All values, current target std::vector<double> result = test_rgi.get_values_at_target(); EXPECT_THAT(result, testing::ElementsAre(testing::DoubleEq(4.2), testing::DoubleEq(8.4))); Btwxt::LOG_LEVEL = 1; // Single value, current target double d_result = test_rgi.get_value_at_target(0); EXPECT_DOUBLE_EQ(d_result, 4.2); std::vector<double> another_target = {8.1, 4.2}; // All values, fresh target result = test_rgi.get_values_at_target(another_target); EXPECT_THAT(result, testing::ElementsAre(testing::DoubleEq(3.189), testing::DoubleEq(6.378))); // Single value, fresh target d_result = test_rgi.get_value_at_target(another_target, 1); EXPECT_DOUBLE_EQ(d_result, 6.378); } TEST_F(TwoDFixture, extrapolate) { // axis1 is designated constant extrapolation std::vector<double> const_extr_target = {10, 3}; Btwxt::LOG_LEVEL = 0; std::vector<double> result = test_rgi(const_extr_target); EXPECT_THAT(result, testing::ElementsAre(testing::DoubleEq(2), testing::DoubleEq(4))); Btwxt::LOG_LEVEL = 1; // axis0 is designated linear extrapolation std::vector<double> lin_extr_target = {18, 5}; Btwxt::LOG_LEVEL = 0; result = test_rgi(lin_extr_target); EXPECT_THAT(result, testing::ElementsAre(testing::DoubleEq(1.8), testing::DoubleEq(3.6))); Btwxt::LOG_LEVEL = 1; } TEST_F(TwoDFixture, invalid_inputs) { // we expect two errors that the value table inputs do not match the grid // we expect an error that the target dimensions do not match the grid std::vector<double> short_values = {6, 3, 2, 8, 4}; EXPECT_THROW(test_gridded_data.add_value_table(short_values);, std::invalid_argument); std::vector<double> long_values = {1, 1, 1, 1, 1, 1, 1}; EXPECT_THROW(test_gridded_data.add_value_table(long_values);, std::invalid_argument); std::vector<double> short_target = {1}; EXPECT_THROW(test_rgi.set_new_target(short_target);, std::invalid_argument); std::vector<double> long_target = {1, 2, 3}; EXPECT_THROW(test_rgi.set_new_target(long_target);, std::invalid_argument); } TEST_F(OneDFixture, cubic_interpolate) { Btwxt::LOG_LEVEL = 0; test_gridded_data.set_axis_interp_method(0, Method::CUBIC); test_rgi = RegularGridInterpolator(test_gridded_data); double result = test_rgi.get_values_at_target(target)[0]; Btwxt::LOG_LEVEL = 1; EXPECT_NEAR(result, 4.804398, 0.0001); } TEST_F(OneDL0Fixture, throw_test) { Btwxt::LOG_LEVEL = 0; EXPECT_THROW(GriddedData(grid, values),std::invalid_argument); } TEST_F(OneDL1Fixture, cubic_interpolate) { Btwxt::LOG_LEVEL = 0; test_gridded_data.set_axis_interp_method(0, Method::CUBIC); test_rgi = RegularGridInterpolator(test_gridded_data); double result = test_rgi.get_values_at_target(target)[0]; Btwxt::LOG_LEVEL = 1; EXPECT_NEAR(result, 5., 0.0001); } TEST_F(OneDL2Fixture, cubic_interpolate) { Btwxt::LOG_LEVEL = 0; test_gridded_data.set_axis_interp_method(0, Method::CUBIC); test_rgi = RegularGridInterpolator(test_gridded_data); double result = test_rgi.get_values_at_target(target)[0]; Btwxt::LOG_LEVEL = 1; EXPECT_NEAR(result, 5.25, 0.0001); } TEST_F(TwoDFixture, cubic_interpolate) { Btwxt::LOG_LEVEL = 0; test_gridded_data.set_axis_interp_method(0, Method::CUBIC); test_gridded_data.set_axis_interp_method(1, Method::CUBIC); test_rgi = RegularGridInterpolator(test_gridded_data); test_rgi.set_new_target(target); // All values, current target std::vector<double> result = test_rgi.get_values_at_target(); EXPECT_THAT(result, testing::ElementsAre(testing::DoubleEq(4.416), testing::DoubleEq(8.832))); Btwxt::LOG_LEVEL = 1; } TEST_F(TwoDFixture, normalize) { Btwxt::LOG_LEVEL = 0; test_gridded_data.set_axis_interp_method(0, Method::CUBIC); test_gridded_data.set_axis_interp_method(1, Method::CUBIC); test_rgi = RegularGridInterpolator(test_gridded_data); test_rgi.set_new_target(target); // All values, current target test_rgi.normalize_values_at_target((std::size_t)0); // normalize first value table std::vector<double> result = test_rgi.get_values_at_target(); EXPECT_THAT(result, testing::ElementsAre(testing::DoubleEq(1.0), testing::DoubleEq(8.832))); Btwxt::LOG_LEVEL = 1; } TEST_F(TwoDSimpleNormalizationFixture, normalization_return_scalar) { std::vector<double> target {7.0, 3.0}; std::vector<double> normalization_target = {2.0, 3.0}; double expected_divisor {test_function(normalization_target)}; double expected_value_at_target {test_function(target)/expected_divisor}; double return_scalar = test_rgi.normalize_values_at_target(0, normalization_target, 1.0); test_rgi.set_new_target(target); std::vector<double> results = test_rgi.get_values_at_target(); EXPECT_THAT(return_scalar, testing::DoubleEq(expected_divisor)); EXPECT_THAT(results, testing::ElementsAre(expected_value_at_target)); } TEST_F(TwoDSimpleNormalizationFixture, normalization_return_compound_scalar) { std::vector<double> target {7.0, 3.0}; std::vector<double> normalization_target = {2.0, 3.0}; double normalization_divisor = 4.0; double expected_compound_divisor {test_function(normalization_target)*normalization_divisor}; double expected_value_at_target {test_function(target)/expected_compound_divisor}; double return_scalar = test_rgi.normalize_values_at_target(0, normalization_target, normalization_divisor); test_rgi.set_new_target(target); std::vector<double> results = test_rgi.get_values_at_target(); EXPECT_THAT(return_scalar, testing::DoubleEq(expected_compound_divisor)); EXPECT_THAT(results, testing::ElementsAre(expected_value_at_target)); }
c++
code
8,877
1,895
#include "Drawer.hpp" using namespace Kruskal; using namespace cv; Drawer::Drawer(const size_t a_height, const size_t a_width) { m_height = (a_height * 2) - 1; m_width = (a_width * 2) - 1; m_mat = Mat::zeros(m_height, m_width, CV_8UC3); m_mat.setTo(Scalar(0, 0, 0)); } Mat& Drawer::getMat() { return m_mat; } using pii = std::pair<size_t, size_t>; void Drawer::drawLine(const pii a, const pii b) { line(m_mat, Point(a.first, a.second) * 2, Point(b.first, b.second) * 2, Scalar(255, 255, 255), 1, cv::LINE_8); }
c++
code
537
162
/* //@HEADER // ************************************************************************ // // rom_has_const_apply_jacobian_method_accept_state_operand_result_return_void.hpp // Pressio // Copyright 2019 // 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. // // Pressio is licensed under BSD-3-Clause terms of use: // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Francesco Rizzi ([email protected]) // // ************************************************************************ //@HEADER */ #ifndef ROM_PREDICATES_ROM_HAS_CONST_APPLY_JACOBIAN_METHOD_ACCEPT_STATE_OPERAND_RESULT_RETURN_VOID_HPP_ #define ROM_PREDICATES_ROM_HAS_CONST_APPLY_JACOBIAN_METHOD_ACCEPT_STATE_OPERAND_RESULT_RETURN_VOID_HPP_ namespace pressio{ namespace rom{ template < class T, class StateType, class OperandType, class ResultType, class = void > struct has_const_apply_jacobian_method_accept_state_operand_result_return_void : std::false_type{}; template < class T, class StateType, class OperandType, class ResultType > struct has_const_apply_jacobian_method_accept_state_operand_result_return_void< T, StateType, OperandType, ResultType, ::pressio::mpl::void_t< decltype ( std::declval<T const>().applyJacobian ( std::declval<StateType const&>(), std::declval<OperandType const&>(), std::declval<ResultType &>() ) ) > >: std::true_type{}; }} #endif // ROM_PREDICATES_ROM_HAS_CONST_APPLY_JACOBIAN_METHOD_ACCEPT_STATE_OPERAND_RESULT_RETURN_VOID_HPP_
c++
code
3,194
646
#include <bits/stdc++.h> #define MAXN 100005 using namespace std; int T,n,m,x; bool a[MAXN],b[MAXN]; int main() { scanf("%d",&T); while (T--) { scanf("%d",&n);int ans=0; for (int i=1;i<=n;i++) a[i]=b[i]=false; for (int i=1;i<=n;i++) { scanf("%d",&m); for (int j=1;j<=m;j++) { scanf("%d",&x); if (!a[x]&&!b[i]) { a[x]=b[i]=true;++ans; } } } if (ans==n){puts("OPTIMAL");continue;} int p=0,q=0; for(int i=1;i<=n;i++) { if (!a[i]) p=i; if (!b[i]) q=i; } puts("IMPROVE"); printf("%d %d\n",q,p); } return 0; }
c++
code
573
287
// Copyleft #include "Grabber.h" #include "GameFramework/PlayerController.h" #include "Runtime/Engine/Public/DrawDebugHelpers.h" #include "Runtime/Engine/Public/CollisionQueryParams.h" // Sets default values for this component's properties UGrabber::UGrabber() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = true; // ... } // Called when the game starts void UGrabber::BeginPlay() { Super::BeginPlay(); UE_LOG(LogTemp, Warning, TEXT("Grabber is here!")); InputCompoment = GetOwner()->FindComponentByClass<UInputComponent>(); BindPhysicsHandle(); BindInputComponent(); } void UGrabber::BindPhysicsHandle() { PhysicsHandle = GetOwner()->FindComponentByClass<UPhysicsHandleComponent>(); if (PhysicsHandle) { } else { UE_LOG(LogTemp, Error, TEXT("%s Missing Physics component"), *(GetOwner()->GetName())); } } void UGrabber::Grab() { UE_LOG(LogTemp, Warning, TEXT("Pressed")); GetFirstPhysicsBodyInReach(); } void UGrabber::Release() { UE_LOG(LogTemp, Warning, TEXT("Released")); } const FHitResult UGrabber::GetFirstPhysicsBodyInReach() { FVector PlayerPosition; FRotator PlayerRotation; GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(PlayerPosition, PlayerRotation); //UE_LOG(LogTemp, Warning, TEXT("Grabber: player view point postion %s, rotation %s"), *PlayerPostion.ToCompactString(), *PlayerRotation.ToCompactString()); FVector LineTraceEnd = PlayerPosition + (PlayerRotation.Vector() * Reach); FHitResult Hit; FCollisionQueryParams TraceParameters(FName(TEXT("")), false, GetOwner()); GetWorld()->LineTraceSingleByObjectType( Hit, PlayerPosition, LineTraceEnd, FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody), TraceParameters ); AActor* ActorHit = Hit.GetActor(); if (ActorHit) { UE_LOG(LogTemp, Warning, TEXT("Line trace hit: %s"), *(ActorHit->GetName())); } return FHitResult(); } void UGrabber::BindInputComponent() { if (InputCompoment) { InputCompoment->BindAction("Grab", IE_Pressed, this, &UGrabber::Grab); InputCompoment->BindAction("Grab", IE_Released, this, &UGrabber::Release); } else { UE_LOG(LogTemp, Error, TEXT("%s Missing Input Component"), *(GetOwner()->GetName())); } } // Called every frame void UGrabber::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); }
c++
code
2,565
557
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef _ALL_SOURCE #define _ALL_SOURCE // Enables thrd_create_with_name in <threads.h>. #endif #include "src/storage/blobfs/compression/decompressor_sandbox/decompressor_impl.h" #include <fuchsia/blobfs/internal/llcpp/fidl.h> #include <fuchsia/scheduler/cpp/fidl.h> #include <lib/fdio/directory.h> #include <lib/fzl/owned-vmo-mapper.h> #include <lib/syslog/cpp/macros.h> #include <lib/trace/event.h> #include <lib/zx/thread.h> #include <lib/zx/time.h> #include <threads.h> #include <zircon/errors.h> #include <zircon/status.h> #include <zircon/threads.h> #include <zircon/types.h> #include <src/lib/chunked-compression/chunked-decompressor.h> #include "src/storage/blobfs/compression/decompressor.h" #include "src/storage/blobfs/compression/external_decompressor.h" #include "src/storage/blobfs/compression_settings.h" namespace { struct FifoInfo { zx::fifo fifo; fzl::OwnedVmoMapper compressed_mapper; fzl::OwnedVmoMapper decompressed_mapper; }; } // namespace namespace blobfs { // This will only decompress a set of complete chunks, if the beginning or end // of the range are not chunk aligned this operation will fail. zx_status_t DecompressChunkedPartial(const fzl::OwnedVmoMapper& decompressed_mapper, const fzl::OwnedVmoMapper& compressed_mapper, const fuchsia_blobfs_internal::wire::Range decompressed, const fuchsia_blobfs_internal::wire::Range compressed, size_t* bytes_decompressed) { const uint8_t* src = static_cast<const uint8_t*>(compressed_mapper.start()) + compressed.offset; uint8_t* dst = static_cast<uint8_t*>(decompressed_mapper.start()) + decompressed.offset; chunked_compression::ChunkedDecompressor decompressor; return decompressor.DecompressFrame(src, compressed.size, dst, decompressed.size, bytes_decompressed); } zx_status_t DecompressFull(const fzl::OwnedVmoMapper& decompressed_mapper, const fzl::OwnedVmoMapper& compressed_mapper, size_t decompressed_length, size_t compressed_length, CompressionAlgorithm algorithm, size_t* bytes_decompressed) { std::unique_ptr<Decompressor> decompressor = nullptr; if (zx_status_t status = Decompressor::Create(algorithm, &decompressor); status != ZX_OK) { return status; } *bytes_decompressed = decompressed_length; return decompressor->Decompress(decompressed_mapper.start(), bytes_decompressed, compressed_mapper.start(), compressed_length); } // The actual handling of a request on the fifo. void HandleFifo(const fzl::OwnedVmoMapper& compressed_mapper, const fzl::OwnedVmoMapper& decompressed_mapper, const fuchsia_blobfs_internal::wire::DecompressRequest* request, fuchsia_blobfs_internal::wire::DecompressResponse* response) { TRACE_DURATION("decompressor", "HandleFifo", "length", request->decompressed.size); size_t bytes_decompressed = 0; switch (request->algorithm) { case fuchsia_blobfs_internal::wire::CompressionAlgorithm::CHUNKED_PARTIAL: response->status = DecompressChunkedPartial(decompressed_mapper, compressed_mapper, request->decompressed, request->compressed, &bytes_decompressed); break; case fuchsia_blobfs_internal::wire::CompressionAlgorithm::LZ4: case fuchsia_blobfs_internal::wire::CompressionAlgorithm::ZSTD: case fuchsia_blobfs_internal::wire::CompressionAlgorithm::ZSTD_SEEKABLE: case fuchsia_blobfs_internal::wire::CompressionAlgorithm::CHUNKED: if (request->decompressed.offset != 0 || request->compressed.offset != 0) { bytes_decompressed = 0; response->status = ZX_ERR_NOT_SUPPORTED; } else { CompressionAlgorithm algorithm = ExternalDecompressorClient::CompressionAlgorithmFidlToLocal(request->algorithm); response->status = DecompressFull(decompressed_mapper, compressed_mapper, request->decompressed.size, request->compressed.size, algorithm, &bytes_decompressed); } break; case fuchsia_blobfs_internal::wire::CompressionAlgorithm::UNCOMPRESSED: response->status = ZX_ERR_NOT_SUPPORTED; break; } response->size = bytes_decompressed; } // Watches a fifo for requests to take data from the compressed_vmo and // extract the result into the memory region of decompressed_mapper. void WatchFifo(zx::fifo fifo, fzl::OwnedVmoMapper compressed_mapper, fzl::OwnedVmoMapper decompressed_mapper) { constexpr zx_signals_t kFifoReadSignals = ZX_FIFO_READABLE | ZX_FIFO_PEER_CLOSED; constexpr zx_signals_t kFifoWriteSignals = ZX_FIFO_WRITABLE | ZX_FIFO_PEER_CLOSED; while (fifo.is_valid()) { zx_signals_t signal; fifo.wait_one(kFifoReadSignals, zx::time::infinite(), &signal); // It doesn't matter if there's anything left in the queue, nobody is there // to read the response. if ((signal & ZX_FIFO_PEER_CLOSED) != 0) { break; } fuchsia_blobfs_internal::wire::DecompressRequest request; zx_status_t status = fifo.read(sizeof(request), &request, 1, nullptr); if (status != ZX_OK) { break; } fuchsia_blobfs_internal::wire::DecompressResponse response; HandleFifo(compressed_mapper, decompressed_mapper, &request, &response); fifo.wait_one(kFifoWriteSignals, zx::time::infinite(), &signal); if ((signal & ZX_FIFO_WRITABLE) == 0 || fifo.write(sizeof(response), &response, 1, nullptr) != ZX_OK) { break; } } } // A Wrapper around WatchFifo just to unwrap the data in the callback provided // by thrd_create_With_name(). int WatchFifoWrapper(void* data) { std::unique_ptr<FifoInfo> info(static_cast<FifoInfo*>(data)); WatchFifo(std::move(info->fifo), std::move(info->compressed_mapper), std::move(info->decompressed_mapper)); return 0; } void SetDeadlineProfile(thrd_t* thread) { zx::channel channel0, channel1; zx_status_t status = zx::channel::create(0u, &channel0, &channel1); if (status != ZX_OK) { FX_LOGS(WARNING) << "[decompressor]: Could not create channel pair: " << zx_status_get_string(status); return; } // Connect to the scheduler profile provider service. status = fdio_service_connect( (std::string("/svc/") + fuchsia::scheduler::ProfileProvider::Name_).c_str(), channel0.release()); if (status != ZX_OK) { FX_LOGS(WARNING) << "[decompressor]: Could not connect to scheduler profile provider: " << zx_status_get_string(status); return; } fuchsia::scheduler::ProfileProvider_SyncProxy profile_provider(std::move(channel1)); // TODO(fxbug.dev/40858): Migrate to the role-based API when available, instead of hard // coding parameters. const zx_duration_t capacity = ZX_USEC(1000); const zx_duration_t deadline = ZX_MSEC(2); const zx_duration_t period = deadline; zx::profile profile; zx_status_t fidl_status = profile_provider.GetDeadlineProfile( capacity, deadline, period, "decompressor-fifo-thread", &status, &profile); if (status != ZX_OK || fidl_status != ZX_OK) { FX_LOGS(WARNING) << "[decompressor]: Failed to get deadline profile: " << zx_status_get_string(status) << ", " << zx_status_get_string(fidl_status); } else { auto zx_thread = zx::unowned_thread(thrd_get_zx_handle(*thread)); // Set the deadline profile. status = zx_thread->set_profile(profile, 0); if (status != ZX_OK) { FX_LOGS(WARNING) << "[decompressor]: Failed to set deadline profile: " << zx_status_get_string(status); } } } void DecompressorImpl::Create(zx::fifo server_end, zx::vmo compressed_vmo, zx::vmo decompressed_vmo, CreateCallback callback) { size_t vmo_size; zx_status_t status = decompressed_vmo.get_size(&vmo_size); if (status != ZX_OK) { return callback(status); } fzl::OwnedVmoMapper decompressed_mapper; status = decompressed_mapper.Map(std::move(decompressed_vmo), vmo_size); if (status != ZX_OK) { return callback(status); } status = compressed_vmo.get_size(&vmo_size); if (status != ZX_OK) { return callback(status); } fzl::OwnedVmoMapper compressed_mapper; status = compressed_mapper.Map(std::move(compressed_vmo), vmo_size, ZX_VM_PERM_READ); if (status != ZX_OK) { return callback(status); } thrd_t handler_thread; std::unique_ptr<FifoInfo> info = std::make_unique<FifoInfo>(); *info = {std::move(server_end), std::move(compressed_mapper), std::move(decompressed_mapper)}; if (thrd_create_with_name(&handler_thread, WatchFifoWrapper, info.release(), "decompressor-fifo-thread") != thrd_success) { return callback(ZX_ERR_INTERNAL); } SetDeadlineProfile(&handler_thread); thrd_detach(handler_thread); return callback(ZX_OK); } } // namespace blobfs
c++
code
9,266
1,675
// RUN: %clang_cc1 -verify -fopenmp %s namespace X { int x; }; struct B { static int ib; // expected-note {{'B::ib' declared here}} static int bfoo() { return 8; } }; int bfoo() { return 4; } int z; const int C1 = 1; const int C2 = 2; void test_linear_colons() { int B = 0; #pragma omp simd linear(B:bfoo()) for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{unexpected ':' in nested name specifier; did you mean '::'}} #pragma omp simd linear(B::ib:B:bfoo()) for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{use of undeclared identifier 'ib'; did you mean 'B::ib'}} #pragma omp simd linear(B:ib) for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{unexpected ':' in nested name specifier; did you mean '::'?}} #pragma omp simd linear(z:B:ib) for (int i = 0; i < 10; ++i) ; #pragma omp simd linear(B:B::bfoo()) for (int i = 0; i < 10; ++i) ; #pragma omp simd linear(X::x : ::z) for (int i = 0; i < 10; ++i) ; #pragma omp simd linear(B,::z, X::x) for (int i = 0; i < 10; ++i) ; #pragma omp simd linear(::z) for (int i = 0; i < 10; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd linear(B::bfoo()) for (int i = 0; i < 10; ++i) ; #pragma omp simd linear(B::ib,B:C1+C2) for (int i = 0; i < 10; ++i) ; } template<int L, class T, class N> T test_template(T* arr, N num) { N i; T sum = (T)0; T ind2 = - num * L; // expected-note {{'ind2' defined here}} // expected-error@+1 {{argument of a linear clause should be of integral or pointer type}} #pragma omp simd linear(ind2:L) for (i = 0; i < num; ++i) { T cur = arr[(int)ind2]; ind2 += L; sum += cur; } return T(); } template<int LEN> int test_warn() { int ind2 = 0; // expected-warning@+1 {{zero linear step (ind2 should probably be const)}} #pragma omp simd linear(ind2:LEN) for (int i = 0; i < 100; i++) { ind2 += LEN; } return ind2; } struct S1; // expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}} extern S1 a; class S2 { mutable int a; public: S2():a(0) { } }; const S2 b; // expected-note 2 {{'b' defined here}} const S2 ba[5]; class S3 { int a; public: S3():a(0) { } }; const S3 ca[5]; class S4 { int a; S4(); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}} template<class I, class C> int foomain(I argc, C **argv) { I e(4); I g(5); int i; int &j = i; #pragma omp simd linear // expected-error {{expected '(' after 'linear'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (val // expected-error {{use of undeclared identifier 'val'}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (uval( // expected-error {{expected expression}} expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (ref() // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (foo() // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear () // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (val argc // expected-error {{use of undeclared identifier 'val'}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (val(argc, // expected-error {{expected expression}} expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argc : 5) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+2 {{linear variable with incomplete type 'S1'}} // expected-error@+1 {{const-qualified variable cannot be linear}} #pragma omp simd linear (val(a, b):B::ib) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(ref(e, g)) // expected-error 2 {{variable of non-reference type 'int' can be used only with 'val' modifier, but used with 'ref'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(h) // expected-error {{threadprivate or thread local variable cannot be linear}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(uval(i)) // expected-error {{variable of non-reference type 'int' can be used only with 'val' modifier, but used with 'uval'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel { int v = 0; int i; #pragma omp simd linear(v:i) for (int k = 0; k < argc; ++k) { i = k; v += i; } } #pragma omp simd linear(ref(j)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(uval(j)) for (int k = 0; k < argc; ++k) ++k; int v = 0; #pragma omp simd linear(v:j) for (int k = 0; k < argc; ++k) { ++k; v += j; } #pragma omp simd linear(i) for (int k = 0; k < argc; ++k) ++k; return 0; } namespace A { double x; #pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}} } namespace C { using A::x; } void linear_modifiers(int argc) { int &f = argc; #pragma omp simd linear(f) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(val(f)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(uval(f)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(ref(f)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(foo(f)) // expected-error {{expected one of 'ref', val' or 'uval' modifiers}} for (int k = 0; k < argc; ++k) ++k; } int f; int main(int argc, char **argv) { double darr[100]; // expected-note@+1 {{in instantiation of function template specialization 'test_template<-4, double, int>' requested here}} test_template<-4>(darr, 4); // expected-note@+1 {{in instantiation of function template specialization 'test_warn<0>' requested here}} test_warn<0>(); S4 e(4); // expected-note {{'e' defined here}} S5 g(5); // expected-note {{'g' defined here}} int i; int &j = i; #pragma omp simd linear(f) linear(f) // expected-error {{linear variable cannot be linear}} expected-note {{defined as linear}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear // expected-error {{expected '(' after 'linear'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear () // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (val // expected-error {{use of undeclared identifier 'val'}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (ref()) // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (foo()) // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argc) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+2 {{linear variable with incomplete type 'S1'}} // expected-error@+1 {{const-qualified variable cannot be linear}} #pragma omp simd linear(a, b) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear (argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; // expected-error@+2 {{argument of a linear clause should be of integral or pointer type, not 'S4'}} // expected-error@+1 {{argument of a linear clause should be of integral or pointer type, not 'S5'}} #pragma omp simd linear(val(e, g)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(h, C::x) // expected-error 2 {{threadprivate or thread local variable cannot be linear}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel { int i; #pragma omp simd linear(val(i)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(uval(i) : 4) // expected-error {{variable of non-reference type 'int' can be used only with 'val' modifier, but used with 'uval'}} for (int k = 0; k < argc; ++k) { ++k; i += 4; } } #pragma omp simd linear(ref(j)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(i) for (int k = 0; k < argc; ++k) ++k; foomain<int,char>(argc,argv); // expected-note {{in instantiation of function template specialization 'foomain<int, char>' requested here}} return 0; }
c++
code
10,008
3,234
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 Ferdinando Ametrano Copyright (C) 2004, 2005, 2007 StatPro Italia srl Copyright (C) 2015 Peter Caspers This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ /*! \file constantoptionletvol.hpp \brief Constant caplet/floorlet volatility */ #ifndef quantlib_caplet_constant_volatility_hpp #define quantlib_caplet_constant_volatility_hpp #include <ql/termstructures/volatility/optionlet/optionletvolatilitystructure.hpp> namespace QuantLib { class Quote; //! Constant caplet volatility, no time-strike dependence class ConstantOptionletVolatility : public OptionletVolatilityStructure { public: //! floating reference date, floating market data ConstantOptionletVolatility(Natural settlementDays, const Calendar &cal, BusinessDayConvention bdc, const Handle< Quote > &volatility, const DayCounter &dc, VolatilityType type = ShiftedLognormal, Real displacement = 0.0); //! fixed reference date, floating market data ConstantOptionletVolatility(const Date &referenceDate, const Calendar &cal, BusinessDayConvention bdc, const Handle< Quote > &volatility, const DayCounter &dc, VolatilityType type = ShiftedLognormal, Real displacement = 0.0); //! floating reference date, fixed market data ConstantOptionletVolatility(Natural settlementDays, const Calendar &cal, BusinessDayConvention bdc, Volatility volatility, const DayCounter &dc, VolatilityType type = ShiftedLognormal, Real displacement = 0.0); //! fixed reference date, fixed market data ConstantOptionletVolatility(const Date &referenceDate, const Calendar &cal, BusinessDayConvention bdc, Volatility volatility, const DayCounter &dc, VolatilityType type = ShiftedLognormal, Real displacement = 0.0); //! \name TermStructure interface //@{ Date maxDate() const; //@} //! \name VolatilityTermStructure interface //@{ Real minStrike() const; Real maxStrike() const; //@} VolatilityType volatilityType() const; Real displacement() const; protected: std::shared_ptr<SmileSection> smileSectionImpl(const Date& d) const; std::shared_ptr<SmileSection> smileSectionImpl(Time) const; Volatility volatilityImpl(Time, Rate) const; private: Handle<Quote> volatility_; VolatilityType type_; Real displacement_; }; // inline definitions inline Date ConstantOptionletVolatility::maxDate() const { return Date::maxDate(); } inline Real ConstantOptionletVolatility::minStrike() const { return QL_MIN_REAL; } inline Real ConstantOptionletVolatility::maxStrike() const { return QL_MAX_REAL; } inline VolatilityType ConstantOptionletVolatility::volatilityType() const { return type_; } inline Real ConstantOptionletVolatility::displacement() const { return displacement_; } } #endif
c++
code
4,442
569
//===- Construction of pass pipelines -------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file /// /// This file provides the implementation of the PassBuilder based on our /// static pass registry as well as related functionality. It also provides /// helpers to aid in analyzing, debugging, and testing passes and pass /// pipelines. /// //===----------------------------------------------------------------------===// #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/BasicAliasAnalysis.h" #include "llvm/Analysis/CGSCCPassManager.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/InlineAdvisor.h" #include "llvm/Analysis/OptimizationRemarkEmitter.h" #include "llvm/Analysis/ProfileSummaryInfo.h" #include "llvm/Analysis/ScopedNoAliasAA.h" #include "llvm/Analysis/TypeBasedAliasAnalysis.h" #include "llvm/IR/PassManager.h" #include "llvm/Passes/OptimizationLevel.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/PGOOptions.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" #include "llvm/Transforms/Coroutines/CoroCleanup.h" #include "llvm/Transforms/Coroutines/CoroEarly.h" #include "llvm/Transforms/Coroutines/CoroElide.h" #include "llvm/Transforms/Coroutines/CoroSplit.h" #include "llvm/Transforms/IPO/AlwaysInliner.h" #include "llvm/Transforms/IPO/Annotation2Metadata.h" #include "llvm/Transforms/IPO/ArgumentPromotion.h" #include "llvm/Transforms/IPO/Attributor.h" #include "llvm/Transforms/IPO/CalledValuePropagation.h" #include "llvm/Transforms/IPO/ConstantMerge.h" #include "llvm/Transforms/IPO/CrossDSOCFI.h" #include "llvm/Transforms/IPO/DeadArgumentElimination.h" #include "llvm/Transforms/IPO/ElimAvailExtern.h" #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" #include "llvm/Transforms/IPO/FunctionAttrs.h" #include "llvm/Transforms/IPO/GlobalDCE.h" #include "llvm/Transforms/IPO/GlobalOpt.h" #include "llvm/Transforms/IPO/GlobalSplit.h" #include "llvm/Transforms/IPO/HotColdSplitting.h" #include "llvm/Transforms/IPO/IROutliner.h" #include "llvm/Transforms/IPO/InferFunctionAttrs.h" #include "llvm/Transforms/IPO/Inliner.h" #include "llvm/Transforms/IPO/LowerTypeTests.h" #include "llvm/Transforms/IPO/MergeFunctions.h" #include "llvm/Transforms/IPO/ModuleInliner.h" #include "llvm/Transforms/IPO/OpenMPOpt.h" #include "llvm/Transforms/IPO/PartialInlining.h" #include "llvm/Transforms/IPO/SCCP.h" #include "llvm/Transforms/IPO/SampleProfile.h" #include "llvm/Transforms/IPO/SampleProfileProbe.h" #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h" #include "llvm/Transforms/IPO/WholeProgramDevirt.h" #include "llvm/Transforms/InstCombine/InstCombine.h" #include "llvm/Transforms/Instrumentation/CGProfile.h" #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h" #include "llvm/Transforms/Instrumentation/InstrOrderFile.h" #include "llvm/Transforms/Instrumentation/InstrProfiling.h" #include "llvm/Transforms/Instrumentation/MemProfiler.h" #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" #include "llvm/Transforms/Scalar/ADCE.h" #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h" #include "llvm/Transforms/Scalar/AnnotationRemarks.h" #include "llvm/Transforms/Scalar/BDCE.h" #include "llvm/Transforms/Scalar/CallSiteSplitting.h" #include "llvm/Transforms/Scalar/ConstraintElimination.h" #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" #include "llvm/Transforms/Scalar/DFAJumpThreading.h" #include "llvm/Transforms/Scalar/DeadStoreElimination.h" #include "llvm/Transforms/Scalar/DivRemPairs.h" #include "llvm/Transforms/Scalar/EarlyCSE.h" #include "llvm/Transforms/Scalar/Float2Int.h" #include "llvm/Transforms/Scalar/GVN.h" #include "llvm/Transforms/Scalar/IndVarSimplify.h" #include "llvm/Transforms/Scalar/InstSimplifyPass.h" #include "llvm/Transforms/Scalar/JumpThreading.h" #include "llvm/Transforms/Scalar/LICM.h" #include "llvm/Transforms/Scalar/LoopDeletion.h" #include "llvm/Transforms/Scalar/LoopDistribute.h" #include "llvm/Transforms/Scalar/LoopFlatten.h" #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" #include "llvm/Transforms/Scalar/LoopInstSimplify.h" #include "llvm/Transforms/Scalar/LoopInterchange.h" #include "llvm/Transforms/Scalar/LoopLoadElimination.h" #include "llvm/Transforms/Scalar/LoopPassManager.h" #include "llvm/Transforms/Scalar/LoopRotation.h" #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" #include "llvm/Transforms/Scalar/LoopSink.h" #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h" #include "llvm/Transforms/Scalar/LoopUnrollPass.h" #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h" #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" #include "llvm/Transforms/Scalar/NewGVN.h" #include "llvm/Transforms/Scalar/Reassociate.h" #include "llvm/Transforms/Scalar/SCCP.h" #include "llvm/Transforms/Scalar/SROA.h" #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" #include "llvm/Transforms/Scalar/SimplifyCFG.h" #include "llvm/Transforms/Scalar/SpeculativeExecution.h" #include "llvm/Transforms/Scalar/TailRecursionElimination.h" #include "llvm/Transforms/Scalar/WarnMissedTransforms.h" #include "llvm/Transforms/Utils/AddDiscriminators.h" #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" #include "llvm/Transforms/Utils/CanonicalizeAliases.h" #include "llvm/Transforms/Utils/InjectTLIMappings.h" #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h" #include "llvm/Transforms/Utils/Mem2Reg.h" #include "llvm/Transforms/Utils/NameAnonGlobals.h" #include "llvm/Transforms/Utils/RelLookupTableConverter.h" #include "llvm/Transforms/Utils/SimplifyCFGOptions.h" #include "llvm/Transforms/Vectorize/LoopVectorize.h" #include "llvm/Transforms/Vectorize/SLPVectorizer.h" #include "llvm/Transforms/Vectorize/VectorCombine.h" using namespace llvm; static cl::opt<InliningAdvisorMode> UseInlineAdvisor( "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden, cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"), cl::values(clEnumValN(InliningAdvisorMode::Default, "default", "Heuristics-based inliner version."), clEnumValN(InliningAdvisorMode::Development, "development", "Use development mode (runtime-loadable model)."), clEnumValN(InliningAdvisorMode::Release, "release", "Use release mode (AOT-compiled model)."))); static cl::opt<bool> EnableSyntheticCounts( "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore, cl::desc("Run synthetic function entry count generation " "pass")); /// Flag to enable inline deferral during PGO. static cl::opt<bool> EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true), cl::Hidden, cl::desc("Enable inline deferral during PGO")); static cl::opt<bool> EnableMemProfiler("enable-mem-prof", cl::init(false), cl::Hidden, cl::ZeroOrMore, cl::desc("Enable memory profiler")); static cl::opt<bool> EnableModuleInliner("enable-module-inliner", cl::init(false), cl::Hidden, cl::desc("Enable module inliner")); static cl::opt<bool> PerformMandatoryInliningsFirst( "mandatory-inlining-first", cl::init(true), cl::Hidden, cl::ZeroOrMore, cl::desc("Perform mandatory inlinings module-wide, before performing " "inlining.")); static cl::opt<bool> EnableO3NonTrivialUnswitching( "enable-npm-O3-nontrivial-unswitch", cl::init(true), cl::Hidden, cl::ZeroOrMore, cl::desc("Enable non-trivial loop unswitching for -O3")); static cl::opt<bool> EnableEagerlyInvalidateAnalyses( "eagerly-invalidate-analyses", cl::init(true), cl::Hidden, cl::desc("Eagerly invalidate more analyses in default pipelines")); static cl::opt<bool> EnableNoRerunSimplificationPipeline( "enable-no-rerun-simplification-pipeline", cl::init(false), cl::Hidden, cl::desc( "Prevent running the simplification pipeline on a function more " "than once in the case that SCC mutations cause a function to be " "visited multiple times as long as the function has not been changed")); PipelineTuningOptions::PipelineTuningOptions() { LoopInterleaving = true; LoopVectorization = true; SLPVectorization = false; LoopUnrolling = true; ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; LicmMssaOptCap = SetLicmMssaOptCap; LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; CallGraphProfile = true; MergeFunctions = false; EagerlyInvalidateAnalyses = EnableEagerlyInvalidateAnalyses; } namespace llvm { extern cl::opt<unsigned> MaxDevirtIterations; extern cl::opt<bool> EnableConstraintElimination; extern cl::opt<bool> EnableFunctionSpecialization; extern cl::opt<bool> EnableGVNHoist; extern cl::opt<bool> EnableGVNSink; extern cl::opt<bool> EnableHotColdSplit; extern cl::opt<bool> EnableIROutliner; extern cl::opt<bool> EnableOrderFileInstrumentation; extern cl::opt<bool> EnableCHR; extern cl::opt<bool> EnableLoopInterchange; extern cl::opt<bool> EnableUnrollAndJam; extern cl::opt<bool> EnableLoopFlatten; extern cl::opt<bool> EnableDFAJumpThreading; extern cl::opt<bool> RunNewGVN; extern cl::opt<bool> RunPartialInlining; extern cl::opt<bool> ExtraVectorizerPasses; extern cl::opt<bool> FlattenedProfileUsed; extern cl::opt<AttributorRunOption> AttributorRun; extern cl::opt<bool> EnableKnowledgeRetention; extern cl::opt<bool> EnableMatrix; extern cl::opt<bool> DisablePreInliner; extern cl::opt<int> PreInlineThreshold; } // namespace llvm void PassBuilder::invokePeepholeEPCallbacks(FunctionPassManager &FPM, OptimizationLevel Level) { for (auto &C : PeepholeEPCallbacks) C(FPM, Level); } // Helper to add AnnotationRemarksPass. static void addAnnotationRemarksPass(ModulePassManager &MPM) { FunctionPassManager FPM; FPM.addPass(AnnotationRemarksPass()); MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); } // Helper to check if the current compilation phase is preparing for LTO static bool isLTOPreLink(ThinOrFullLTOPhase Phase) { return Phase == ThinOrFullLTOPhase::ThinLTOPreLink || Phase == ThinOrFullLTOPhase::FullLTOPreLink; } // TODO: Investigate the cost/benefit of tail call elimination on debugging. FunctionPassManager PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase) { FunctionPassManager FPM; // Form SSA out of local memory accesses after breaking apart aggregates into // scalars. FPM.addPass(SROAPass()); // Catch trivial redundancies FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); // Hoisting of scalars and load expressions. FPM.addPass(SimplifyCFGPass()); FPM.addPass(InstCombinePass()); FPM.addPass(LibCallsShrinkWrapPass()); invokePeepholeEPCallbacks(FPM, Level); FPM.addPass(SimplifyCFGPass()); // Form canonically associated expression trees, and simplify the trees using // basic mathematical properties. For example, this will form (nearly) // minimal multiplication trees. FPM.addPass(ReassociatePass()); // Add the primary loop simplification pipeline. // FIXME: Currently this is split into two loop pass pipelines because we run // some function passes in between them. These can and should be removed // and/or replaced by scheduling the loop pass equivalents in the correct // positions. But those equivalent passes aren't powerful enough yet. // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to // fully replace `SimplifyCFGPass`, and the closest to the other we have is // `LoopInstSimplify`. LoopPassManager LPM1, LPM2; // Simplify the loop body. We do this initially to clean up after other loop // passes run, either when iterating on a loop or on inner loops with // implications on the outer loop. LPM1.addPass(LoopInstSimplifyPass()); LPM1.addPass(LoopSimplifyCFGPass()); // Try to remove as much code from the loop header as possible, // to reduce amount of IR that will have to be duplicated. // TODO: Investigate promotion cap for O1. LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true, isLTOPreLink(Phase))); // TODO: Investigate promotion cap for O1. LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); LPM1.addPass(SimpleLoopUnswitchPass()); LPM2.addPass(LoopIdiomRecognizePass()); LPM2.addPass(IndVarSimplifyPass()); for (auto &C : LateLoopOptimizationsEPCallbacks) C(LPM2, Level); LPM2.addPass(LoopDeletionPass()); if (EnableLoopInterchange) LPM2.addPass(LoopInterchangePass()); // Do not enable unrolling in PreLinkThinLTO phase during sample PGO // because it changes IR to makes profile annotation in back compile // inaccurate. The normal unroller doesn't pay attention to forced full unroll // attributes so we need to make sure and allow the full unroll pass to pay // attention to it. if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt || PGOOpt->Action != PGOOptions::SampleUse) LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), /* OnlyWhenForced= */ !PTO.LoopUnrolling, PTO.ForgetAllSCEVInLoopUnroll)); for (auto &C : LoopOptimizerEndEPCallbacks) C(LPM2, Level); // We provide the opt remark emitter pass for LICM to use. We only need to do // this once as it is immutable. FPM.addPass( RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); FPM.addPass(SimplifyCFGPass()); FPM.addPass(InstCombinePass()); if (EnableLoopFlatten) FPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass())); // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA. // *All* loop passes must preserve it, in order to be able to use it. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false)); // Delete small array after loop unroll. FPM.addPass(SROAPass()); // Specially optimize memory movement as it doesn't look like dataflow in SSA. FPM.addPass(MemCpyOptPass()); // Sparse conditional constant propagation. // FIXME: It isn't clear why we do this *after* loop passes rather than // before... FPM.addPass(SCCPPass()); // Delete dead bit computations (instcombine runs after to fold away the dead // computations, and then ADCE will run later to exploit any new DCE // opportunities that creates). FPM.addPass(BDCEPass()); // Run instcombine after redundancy and dead bit elimination to exploit // opportunities opened up by them. FPM.addPass(InstCombinePass()); invokePeepholeEPCallbacks(FPM, Level); FPM.addPass(CoroElidePass()); for (auto &C : ScalarOptimizerLateEPCallbacks) C(FPM, Level); // Finally, do an expensive DCE pass to catch all the dead code exposed by // the simplifications and basic cleanup after all the simplifications. // TODO: Investigate if this is too expensive. FPM.addPass(ADCEPass()); FPM.addPass(SimplifyCFGPass()); FPM.addPass(InstCombinePass()); invokePeepholeEPCallbacks(FPM, Level); return FPM; } FunctionPassManager PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level, ThinOrFullLTOPhase Phase) { assert(Level != OptimizationLevel::O0 && "Must request optimizations!"); // The O1 pipeline has a separate pipeline creation function to simplify // construction readability. if (Level.getSpeedupLevel() == 1) return buildO1FunctionSimplificationPipeline(Level, Phase); FunctionPassManager FPM; // Form SSA out of local memory accesses after breaking apart aggregates into // scalars. FPM.addPass(SROAPass()); // Catch trivial redundancies FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); if (EnableKnowledgeRetention) FPM.addPass(AssumeSimplifyPass()); // Hoisting of scalars and load expressions. if (EnableGVNHoist) FPM.addPass(GVNHoistPass()); // Global value numbering based sinking. if (EnableGVNSink) { FPM.addPass(GVNSinkPass()); FPM.addPass(SimplifyCFGPass()); } if (EnableConstraintElimination) FPM.addPass(ConstraintEliminationPass()); // Speculative execution if the target has divergent branches; otherwise nop. FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true)); // Optimize based on known information about branches, and cleanup afterward. FPM.addPass(JumpThreadingPass()); FPM.addPass(CorrelatedValuePropagationPass()); FPM.addPass(SimplifyCFGPass()); if (Level == OptimizationLevel::O3) FPM.addPass(AggressiveInstCombinePass()); FPM.addPass(InstCombinePass()); if (!Level.isOptimizingForSize()) FPM.addPass(LibCallsShrinkWrapPass()); invokePeepholeEPCallbacks(FPM, Level); // For PGO use pipeline, try to optimize memory intrinsics such as memcpy // using the size value profile. Don't perform this when optimizing for size. if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse && !Level.isOptimizingForSize()) FPM.addPass(PGOMemOPSizeOpt()); FPM.addPass(TailCallElimPass()); FPM.addPass(SimplifyCFGPass()); // Form canonically associated expression trees, and simplify the trees using // basic mathematical properties. For example, this will form (nearly) // minimal multiplication trees. FPM.addPass(ReassociatePass()); // Add the primary loop simplification pipeline. // FIXME: Currently this is split into two loop pass pipelines because we run // some function passes in between them. These can and should be removed // and/or replaced by scheduling the loop pass equivalents in the correct // positions. But those equivalent passes aren't powerful enough yet. // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to // fully replace `SimplifyCFGPass`, and the closest to the other we have is // `LoopInstSimplify`. LoopPassManager LPM1, LPM2; // Simplify the loop body. We do this initially to clean up after other loop // passes run, either when iterating on a loop or on inner loops with // implications on the outer loop. LPM1.addPass(LoopInstSimplifyPass()); LPM1.addPass(LoopSimplifyCFGPass()); // Try to remove as much code from the loop header as possible, // to reduce amount of IR that will have to be duplicated. // TODO: Investigate promotion cap for O1. LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); // Disable header duplication in loop rotation at -Oz. LPM1.addPass(
c++
code
19,995
3,384
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /** * @brief A header for advanced hardware specific properties for OpenVINO runtime devices * To use in set_property, compile_model, import_model, get_property methods * * @file openvino/runtime/properties.hpp */ #pragma once #include <istream> #include <map> #include <string> #include <unordered_map> #include <vector> #include "ie_precision.hpp" #include "openvino/core/any.hpp" #include "openvino/core/type/element_type.hpp" #include "openvino/runtime/common.hpp" namespace ov { /** * @brief Enum to define property value mutability */ enum class PropertyMutability { RO, //!< Read-only property values can not be passed as input parameter RW, //!< Read/Write property key may change readability in runtime }; /** * @brief This class is used to return property name and its mutability attribute */ struct PropertyName : public std::string { using std::string::string; /** * @brief Constructs property name object * @param str property name * @param mutability property mutability */ PropertyName(const std::string& str, PropertyMutability mutability = PropertyMutability::RW) : std::string{str}, _mutability{mutability} {} /** * @brief check property mutability * @return true if property is mutable */ bool is_mutable() const { return _mutability == PropertyMutability::RW; } private: PropertyMutability _mutability = PropertyMutability::RW; }; /** @cond INTERNAL */ namespace util { struct PropertyTag {}; template <typename... Args> struct StringAny; template <typename T, typename... Args> struct StringAny<T, Args...> { constexpr static const bool value = std::is_convertible<T, std::pair<std::string, ov::Any>>::value && StringAny<Args...>::value; }; template <typename T> struct StringAny<T> { constexpr static const bool value = std::is_convertible<T, std::pair<std::string, ov::Any>>::value; }; template <typename T, typename... Args> using EnableIfAllStringAny = typename std::enable_if<StringAny<Args...>::value, T>::type; /** * @brief This class is used to bind property name with property type * @tparam T type of value used to pass or get property */ template <typename T, PropertyMutability mutability_ = PropertyMutability::RW> struct BaseProperty : public PropertyTag { using value_type = T; //!< Property type constexpr static const auto mutability = mutability_; //!< Property readability /** * @brief Constructs property access variable * @param str_ property name */ constexpr BaseProperty(const char* name_) : _name{name_} {} /** * @brief return property name * @return Pointer to const string key representation */ const char* name() const { return _name; } /** * @brief compares property name * @return true if string is the same */ bool operator==(const std::string& str) const { return _name == str; } /** * @brief compares property name * @return true if string is the same */ friend bool operator==(const std::string& str, const BaseProperty<T, mutability_>& property) { return property == str; } private: const char* _name = nullptr; }; template <typename T, PropertyMutability M> inline std::ostream& operator<<(std::ostream& os, const BaseProperty<T, M>& property) { return os << property.name(); } } // namespace util /** @endcond */ /** * @brief This class is used to bind property name with value type * @tparam T type of value used to set or get property */ template <typename T, PropertyMutability mutability_ = PropertyMutability::RW> class Property : public util::BaseProperty<T, mutability_> { template <typename V> struct Forward { template <typename U, typename std::enable_if<std::is_same<U, const std::string&>::value && std::is_convertible<V, std::string>::value, bool>::type = true> explicit operator U() { return value; } template <typename U, typename std::enable_if<std::is_same<U, const std::string&>::value && !std::is_convertible<V, std::string>::value, bool>::type = true> explicit operator U() { return Any{value}.as<std::string>(); } template <typename U, typename std::enable_if<!std::is_same<U, const std::string&>::value && std::is_convertible<V, std::string>::value, bool>::type = true> explicit operator U() { return Any{value}.as<U>(); } template <typename U, typename std::enable_if<!std::is_same<U, const std::string&>::value && !std::is_convertible<V, std::string>::value, bool>::type = true> explicit operator U() { return value; } V&& value; }; public: using util::BaseProperty<T, mutability_>::BaseProperty; /** * @brief Constructs property * @tparam Args property constructor arguments types * @param args property constructor arguments * @return Pair of name and type erased value. */ template <typename... Args> inline std::pair<std::string, Any> operator()(Args&&... args) const { return {this->name(), Any::make<T>(Forward<Args>{std::forward<Args>(args)}...)}; } }; /** * @brief This class is used to bind read-only property name with value type * @tparam T type of value used to pass or get property */ template <typename T> struct Property<T, PropertyMutability::RO> : public util::BaseProperty<T, PropertyMutability::RO> { using util::BaseProperty<T, PropertyMutability::RO>::BaseProperty; }; /** * @brief Read-only property to get a std::vector<PropertyName> of supported read-only properties. * * This can be used as a compiled model property as well. * */ static constexpr Property<std::vector<PropertyName>, PropertyMutability::RO> supported_properties{ "SUPPORTED_PROPERTIES"}; /** * @brief Read-only property to get a std::vector<std::string> of available device IDs */ static constexpr Property<std::vector<std::string>, PropertyMutability::RO> available_devices{"AVAILABLE_DEVICES"}; /** * @brief Read-only property to get a name of name of a model */ static constexpr Property<std::string, PropertyMutability::RO> model_name{"NETWORK_NAME"}; /** * @brief Read-only property to get an unsigned integer value of optimal number of compiled model infer requests. */ static constexpr Property<uint32_t, PropertyMutability::RO> optimal_number_of_infer_requests{ "OPTIMAL_NUMBER_OF_INFER_REQUESTS"}; namespace hint { /** * @brief Hint for device to use specified precision for inference */ static constexpr Property<element::Type, PropertyMutability::RW> inference_precision{"INFERENCE_PRECISION_HINT"}; /** * @brief Enum to define possible priorities hints */ enum class Priority { LOW = 0, MEDIUM = 1, HIGH = 2, DEFAULT = MEDIUM, }; /** @cond INTERNAL */ inline std::ostream& operator<<(std::ostream& os, const Priority& priority) { switch (priority) { case Priority::LOW: return os << "LOW"; case Priority::MEDIUM: return os << "MEDIUM"; case Priority::HIGH: return os << "HIGH"; default: throw ov::Exception{"Unsupported performance measure hint"}; } } inline std::istream& operator>>(std::istream& is, Priority& priority) { std::string str; is >> str; if (str == "LOW") { priority = Priority::LOW; } else if (str == "MEDIUM") { priority = Priority::MEDIUM; } else if (str == "HIGH") { priority = Priority::HIGH; } else { throw ov::Exception{"Unsupported model priority: " + str}; } return is; } /** @endcond */ /** * @brief High-level OpenVINO model priority hint * Defines what model should be provided with more performant bounded resource first */ static constexpr Property<Priority> model_priority{"MODEL_PRIORITY"}; /** * @brief Enum to define possible performance mode hints */ enum class PerformanceMode { UNDEFINED = -1, LATENCY = 1, THROUGHPUT = 2, }; /** @cond INTERNAL */ inline std::ostream& operator<<(std::ostream& os, const PerformanceMode& performance_mode) { switch (performance_mode) { case PerformanceMode::UNDEFINED: return os << ""; case PerformanceMode::LATENCY: return os << "LATENCY"; case PerformanceMode::THROUGHPUT: return os << "THROUGHPUT"; default: throw ov::Exception{"Unsupported performance mode hint"}; } } inline std::istream& operator>>(std::istream& is, PerformanceMode& performance_mode) { std::string str; is >> str; if (str == "LATENCY") { performance_mode = PerformanceMode::LATENCY; } else if (str == "THROUGHPUT") { performance_mode = PerformanceMode::THROUGHPUT; } else if (str == "") { performance_mode = PerformanceMode::UNDEFINED; } else { throw ov::Exception{"Unsupported performance mode: " + str}; } return is; } /** @endcond */ /** * @brief High-level OpenVINO Performance Hints * unlike low-level properties that are individual (per-device), the hints are something that every device accepts * and turns into device-specific settings */ static constexpr Property<PerformanceMode> performance_mode{"PERFORMANCE_HINT"}; /** * @brief (Optional) property that backs the (above) Performance Hints * by giving additional information on how many inference requests the application will be keeping in flight * usually this value comes from the actual use-case (e.g. number of video-cameras, or other sources of inputs) */ static constexpr Property<uint32_t> num_requests{"PERFORMANCE_HINT_NUM_REQUESTS"}; /** * @brief This key identifies shared pointer to the ov::Model, required for some properties (ov::max_batch_size and * ov::optimal_batch_size) */ static constexpr Property<std::shared_ptr<ov::Model>> model{"MODEL_PTR"}; /** * @brief Special key for auto batching feature configuration. Enabled by default */ static constexpr Property<bool, PropertyMutability::RW> allow_auto_batching{"ALLOW_AUTO_BATCHING"}; } // namespace hint /** * @brief The name for setting performance counters option. * * It is passed to Core::set_property() */ static constexpr Property<bool> enable_profiling{"PERF_COUNT"}; namespace log { /** * @brief Enum to define possible log levels */ enum class Level { NO = -1, //!< disable any logging ERR = 0, //!< error events that might still allow the application to continue running WARNING = 1, //!< potentially harmful situations which may further lead to ERROR INFO = 2, //!< informational messages that display the progress of the application at coarse-grained level DEBUG = 3, //!< fine-grained events that are most useful to debug an application. TRACE = 4, //!< finer-grained informational events than the DEBUG }; /** @cond INTERNAL */ inline std::ostream& operator<<(std::ostream& os, const Level& level) { switch (level) { case Level::NO: return os << "LOG_NONE"; case Level::ERR: return os << "LOG_ERROR"; case Level::WARNING: return os << "LOG_WARNING"; case Level::INFO: return os << "LOG_INFO"; case Level::DEBUG: return os << "LOG_DEBUG"; case Level::TRACE: return os << "LOG_TRACE"; default: throw ov::Exception{"Unsupported log level"}; } } inline std::istream& operator>>(std::istream& is, Level& level) { std::string str; is >> str; if (str == "LOG_NONE") { level = Level::NO; } else if (str == "LOG_ERROR") { level = Level::ERR; } else if (str == "LOG_WARNING") { level = Level::WARNING; } else if (str == "LOG_INFO") { level = Level::INFO; } else if (str == "LOG_DEBUG") { level = Level::DEBUG; } else if (str == "LOG_TRACE") { level = Level::TRACE; } else { throw ov::Exception{"Unsupported log level: " + str}; } return is; } /** @endcond */ /** * @brief the property for setting desirable log level. */ static constexpr Property<Level> level{"LOG_LEVEL"}; } // namespace log /** * @brief This property defines the directory which will be used to store any data cached by plugins. * * The underlying cache structure is not defined and might differ between OpenVINO releases * Cached data might be platform / device specific and might be invalid after OpenVINO version change * If this property is not specified or value is empty string, then caching is disabled. * The property might enable caching for the plugin using the following code: * * @code * ie.set_property("GPU", ov::cache_dir("cache/")); // enables cache for GPU plugin * @endcode * * The following code enables caching of compiled network blobs for devices where import/export is supported * * @code * ie.set_property(ov::cache_dir("cache/")); // enables models cache * @endcode */ static constexpr Property<std::string> cache_dir{"CACHE_DIR"}; /** * @brief Read-only property to provide information about a range for streams on platforms where streams are supported. * * Property returns a value of std::tuple<unsigned int, unsigned int> type, where: * - First value is bottom bound. * - Second value is upper bound. */ static constexpr Property<std::tuple<unsigned int, unsigned int>, PropertyMutability::RO> range_for_streams{ "RANGE_FOR_STREAMS"}; /** * @brief Read-only property to query information optimal batch size for the given device and the network * * Property returns a value of unsigned int type, * Returns optimal batch size for a given network on the given device. The returned value is aligned to power of 2. * Also, ov::hint::model is the required option for this metric since the optimal batch size depends on the model, * so if the ov::hint::model is not given, the result of the metric is always 1. * For the GPU the metric is queried automatically whenever the OpenVINO performance hint for the throughput is used, * so that the result (>1) governs the automatic batching (transparently to the application). * The automatic batching can be disabled with ALLOW_AUTO_BATCHING set to NO */ static constexpr Property<unsigned int, PropertyMutability::RO> optimal_batch_size{"OPTIMAL_BATCH_SIZE"}; /** * @brief Read-only property to get maximum batch size which does not cause performance degradation due to memory swap * impact. */ static constexpr Property<uint32_t, PropertyMutability::RO> max_batch_size{"MAX_BATCH_SIZE"}; /** * @brief Read-only property to provide a hint for a range for number of async infer requests. If device supports * streams, the metric provides range for number of IRs per stream. * * Property returns a value of std::tuple<unsigned int, unsigned int, unsigned int> type, where: * - First value is bottom bound. * - Second value is upper bound. * - Third value is step inside this range. */ static constexpr Property<std::tuple<unsigned int, unsigned int, unsigned int>, PropertyMutability::RO> range_for_async_infer_requests{"RANGE_FOR_ASYNC_INFER_REQUESTS"}; namespace device { /** * @brief the property for setting of required device to execute on * values: device id starts from "0" - first device, "1" - second device, etc */ static constexpr Property<std::string> id{"DEVICE_ID"}; /** * @brief Type for device Priorities config option, with comma-separated devices listed in the desired priority */ struct Priorities : public Property<std::string> { private: template <typename H, typename... T> static inline std::string concat(const H& head, T&&... tail) { return head + std::string{','} + concat(std::forward<T>(tail)...); } template <typename H> static inline std::string concat(const H& head) { return head; } public: using Property<std::string>::Property; /** * @brief Constructs device priorities * @tparam Args property constructor arguments types * @param args property constructor arguments * @return Pair of name and type erased value. */ template <typename... Args> inline std::pair<std::string, Any> operator()(Args&&... args) const { return {name(), Any{concat(std::forward<Args>(args)...)}}; } }; /** * @brief Device Priorities config option, with comma-separated devices listed in the desired priority */ static constexpr Priorities priorities{"MULTI_DEVICE_PRIORITIES"}; /** * @brief Type for property to pass set of properties to specified device */ struct Properties { /** * @brief Constructs property * @param device_name device plugin alias * @param config set of property values with names * @return Pair of string key representation and type erased property value. */ inline std::pair<std::string, Any> operator()(const std::string& device_name, const AnyMap& config) const { return {device_name, config}; } /** * @brief Constructs property * @tparam Properties Should be the pack of `std::pair<std::string, ov::Any>` types * @param device_name device plugin alias * @param configs Optional pack of pairs: (config parameter name, config parameter value) * @return Pair of string key representation and type erased property value. */ template <typename... Properties> inline util::EnableIfAllStringAny<std::pair<std::string, Any>, Properties...> operator()( const std::string& device_name, Properties&&... configs) const { return {device_name, AnyMap{std::pair<std::string, Any>{configs}...}}; } }; /** * @brief Property to pass set of property values to specified device * Usage Example: * @code * core.compile_model("HETERO" * ov::device::priorities("GPU", "CPU"), * ov::device::properties("CPU", ov::enable_profiling(true)), * ov::device::properties("GPU", ov::enable_profiling(false))); * @endcode */ static constexpr Properties properties; /** * @brief Read-only property to get a std::string value representing a full device name. */ static constexpr Property<std::string, PropertyMutability::RO> full_name{"FULL_DEVICE_NAME"}; /** * @brief Read-only property which defines the device architecture. */ static constexpr Property<std::string, PropertyMutability::RO> architecture{"DEVICE_ARCHITECTURE"}; /** * @brief Enum to define possible device types */ enum class Type { INTEGRATED = 0, //!< Device is integrated into host system DISCRETE = 1, //!< Device is not integrated into host system }; /** @cond INTERNAL */ inline std::ostream& operator<<(std::ostream& os, const Type& device_type) { switch (device_type) { case Type::DISCRETE: return os << "discrete"; case Type::INTEGRATED: return os << "integrated"; default: throw ov::Exception{"Unsupported device type"}; } } inline std::istream& operator>>(std::istream& is, Type& device_type) { std::string str; is >> str; if (str == "discrete") { device_type = Type::DISCRETE; } else if (str == "integrated") { device_type = Type::INTEGRATED; } else { throw ov::Exception{"Unsupported device type: " + str}; } return is; } /** @endcond */ /** * @brief Read-only property to get a type of device. See Type enum definition for possible return values */ static constexpr Property<Type, PropertyMutability::RO> type{"DEVICE_TYPE"};
c++
code
19,999
4,481
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/prefs/chrome_pref_service_factory.h" #include "base/bind.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/metrics/histogram.h" #include "base/prefs/default_pref_store.h" #include "base/prefs/json_pref_store.h" #include "base/prefs/pref_notifier_impl.h" #include "base/prefs/pref_registry.h" #include "base/prefs/pref_service.h" #include "base/prefs/pref_value_store.h" #include "chrome/browser/policy/configuration_policy_pref_store.h" #include "chrome/browser/prefs/command_line_pref_store.h" #include "chrome/browser/prefs/pref_model_associator.h" #include "chrome/browser/prefs/pref_registry_syncable.h" #include "chrome/browser/prefs/pref_service_syncable_builder.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/profile_error_dialog.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" using content::BrowserContext; using content::BrowserThread; namespace { // Shows notifications which correspond to PersistentPrefStore's reading errors. void HandleReadError(PersistentPrefStore::PrefReadError error) { if (error != PersistentPrefStore::PREF_READ_ERROR_NONE) { // Failing to load prefs on startup is a bad thing(TM). See bug 38352 for // an example problem that this can cause. // Do some diagnosis and try to avoid losing data. int message_id = 0; if (error <= PersistentPrefStore::PREF_READ_ERROR_JSON_TYPE) { message_id = IDS_PREFERENCES_CORRUPT_ERROR; } else if (error != PersistentPrefStore::PREF_READ_ERROR_NO_FILE) { message_id = IDS_PREFERENCES_UNREADABLE_ERROR; } if (message_id) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&ShowProfileErrorDialog, message_id)); } UMA_HISTOGRAM_ENUMERATION("PrefService.ReadError", error, PersistentPrefStore::PREF_READ_ERROR_MAX_ENUM); } } void PrepareBuilder( PrefServiceSyncableBuilder* builder, const base::FilePath& pref_filename, base::SequencedTaskRunner* pref_io_task_runner, policy::PolicyService* policy_service, const scoped_refptr<PrefStore>& extension_prefs, bool async) { #if defined(OS_LINUX) // We'd like to see what fraction of our users have the preferences // stored on a network file system, as we've had no end of troubles // with NFS/AFS. // TODO(evanm): remove this once we've collected state. file_util::FileSystemType fstype; if (file_util::GetFileSystemType(pref_filename.DirName(), &fstype)) { UMA_HISTOGRAM_ENUMERATION("PrefService.FileSystemType", static_cast<int>(fstype), file_util::FILE_SYSTEM_TYPE_COUNT); } #endif #if defined(ENABLE_CONFIGURATION_POLICY) using policy::ConfigurationPolicyPrefStore; builder->WithManagedPrefs( ConfigurationPolicyPrefStore::CreateMandatoryPolicyPrefStore( policy_service)); builder->WithRecommendedPrefs( ConfigurationPolicyPrefStore::CreateRecommendedPolicyPrefStore( policy_service)); #endif // ENABLE_CONFIGURATION_POLICY builder->WithAsync(async); builder->WithExtensionPrefs(extension_prefs); builder->WithCommandLinePrefs( new CommandLinePrefStore(CommandLine::ForCurrentProcess())); builder->WithReadErrorCallback(base::Bind(&HandleReadError)); builder->WithUserPrefs(new JsonPrefStore(pref_filename, pref_io_task_runner)); } } // namespace // TODO(joi): Find a better home for this. PrefService* PrefServiceFromBrowserContext(BrowserContext* context) { return static_cast<Profile*>(context)->GetPrefs(); } namespace chrome_prefs { PrefService* CreateLocalState( const base::FilePath& pref_filename, base::SequencedTaskRunner* pref_io_task_runner, policy::PolicyService* policy_service, const scoped_refptr<PrefStore>& extension_prefs, const scoped_refptr<PrefRegistry>& pref_registry, bool async) { PrefServiceSyncableBuilder builder; PrepareBuilder(&builder, pref_filename, pref_io_task_runner, policy_service, extension_prefs, async); return builder.Create(pref_registry); } PrefServiceSyncable* CreateProfilePrefs( const base::FilePath& pref_filename, base::SequencedTaskRunner* pref_io_task_runner, policy::PolicyService* policy_service, const scoped_refptr<PrefStore>& extension_prefs, const scoped_refptr<PrefRegistrySyncable>& pref_registry, bool async) { PrefServiceSyncableBuilder builder; PrepareBuilder(&builder, pref_filename, pref_io_task_runner, policy_service, extension_prefs, async); return builder.CreateSyncable(pref_registry); } } // namespace chrome_prefs
c++
code
5,129
760
#include <iostream> #include <pulse/pulseaudio.h> #include <pulse/simple.h> #include <pulse/sample.h> int main(int argc, char **argv) { std::cout << "Hello World!"; pa_simple *s; pa_sample_spec ss; ss.format = PA_SAMPLE_S16NE; ss.channels = 2; ss.rate = 44100; s = pa_simple_new(NULL, "PluMP", PA_STREAM_PLAYBACK, NULL, "Music", &ss, NULL, NULL, NULL); if( s == NULL ) { printf("Error : Failed \n"); return -1; } printf("Success\n"); return 0; }
c++
code
525
131
/**************************************************************************** * * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include <QNetworkAccessManager> #include <QNetworkRequest> #include "MapProvider.h" MapProvider::MapProvider(const QString &referrer, const QString &imageFormat, const quint32 averageSize, const QGeoMapType::MapStyle mapType, QObject* parent) : QObject(parent) , _referrer(referrer) , _imageFormat(imageFormat) , _averageSize(averageSize) , _mapType(mapType) { const QStringList langs = QLocale::system().uiLanguages(); if (langs.length() > 0) { _language = langs[0]; } } QNetworkRequest MapProvider::getTileURL(const int x, const int y, const int zoom, QNetworkAccessManager* networkManager) { //-- Build URL QNetworkRequest request; const QString url = _getURL(x, y, zoom, networkManager); if (url.isEmpty()) { return request; } request.setUrl(QUrl(url)); request.setRawHeader(QByteArrayLiteral("Accept"), QByteArrayLiteral("*/*")); request.setRawHeader(QByteArrayLiteral("Referrer"), _referrer.toUtf8()); request.setRawHeader(QByteArrayLiteral("User-Agent"), _userAgent); return request; } QString MapProvider::getImageFormat(const QByteArray& image) const { QString format; if (image.size() > 2) { if (image.startsWith(reinterpret_cast<const char*>(pngSignature))) format = QStringLiteral("png"); else if (image.startsWith(reinterpret_cast<const char*>(jpegSignature))) format = QStringLiteral("jpg"); else if (image.startsWith(reinterpret_cast<const char*>(gifSignature))) format = QStringLiteral("gif"); else { return _imageFormat; } } return format; } QString MapProvider::_tileXYToQuadKey(const int tileX, const int tileY, const int levelOfDetail) const { QString quadKey; for (int i = levelOfDetail; i > 0; i--) { char digit = '0'; const int mask = 1 << (i - 1); if ((tileX & mask) != 0) { digit++; } if ((tileY & mask) != 0) { digit++; digit++; } quadKey.append(digit); } return quadKey; } int MapProvider::_getServerNum(const int x, const int y, const int max) const { return (x + 2 * y) % max; } int MapProvider::long2tileX(const double lon, const int z) const { return static_cast<int>(floor((lon + 180.0) / 360.0 * pow(2.0, z))); } //----------------------------------------------------------------------------- int MapProvider::lat2tileY(const double lat, const int z) const { return static_cast<int>(floor( (1.0 - log(tan(lat * M_PI / 180.0) + 1.0 / cos(lat * M_PI / 180.0)) / M_PI) / 2.0 * pow(2.0, z))); } bool MapProvider::_isElevationProvider() const { return false; } QGCTileSet MapProvider::getTileCount(const int zoom, const double topleftLon, const double topleftLat, const double bottomRightLon, const double bottomRightLat) const { QGCTileSet set; set.tileX0 = long2tileX(topleftLon, zoom); set.tileY0 = lat2tileY(topleftLat, zoom); set.tileX1 = long2tileX(bottomRightLon, zoom); set.tileY1 = lat2tileY(bottomRightLat, zoom); set.tileCount = (static_cast<quint64>(set.tileX1) - static_cast<quint64>(set.tileX0) + 1) * (static_cast<quint64>(set.tileY1) - static_cast<quint64>(set.tileY0) + 1); set.tileSize = getAverageSize() * set.tileCount; return set; }
c++
code
3,890
984
// This file is part of BOINC. // http://boinc.berkeley.edu // Copyright (C) 2008 University of California // // BOINC is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // BOINC is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with BOINC. If not, see <http://www.gnu.org/licenses/>. #include "cpp.h" #ifdef _WIN32 #include "boinc_win.h" #else #include "config.h" #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <grp.h> #endif #ifdef _MSC_VER #define snprintf _snprintf #endif #include "error_numbers.h" #include "file_names.h" #include "util.h" #include "str_util.h" #include "str_replace.h" #include "filesys.h" #include "parse.h" #include "client_msgs.h" #include "client_state.h" #include "sandbox.h" bool g_use_sandbox = false; #ifndef _WIN32 // POSIX requires that shells run from an application will use the // real UID and GID if different from the effective UID and GID. // Mac OS 10.4 did not enforce this, but OS 10.5 does. Since // system() invokes a shell, we can't use it to run the switcher // or setprojectgrp utilities, so we must do a fork() and execv(). // int switcher_exec(const char *util_filename, const char* cmdline) { char* argv[100]; char util_path[MAXPATHLEN]; char command [1024]; char buffer[1024]; int fds_out[2], fds_err[2]; int stat; int retval; string output_out, output_err; snprintf(util_path, sizeof(util_path), "%s/%s", SWITCHER_DIR, util_filename); argv[0] = const_cast<char*>(util_filename); // Make a copy of cmdline because parse_command_line modifies it safe_strcpy(command, cmdline); parse_command_line(const_cast<char*>(cmdline), argv+1); // Create the output pipes if (pipe(fds_out) == -1) { perror("pipe() for fds_out failed in switcher_exec"); return ERR_PIPE; } if (pipe(fds_err) == -1) { perror("pipe() for fds_err failed in switcher_exec"); return ERR_PIPE; } int pid = fork(); if (pid == -1) { perror("fork() failed in switcher_exec"); return ERR_FORK; } if (pid == 0) { // This is the new (forked) process // Setup pipe redirects while ((dup2(fds_out[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {} while ((dup2(fds_err[1], STDERR_FILENO) == -1) && (errno == EINTR)) {} // Child only needs one-way (write) pipes so close read pipes close(fds_out[0]); close(fds_err[0]); execv(util_path, argv); fprintf(stderr, "execv failed in switcher_exec(%s, %s): %s", util_path, cmdline, strerror(errno)); _exit(EXIT_FAILURE); } // Parent only needs one-way (read) pipes so close write pipes close(fds_out[1]); close(fds_err[1]); // Capture stdout output while (1) { ssize_t count = read(fds_out[0], buffer, sizeof(buffer)); if (count == -1) { if (errno == EINTR) { continue; } else { break; } } else if (count == 0) { break; } else { buffer[count] = '\0'; output_out += buffer; } } // Capture stderr output while (1) { ssize_t count = read(fds_err[0], buffer, sizeof(buffer)); if (count == -1) { if (errno == EINTR) { continue; } else { break; } } else if (count == 0) { break; } else { buffer[count] = '\0'; output_err += buffer; } } // Wait for command to complete, like system() does. waitpid(pid, &stat, 0); // Close pipe descriptors close(fds_out[0]); close(fds_err[0]); if (WIFEXITED(stat)) { retval = WEXITSTATUS(stat); if (retval) { if (log_flags.task_debug) { msg_printf(0, MSG_INTERNAL_ERROR, "[task_debug] failure in switcher_exec"); msg_printf(0, MSG_INTERNAL_ERROR, "[task_debug] switcher: %s", util_path); msg_printf(0, MSG_INTERNAL_ERROR, "[task_debug] command: %s", command); msg_printf(0, MSG_INTERNAL_ERROR, "[task_debug] exit code: %d", retval); msg_printf(0, MSG_INTERNAL_ERROR, "[task_debug] stdout: %s", output_out.c_str()); msg_printf(0, MSG_INTERNAL_ERROR, "[task_debug] stderr: %s", output_err.c_str()); } } return retval; } return 0; } int kill_via_switcher(int pid) { char cmd[1024]; if (!g_use_sandbox) return 0; // if project application is running as user boinc_project and // client is running as user boinc_master, // we cannot send a signal directly, so use switcher. // snprintf(cmd, sizeof(cmd), "/bin/kill kill -s KILL %d", pid); return switcher_exec(SWITCHER_FILE_NAME, cmd); } #ifndef _DEBUG static int lookup_group(const char* name, gid_t& gid) { struct group* gp = getgrnam(name); if (!gp) return ERR_GETGRNAM; gid = gp->gr_gid; return 0; } #endif int remove_project_owned_file_or_dir(const char* path) { char cmd[1024]; if (g_use_sandbox) { snprintf(cmd, sizeof(cmd), "/bin/rm rm -fR \"%s\"", path); if (switcher_exec(SWITCHER_FILE_NAME, cmd)) { return ERR_UNLINK; } else { return 0; } } return ERR_UNLINK; } int get_project_gid() { if (g_use_sandbox) { #ifdef _DEBUG // GDB can't attach to applications which are running as a different user // or group, so fix up data with current user and group during debugging gstate.boinc_project_gid = getegid(); #else return lookup_group(BOINC_PROJECT_GROUP_NAME, gstate.boinc_project_gid); #endif // _DEBUG } else { gstate.boinc_project_gid = 0; } return 0; } int set_to_project_group(const char* path) { if (g_use_sandbox) { if (switcher_exec(SETPROJECTGRP_FILE_NAME, path)) { return ERR_CHOWN; } } return 0; } #else int get_project_gid() { return 0; } int set_to_project_group(const char*) { return 0; } #endif // ! _WIN32 // delete a file. // return success if we deleted it or it didn't exist in the first place // static int delete_project_owned_file_aux(const char* path) { #ifdef _WIN32 if (DeleteFile(path)) return 0; int error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND) { return 0; } if (error == ERROR_ACCESS_DENIED) { SetFileAttributes(path, FILE_ATTRIBUTE_NORMAL); if (DeleteFile(path)) return 0; } return error; #else int retval = unlink(path); if (retval == 0) return 0; if (errno == ENOENT) { return 0; } if (g_use_sandbox && (errno == EACCES)) { // We may not have permission to read subdirectories created by projects // return remove_project_owned_file_or_dir(path); } return ERR_UNLINK; #endif } // Delete the file located at path. // If "retry" is set, do retries for 5 sec in case some // other program (e.g. virus checker) has the file locked. // Don't do this if deleting directories - it can lock up the Manager. // int delete_project_owned_file(const char* path, bool retry) { int retval = 0; retval = delete_project_owned_file_aux(path); if (retval && retry) { if (log_flags.slot_debug) { msg_printf(0, MSG_INFO, "[slot] delete of %s failed (%d); retrying", path, retval ); } double start = dtime(); do { boinc_sleep(drand()*2); // avoid lockstep retval = delete_project_owned_file_aux(path); if (!retval) break; } while (dtime() < start + FILE_RETRY_INTERVAL); } if (retval) { if (log_flags.slot_debug) { msg_printf(0, MSG_INFO, "[slot] failed to remove file %s: %s", path, boincerror(retval) ); } safe_strcpy(boinc_failed_file, path); return ERR_UNLINK; } if (log_flags.slot_debug) { msg_printf(0, MSG_INFO, "[slot] removed file %s", path); } return 0; } // recursively delete everything in the specified directory // (but not the directory itself). // If an error occurs, delete as much as possible. // int client_clean_out_dir( const char* dirpath, const char* reason, const char* except ) { char filename[MAXPATHLEN], path[MAXPATHLEN]; int retval, final_retval = 0; DIRREF dirp; if (reason && log_flags.slot_debug) { msg_printf(0, MSG_INFO, "[slot] cleaning out %s: %s", dirpath, reason); } dirp = dir_open(dirpath); if (!dirp) { #ifndef _WIN32 if (g_use_sandbox && (errno == EACCES)) { // dir may be owned by boinc_apps return remove_project_owned_file_or_dir(dirpath); } #endif return 0; // if dir doesn't exist, it's empty } while (1) { safe_strcpy(filename, ""); retval = dir_scan(filename, dirp, sizeof(filename)); if (retval) { if (retval != ERR_NOT_FOUND) { if (log_flags.slot_debug) { msg_printf(0, MSG_INFO, "[slot] dir_scan(%s) failed: %s", dirpath, boincerror(retval) ); } final_retval = retval; } break; } if (except && !strcmp(except, filename)) { continue; } snprintf(path, sizeof(path), "%s/%s", dirpath, filename); if (is_dir(path)) { retval = client_clean_out_dir(path, NULL); if (retval) final_retval = retval; retval = remove_project_owned_dir(path); if (retval) final_retval = retval; } else { retval = delete_project_owned_file(path, false); if (retval) final_retval = retval; } } dir_close(dirp); return final_retval; } int remove_project_owned_dir(const char* name) { #ifdef _WIN32 if (!RemoveDirectory(name)) { return GetLastError(); } return 0; #else int retval; retval = rmdir(name); // We may not have permission to read subdirectories created by projects if (retval && g_use_sandbox && (errno == EACCES)) { retval = remove_project_owned_file_or_dir(name); } return retval; #endif }
c++
code
11,006
2,312
// // main.cpp // domain-server/src // // Created by Philip Rosedale on 11/20/12. // Copyright 2012 High Fidelity, Inc. // // The Domain Server keeps a list of nodes that have connected to it, and echoes that list of // nodes out to nodes when they check in. // // The connection is stateless... the domain server will set you inactive if it does not hear from // you in LOGOFF_CHECK_INTERVAL milliseconds, meaning your info will not be sent to other users. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <QtCore/QCoreApplication> #include <LogHandler.h> #include <SharedUtil.h> #include "DomainServer.h" int main(int argc, char* argv[]) { #ifndef WIN32 setvbuf(stdout, NULL, _IOLBF, 0); #endif int currentExitCode = 0; // use a do-while to handle domain-server restart do { DomainServer domainServer(argc, argv); currentExitCode = domainServer.exec(); } while (currentExitCode == DomainServer::EXIT_CODE_REBOOT); return currentExitCode; }
c++
code
1,107
208
#include "ModelLoader.h" #include <fstream> #include <iostream> #include <vector> #include "glm/glm.hpp" namespace Core { std::vector<Quad> Core::ModelLoader::Load(const std::string& filePath) { // Open file. std::fstream file; file.open(filePath.c_str()); // Check if file is succesfully opened. if (!file.is_open()) std::cout << "File not found - " << filePath; // Write words to string vector. std::string word; std::vector<std::string> words; while (file >> word) words.push_back(word); file.close(); // Create quads and convert string to float. std::vector<Quad> quads; for (size_t i = 0; i < words.size(); i += 16) { glm::vec3 vert1 = { std::stof(words[i]), std::stof(words[i + 1]), std::stof(words[i + 2]), }; glm::vec3 vert2 = { std::stof(words[i + 3]), std::stof(words[i + 4]), std::stof(words[i + 5]), }; glm::vec3 vert3 = { std::stof(words[i + 6]), std::stof(words[i + 7]), std::stof(words[i + 8]), }; glm::vec3 vert4 = { std::stof(words[i + 9]), std::stof(words[i + 10]), std::stof(words[i + 11]), }; glm::vec4 color = { std::stof(words[i + 12]), std::stof(words[i + 13]), std::stof(words[i + 14]), std::stof(words[i + 15]), }; quads.push_back(Quad({vert1, vert2, vert3, vert4}, color)); } return quads; } }
c++
code
1,389
467
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quic/core/quic_crypto_handshaker.h" #include "quic/core/quic_session.h" namespace quic { #define ENDPOINT \ (session()->perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ") QuicCryptoHandshaker::QuicCryptoHandshaker(QuicCryptoStream* stream, QuicSession* session) : stream_(stream), session_(session), last_sent_handshake_message_tag_(0) { crypto_framer_.set_visitor(this); } QuicCryptoHandshaker::~QuicCryptoHandshaker() {} void QuicCryptoHandshaker::SendHandshakeMessage( const CryptoHandshakeMessage& message, EncryptionLevel level) { QUIC_DVLOG(1) << ENDPOINT << "Sending " << message.DebugString(); session()->NeuterUnencryptedData(); session()->OnCryptoHandshakeMessageSent(message); last_sent_handshake_message_tag_ = message.tag(); const QuicData& data = message.GetSerialized(); stream_->WriteCryptoData(level, data.AsStringPiece()); } void QuicCryptoHandshaker::OnError(CryptoFramer* framer) { QUIC_DLOG(WARNING) << "Error processing crypto data: " << QuicErrorCodeToString(framer->error()); } void QuicCryptoHandshaker::OnHandshakeMessage( const CryptoHandshakeMessage& message) { QUIC_DVLOG(1) << ENDPOINT << "Received " << message.DebugString(); session()->OnCryptoHandshakeMessageReceived(message); } CryptoMessageParser* QuicCryptoHandshaker::crypto_message_parser() { return &crypto_framer_; } size_t QuicCryptoHandshaker::BufferSizeLimitForLevel(EncryptionLevel) const { return GetQuicFlag(FLAGS_quic_max_buffered_crypto_bytes); } #undef ENDPOINT // undef for jumbo builds } // namespace quic
c++
code
1,822
334
/* Generated file - do not edit! */ #include "minter/bip39/wordlist.h" static const unsigned char es_[] = { 0x61, 0xcc, 0x81, 0x62, 0x61, 0x63, 0x6f, 0, 0x61, 0x62, 0x64, 0x6f, 0x6d, 0x65, 0x6e, 0, 0x61, 0x62, 0x65, 0x6a, 0x61, 0, 0x61, 0x62, 0x69, 0x65, 0x72, 0x74, 0x6f, 0, 0x61, 0x62, 0x6f, 0x67, 0x61, 0x64, 0x6f, 0, 0x61, 0x62, 0x6f, 0x6e, 0x6f, 0, 0x61, 0x62, 0x6f, 0x72, 0x74, 0x6f, 0, 0x61, 0x62, 0x72, 0x61, 0x7a, 0x6f, 0, 0x61, 0x62, 0x72, 0x69, 0x72, 0, 0x61, 0x62, 0x75, 0x65, 0x6c, 0x6f, 0, 0x61, 0x62, 0x75, 0x73, 0x6f, 0, 0x61, 0x63, 0x61, 0x62, 0x61, 0x72, 0, 0x61, 0x63, 0x61, 0x64, 0x65, 0x6d, 0x69, 0x61, 0, 0x61, 0x63, 0x63, 0x65, 0x73, 0x6f, 0, 0x61, 0x63, 0x63, 0x69, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x61, 0x63, 0x65, 0x69, 0x74, 0x65, 0, 0x61, 0x63, 0x65, 0x6c, 0x67, 0x61, 0, 0x61, 0x63, 0x65, 0x6e, 0x74, 0x6f, 0, 0x61, 0x63, 0x65, 0x70, 0x74, 0x61, 0x72, 0, 0x61, 0xcc, 0x81, 0x63, 0x69, 0x64, 0x6f, 0, 0x61, 0x63, 0x6c, 0x61, 0x72, 0x61, 0x72, 0, 0x61, 0x63, 0x6e, 0x65, 0xcc, 0x81, 0, 0x61, 0x63, 0x6f, 0x67, 0x65, 0x72, 0, 0x61, 0x63, 0x6f, 0x73, 0x6f, 0, 0x61, 0x63, 0x74, 0x69, 0x76, 0x6f, 0, 0x61, 0x63, 0x74, 0x6f, 0, 0x61, 0x63, 0x74, 0x72, 0x69, 0x7a, 0, 0x61, 0x63, 0x74, 0x75, 0x61, 0x72, 0, 0x61, 0x63, 0x75, 0x64, 0x69, 0x72, 0, 0x61, 0x63, 0x75, 0x65, 0x72, 0x64, 0x6f, 0, 0x61, 0x63, 0x75, 0x73, 0x61, 0x72, 0, 0x61, 0x64, 0x69, 0x63, 0x74, 0x6f, 0, 0x61, 0x64, 0x6d, 0x69, 0x74, 0x69, 0x72, 0, 0x61, 0x64, 0x6f, 0x70, 0x74, 0x61, 0x72, 0, 0x61, 0x64, 0x6f, 0x72, 0x6e, 0x6f, 0, 0x61, 0x64, 0x75, 0x61, 0x6e, 0x61, 0, 0x61, 0x64, 0x75, 0x6c, 0x74, 0x6f, 0, 0x61, 0x65, 0xcc, 0x81, 0x72, 0x65, 0x6f, 0, 0x61, 0x66, 0x65, 0x63, 0x74, 0x61, 0x72, 0, 0x61, 0x66, 0x69, 0x63, 0x69, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x61, 0x66, 0x69, 0x6e, 0x61, 0x72, 0, 0x61, 0x66, 0x69, 0x72, 0x6d, 0x61, 0x72, 0, 0x61, 0xcc, 0x81, 0x67, 0x69, 0x6c, 0, 0x61, 0x67, 0x69, 0x74, 0x61, 0x72, 0, 0x61, 0x67, 0x6f, 0x6e, 0x69, 0xcc, 0x81, 0x61, 0, 0x61, 0x67, 0x6f, 0x73, 0x74, 0x6f, 0, 0x61, 0x67, 0x6f, 0x74, 0x61, 0x72, 0, 0x61, 0x67, 0x72, 0x65, 0x67, 0x61, 0x72, 0, 0x61, 0x67, 0x72, 0x69, 0x6f, 0, 0x61, 0x67, 0x75, 0x61, 0, 0x61, 0x67, 0x75, 0x64, 0x6f, 0, 0x61, 0xcc, 0x81, 0x67, 0x75, 0x69, 0x6c, 0x61, 0, 0x61, 0x67, 0x75, 0x6a, 0x61, 0, 0x61, 0x68, 0x6f, 0x67, 0x6f, 0, 0x61, 0x68, 0x6f, 0x72, 0x72, 0x6f, 0, 0x61, 0x69, 0x72, 0x65, 0, 0x61, 0x69, 0x73, 0x6c, 0x61, 0x72, 0, 0x61, 0x6a, 0x65, 0x64, 0x72, 0x65, 0x7a, 0, 0x61, 0x6a, 0x65, 0x6e, 0x6f, 0, 0x61, 0x6a, 0x75, 0x73, 0x74, 0x65, 0, 0x61, 0x6c, 0x61, 0x63, 0x72, 0x61, 0xcc, 0x81, 0x6e, 0, 0x61, 0x6c, 0x61, 0x6d, 0x62, 0x72, 0x65, 0, 0x61, 0x6c, 0x61, 0x72, 0x6d, 0x61, 0, 0x61, 0x6c, 0x62, 0x61, 0, 0x61, 0xcc, 0x81, 0x6c, 0x62, 0x75, 0x6d, 0, 0x61, 0x6c, 0x63, 0x61, 0x6c, 0x64, 0x65, 0, 0x61, 0x6c, 0x64, 0x65, 0x61, 0, 0x61, 0x6c, 0x65, 0x67, 0x72, 0x65, 0, 0x61, 0x6c, 0x65, 0x6a, 0x61, 0x72, 0, 0x61, 0x6c, 0x65, 0x72, 0x74, 0x61, 0, 0x61, 0x6c, 0x65, 0x74, 0x61, 0, 0x61, 0x6c, 0x66, 0x69, 0x6c, 0x65, 0x72, 0, 0x61, 0x6c, 0x67, 0x61, 0, 0x61, 0x6c, 0x67, 0x6f, 0x64, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x61, 0x6c, 0x69, 0x61, 0x64, 0x6f, 0, 0x61, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x6f, 0, 0x61, 0x6c, 0x69, 0x76, 0x69, 0x6f, 0, 0x61, 0x6c, 0x6d, 0x61, 0, 0x61, 0x6c, 0x6d, 0x65, 0x6a, 0x61, 0, 0x61, 0x6c, 0x6d, 0x69, 0xcc, 0x81, 0x62, 0x61, 0x72, 0, 0x61, 0x6c, 0x74, 0x61, 0x72, 0, 0x61, 0x6c, 0x74, 0x65, 0x7a, 0x61, 0, 0x61, 0x6c, 0x74, 0x69, 0x76, 0x6f, 0, 0x61, 0x6c, 0x74, 0x6f, 0, 0x61, 0x6c, 0x74, 0x75, 0x72, 0x61, 0, 0x61, 0x6c, 0x75, 0x6d, 0x6e, 0x6f, 0, 0x61, 0x6c, 0x7a, 0x61, 0x72, 0, 0x61, 0x6d, 0x61, 0x62, 0x6c, 0x65, 0, 0x61, 0x6d, 0x61, 0x6e, 0x74, 0x65, 0, 0x61, 0x6d, 0x61, 0x70, 0x6f, 0x6c, 0x61, 0, 0x61, 0x6d, 0x61, 0x72, 0x67, 0x6f, 0, 0x61, 0x6d, 0x61, 0x73, 0x61, 0x72, 0, 0x61, 0xcc, 0x81, 0x6d, 0x62, 0x61, 0x72, 0, 0x61, 0xcc, 0x81, 0x6d, 0x62, 0x69, 0x74, 0x6f, 0, 0x61, 0x6d, 0x65, 0x6e, 0x6f, 0, 0x61, 0x6d, 0x69, 0x67, 0x6f, 0, 0x61, 0x6d, 0x69, 0x73, 0x74, 0x61, 0x64, 0, 0x61, 0x6d, 0x6f, 0x72, 0, 0x61, 0x6d, 0x70, 0x61, 0x72, 0x6f, 0, 0x61, 0x6d, 0x70, 0x6c, 0x69, 0x6f, 0, 0x61, 0x6e, 0x63, 0x68, 0x6f, 0, 0x61, 0x6e, 0x63, 0x69, 0x61, 0x6e, 0x6f, 0, 0x61, 0x6e, 0x63, 0x6c, 0x61, 0, 0x61, 0x6e, 0x64, 0x61, 0x72, 0, 0x61, 0x6e, 0x64, 0x65, 0xcc, 0x81, 0x6e, 0, 0x61, 0x6e, 0x65, 0x6d, 0x69, 0x61, 0, 0x61, 0xcc, 0x81, 0x6e, 0x67, 0x75, 0x6c, 0x6f, 0, 0x61, 0x6e, 0x69, 0x6c, 0x6c, 0x6f, 0, 0x61, 0xcc, 0x81, 0x6e, 0x69, 0x6d, 0x6f, 0, 0x61, 0x6e, 0x69, 0xcc, 0x81, 0x73, 0, 0x61, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0, 0x61, 0x6e, 0x74, 0x65, 0x6e, 0x61, 0, 0x61, 0x6e, 0x74, 0x69, 0x67, 0x75, 0x6f, 0, 0x61, 0x6e, 0x74, 0x6f, 0x6a, 0x6f, 0, 0x61, 0x6e, 0x75, 0x61, 0x6c, 0, 0x61, 0x6e, 0x75, 0x6c, 0x61, 0x72, 0, 0x61, 0x6e, 0x75, 0x6e, 0x63, 0x69, 0x6f, 0, 0x61, 0x6e, 0xcc, 0x83, 0x61, 0x64, 0x69, 0x72, 0, 0x61, 0x6e, 0xcc, 0x83, 0x65, 0x6a, 0x6f, 0, 0x61, 0x6e, 0xcc, 0x83, 0x6f, 0, 0x61, 0x70, 0x61, 0x67, 0x61, 0x72, 0, 0x61, 0x70, 0x61, 0x72, 0x61, 0x74, 0x6f, 0, 0x61, 0x70, 0x65, 0x74, 0x69, 0x74, 0x6f, 0, 0x61, 0x70, 0x69, 0x6f, 0, 0x61, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x72, 0, 0x61, 0x70, 0x6f, 0x64, 0x6f, 0, 0x61, 0x70, 0x6f, 0x72, 0x74, 0x65, 0, 0x61, 0x70, 0x6f, 0x79, 0x6f, 0, 0x61, 0x70, 0x72, 0x65, 0x6e, 0x64, 0x65, 0x72, 0, 0x61, 0x70, 0x72, 0x6f, 0x62, 0x61, 0x72, 0, 0x61, 0x70, 0x75, 0x65, 0x73, 0x74, 0x61, 0, 0x61, 0x70, 0x75, 0x72, 0x6f, 0, 0x61, 0x72, 0x61, 0x64, 0x6f, 0, 0x61, 0x72, 0x61, 0x6e, 0xcc, 0x83, 0x61, 0, 0x61, 0x72, 0x61, 0x72, 0, 0x61, 0xcc, 0x81, 0x72, 0x62, 0x69, 0x74, 0x72, 0x6f, 0, 0x61, 0xcc, 0x81, 0x72, 0x62, 0x6f, 0x6c, 0, 0x61, 0x72, 0x62, 0x75, 0x73, 0x74, 0x6f, 0, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x6f, 0, 0x61, 0x72, 0x63, 0x6f, 0, 0x61, 0x72, 0x64, 0x65, 0x72, 0, 0x61, 0x72, 0x64, 0x69, 0x6c, 0x6c, 0x61, 0, 0x61, 0x72, 0x64, 0x75, 0x6f, 0, 0x61, 0xcc, 0x81, 0x72, 0x65, 0x61, 0, 0x61, 0xcc, 0x81, 0x72, 0x69, 0x64, 0x6f, 0, 0x61, 0x72, 0x69, 0x65, 0x73, 0, 0x61, 0x72, 0x6d, 0x6f, 0x6e, 0x69, 0xcc, 0x81, 0x61, 0, 0x61, 0x72, 0x6e, 0x65, 0xcc, 0x81, 0x73, 0, 0x61, 0x72, 0x6f, 0x6d, 0x61, 0, 0x61, 0x72, 0x70, 0x61, 0, 0x61, 0x72, 0x70, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x61, 0x72, 0x72, 0x65, 0x67, 0x6c, 0x6f, 0, 0x61, 0x72, 0x72, 0x6f, 0x7a, 0, 0x61, 0x72, 0x72, 0x75, 0x67, 0x61, 0, 0x61, 0x72, 0x74, 0x65, 0, 0x61, 0x72, 0x74, 0x69, 0x73, 0x74, 0x61, 0, 0x61, 0x73, 0x61, 0, 0x61, 0x73, 0x61, 0x64, 0x6f, 0, 0x61, 0x73, 0x61, 0x6c, 0x74, 0x6f, 0, 0x61, 0x73, 0x63, 0x65, 0x6e, 0x73, 0x6f, 0, 0x61, 0x73, 0x65, 0x67, 0x75, 0x72, 0x61, 0x72, 0, 0x61, 0x73, 0x65, 0x6f, 0, 0x61, 0x73, 0x65, 0x73, 0x6f, 0x72, 0, 0x61, 0x73, 0x69, 0x65, 0x6e, 0x74, 0x6f, 0, 0x61, 0x73, 0x69, 0x6c, 0x6f, 0, 0x61, 0x73, 0x69, 0x73, 0x74, 0x69, 0x72, 0, 0x61, 0x73, 0x6e, 0x6f, 0, 0x61, 0x73, 0x6f, 0x6d, 0x62, 0x72, 0x6f, 0, 0x61, 0xcc, 0x81, 0x73, 0x70, 0x65, 0x72, 0x6f, 0, 0x61, 0x73, 0x74, 0x69, 0x6c, 0x6c, 0x61, 0, 0x61, 0x73, 0x74, 0x72, 0x6f, 0, 0x61, 0x73, 0x74, 0x75, 0x74, 0x6f, 0, 0x61, 0x73, 0x75, 0x6d, 0x69, 0x72, 0, 0x61, 0x73, 0x75, 0x6e, 0x74, 0x6f, 0, 0x61, 0x74, 0x61, 0x6a, 0x6f, 0, 0x61, 0x74, 0x61, 0x71, 0x75, 0x65, 0, 0x61, 0x74, 0x61, 0x72, 0, 0x61, 0x74, 0x65, 0x6e, 0x74, 0x6f, 0, 0x61, 0x74, 0x65, 0x6f, 0, 0x61, 0xcc, 0x81, 0x74, 0x69, 0x63, 0x6f, 0, 0x61, 0x74, 0x6c, 0x65, 0x74, 0x61, 0, 0x61, 0xcc, 0x81, 0x74, 0x6f, 0x6d, 0x6f, 0, 0x61, 0x74, 0x72, 0x61, 0x65, 0x72, 0, 0x61, 0x74, 0x72, 0x6f, 0x7a, 0, 0x61, 0x74, 0x75, 0xcc, 0x81, 0x6e, 0, 0x61, 0x75, 0x64, 0x61, 0x7a, 0, 0x61, 0x75, 0x64, 0x69, 0x6f, 0, 0x61, 0x75, 0x67, 0x65, 0, 0x61, 0x75, 0x6c, 0x61, 0, 0x61, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x6f, 0, 0x61, 0x75, 0x73, 0x65, 0x6e, 0x74, 0x65, 0, 0x61, 0x75, 0x74, 0x6f, 0x72, 0, 0x61, 0x76, 0x61, 0x6c, 0, 0x61, 0x76, 0x61, 0x6e, 0x63, 0x65, 0, 0x61, 0x76, 0x61, 0x72, 0x6f, 0, 0x61, 0x76, 0x65, 0, 0x61, 0x76, 0x65, 0x6c, 0x6c, 0x61, 0x6e, 0x61, 0, 0x61, 0x76, 0x65, 0x6e, 0x61, 0, 0x61, 0x76, 0x65, 0x73, 0x74, 0x72, 0x75, 0x7a, 0, 0x61, 0x76, 0x69, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x61, 0x76, 0x69, 0x73, 0x6f, 0, 0x61, 0x79, 0x65, 0x72, 0, 0x61, 0x79, 0x75, 0x64, 0x61, 0, 0x61, 0x79, 0x75, 0x6e, 0x6f, 0, 0x61, 0x7a, 0x61, 0x66, 0x72, 0x61, 0xcc, 0x81, 0x6e, 0, 0x61, 0x7a, 0x61, 0x72, 0, 0x61, 0x7a, 0x6f, 0x74, 0x65, 0, 0x61, 0x7a, 0x75, 0xcc, 0x81, 0x63, 0x61, 0x72, 0, 0x61, 0x7a, 0x75, 0x66, 0x72, 0x65, 0, 0x61, 0x7a, 0x75, 0x6c, 0, 0x62, 0x61, 0x62, 0x61, 0, 0x62, 0x61, 0x62, 0x6f, 0x72, 0, 0x62, 0x61, 0x63, 0x68, 0x65, 0, 0x62, 0x61, 0x68, 0x69, 0xcc, 0x81, 0x61, 0, 0x62, 0x61, 0x69, 0x6c, 0x65, 0, 0x62, 0x61, 0x6a, 0x61, 0x72, 0, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x7a, 0x61, 0, 0x62, 0x61, 0x6c, 0x63, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x62, 0x61, 0x6c, 0x64, 0x65, 0, 0x62, 0x61, 0x6d, 0x62, 0x75, 0xcc, 0x81, 0, 0x62, 0x61, 0x6e, 0x63, 0x6f, 0, 0x62, 0x61, 0x6e, 0x64, 0x61, 0, 0x62, 0x61, 0x6e, 0xcc, 0x83, 0x6f, 0, 0x62, 0x61, 0x72, 0x62, 0x61, 0, 0x62, 0x61, 0x72, 0x63, 0x6f, 0, 0x62, 0x61, 0x72, 0x6e, 0x69, 0x7a, 0, 0x62, 0x61, 0x72, 0x72, 0x6f, 0, 0x62, 0x61, 0xcc, 0x81, 0x73, 0x63, 0x75, 0x6c, 0x61, 0, 0x62, 0x61, 0x73, 0x74, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x62, 0x61, 0x73, 0x75, 0x72, 0x61, 0, 0x62, 0x61, 0x74, 0x61, 0x6c, 0x6c, 0x61, 0, 0x62, 0x61, 0x74, 0x65, 0x72, 0x69, 0xcc, 0x81, 0x61, 0, 0x62, 0x61, 0x74, 0x69, 0x72, 0, 0x62, 0x61, 0x74, 0x75, 0x74, 0x61, 0, 0x62, 0x61, 0x75, 0xcc, 0x81, 0x6c, 0, 0x62, 0x61, 0x7a, 0x61, 0x72, 0, 0x62, 0x65, 0x62, 0x65, 0xcc, 0x81, 0, 0x62, 0x65, 0x62, 0x69, 0x64, 0x61, 0, 0x62, 0x65, 0x6c, 0x6c, 0x6f, 0, 0x62, 0x65, 0x73, 0x61, 0x72, 0, 0x62, 0x65, 0x73, 0x6f, 0, 0x62, 0x65, 0x73, 0x74, 0x69, 0x61, 0, 0x62, 0x69, 0x63, 0x68, 0x6f, 0, 0x62, 0x69, 0x65, 0x6e, 0, 0x62, 0x69, 0x6e, 0x67, 0x6f, 0, 0x62, 0x6c, 0x61, 0x6e, 0x63, 0x6f, 0, 0x62, 0x6c, 0x6f, 0x71, 0x75, 0x65, 0, 0x62, 0x6c, 0x75, 0x73, 0x61, 0, 0x62, 0x6f, 0x61, 0, 0x62, 0x6f, 0x62, 0x69, 0x6e, 0x61, 0, 0x62, 0x6f, 0x62, 0x6f, 0, 0x62, 0x6f, 0x63, 0x61, 0, 0x62, 0x6f, 0x63, 0x69, 0x6e, 0x61, 0, 0x62, 0x6f, 0x64, 0x61, 0, 0x62, 0x6f, 0x64, 0x65, 0x67, 0x61, 0, 0x62, 0x6f, 0x69, 0x6e, 0x61, 0, 0x62, 0x6f, 0x6c, 0x61, 0, 0x62, 0x6f, 0x6c, 0x65, 0x72, 0x6f, 0, 0x62, 0x6f, 0x6c, 0x73, 0x61, 0, 0x62, 0x6f, 0x6d, 0x62, 0x61, 0, 0x62, 0x6f, 0x6e, 0x64, 0x61, 0x64, 0, 0x62, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0, 0x62, 0x6f, 0x6e, 0x6f, 0, 0x62, 0x6f, 0x6e, 0x73, 0x61, 0xcc, 0x81, 0x69, 0, 0x62, 0x6f, 0x72, 0x64, 0x65, 0, 0x62, 0x6f, 0x72, 0x72, 0x61, 0x72, 0, 0x62, 0x6f, 0x73, 0x71, 0x75, 0x65, 0, 0x62, 0x6f, 0x74, 0x65, 0, 0x62, 0x6f, 0x74, 0x69, 0xcc, 0x81, 0x6e, 0, 0x62, 0x6f, 0xcc, 0x81, 0x76, 0x65, 0x64, 0x61, 0, 0x62, 0x6f, 0x7a, 0x61, 0x6c, 0, 0x62, 0x72, 0x61, 0x76, 0x6f, 0, 0x62, 0x72, 0x61, 0x7a, 0x6f, 0, 0x62, 0x72, 0x65, 0x63, 0x68, 0x61, 0, 0x62, 0x72, 0x65, 0x76, 0x65, 0, 0x62, 0x72, 0x69, 0x6c, 0x6c, 0x6f, 0, 0x62, 0x72, 0x69, 0x6e, 0x63, 0x6f, 0, 0x62, 0x72, 0x69, 0x73, 0x61, 0, 0x62, 0x72, 0x6f, 0x63, 0x61, 0, 0x62, 0x72, 0x6f, 0x6d, 0x61, 0, 0x62, 0x72, 0x6f, 0x6e, 0x63, 0x65, 0, 0x62, 0x72, 0x6f, 0x74, 0x65, 0, 0x62, 0x72, 0x75, 0x6a, 0x61, 0, 0x62, 0x72, 0x75, 0x73, 0x63, 0x6f, 0, 0x62, 0x72, 0x75, 0x74, 0x6f, 0, 0x62, 0x75, 0x63, 0x65, 0x6f, 0, 0x62, 0x75, 0x63, 0x6c, 0x65, 0, 0x62, 0x75, 0x65, 0x6e, 0x6f, 0, 0x62, 0x75, 0x65, 0x79, 0, 0x62, 0x75, 0x66, 0x61, 0x6e, 0x64, 0x61, 0, 0x62, 0x75, 0x66, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x62, 0x75, 0xcc, 0x81, 0x68, 0x6f, 0, 0x62, 0x75, 0x69, 0x74, 0x72, 0x65, 0, 0x62, 0x75, 0x6c, 0x74, 0x6f, 0, 0x62, 0x75, 0x72, 0x62, 0x75, 0x6a, 0x61, 0, 0x62, 0x75, 0x72, 0x6c, 0x61, 0, 0x62, 0x75, 0x72, 0x72, 0x6f, 0, 0x62, 0x75, 0x73, 0x63, 0x61, 0x72, 0, 0x62, 0x75, 0x74, 0x61, 0x63, 0x61, 0, 0x62, 0x75, 0x7a, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x63, 0x61, 0x62, 0x61, 0x6c, 0x6c, 0x6f, 0, 0x63, 0x61, 0x62, 0x65, 0x7a, 0x61, 0, 0x63, 0x61, 0x62, 0x69, 0x6e, 0x61, 0, 0x63, 0x61, 0x62, 0x72, 0x61, 0, 0x63, 0x61, 0x63, 0x61, 0x6f, 0, 0x63, 0x61, 0x64, 0x61, 0xcc, 0x81, 0x76, 0x65, 0x72, 0, 0x63, 0x61, 0x64, 0x65, 0x6e, 0x61, 0, 0x63, 0x61, 0x65, 0x72, 0, 0x63, 0x61, 0x66, 0x65, 0xcc, 0x81, 0, 0x63, 0x61, 0x69, 0xcc, 0x81, 0x64, 0x61, 0, 0x63, 0x61, 0x69, 0x6d, 0x61, 0xcc, 0x81, 0x6e, 0, 0x63, 0x61, 0x6a, 0x61, 0, 0x63, 0x61, 0x6a, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x63, 0x61, 0x6c, 0, 0x63, 0x61, 0x6c, 0x61, 0x6d, 0x61, 0x72, 0, 0x63, 0x61, 0x6c, 0x63, 0x69, 0x6f, 0, 0x63, 0x61, 0x6c, 0x64, 0x6f, 0, 0x63, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x64, 0, 0x63, 0x61, 0x6c, 0x6c, 0x65, 0, 0x63, 0x61, 0x6c, 0x6d, 0x61, 0, 0x63, 0x61, 0x6c, 0x6f, 0x72, 0, 0x63, 0x61, 0x6c, 0x76, 0x6f, 0, 0x63, 0x61, 0x6d, 0x61, 0, 0x63, 0x61, 0x6d, 0x62, 0x69, 0x6f, 0, 0x63, 0x61, 0x6d, 0x65, 0x6c, 0x6c, 0x6f, 0, 0x63, 0x61, 0x6d, 0x69, 0x6e, 0x6f, 0, 0x63, 0x61, 0x6d, 0x70, 0x6f, 0, 0x63, 0x61, 0xcc, 0x81, 0x6e, 0x63, 0x65, 0x72, 0, 0x63, 0x61, 0x6e, 0x64, 0x69, 0x6c, 0, 0x63, 0x61, 0x6e, 0x65, 0x6c, 0x61, 0, 0x63, 0x61, 0x6e, 0x67, 0x75, 0x72, 0x6f, 0, 0x63, 0x61, 0x6e, 0x69, 0x63, 0x61, 0, 0x63, 0x61, 0x6e, 0x74, 0x6f, 0, 0x63, 0x61, 0x6e, 0xcc, 0x83, 0x61, 0, 0x63, 0x61, 0x6e, 0xcc, 0x83, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x63, 0x61, 0x6f, 0x62, 0x61, 0, 0x63, 0x61, 0x6f, 0x73, 0, 0x63, 0x61, 0x70, 0x61, 0x7a, 0, 0x63, 0x61, 0x70, 0x69, 0x74, 0x61, 0xcc, 0x81, 0x6e, 0, 0x63, 0x61, 0x70, 0x6f, 0x74, 0x65, 0, 0x63, 0x61, 0x70, 0x74, 0x61, 0x72, 0, 0x63, 0x61, 0x70, 0x75, 0x63, 0x68, 0x61, 0, 0x63, 0x61, 0x72, 0x61, 0, 0x63, 0x61, 0x72, 0x62, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x63, 0x61, 0xcc, 0x81, 0x72, 0x63, 0x65, 0x6c, 0, 0x63, 0x61, 0x72, 0x65, 0x74, 0x61, 0, 0x63, 0x61, 0x72, 0x67, 0x61, 0, 0x63, 0x61, 0x72, 0x69, 0x6e, 0xcc, 0x83, 0x6f, 0, 0x63, 0x61, 0x72, 0x6e, 0x65, 0, 0x63, 0x61, 0x72, 0x70, 0x65, 0x74, 0x61, 0, 0x63, 0x61, 0x72, 0x72, 0x6f, 0, 0x63, 0x61, 0x72, 0x74, 0x61, 0, 0x63, 0x61, 0x73, 0x61, 0, 0x63, 0x61, 0x73, 0x63, 0x6f, 0, 0x63, 0x61, 0x73, 0x65, 0x72, 0x6f, 0, 0x63, 0x61, 0x73, 0x70, 0x61, 0, 0x63, 0x61, 0x73, 0x74, 0x6f, 0x72, 0, 0x63, 0x61, 0x74, 0x6f, 0x72, 0x63, 0x65, 0, 0x63, 0x61, 0x74, 0x72, 0x65, 0, 0x63, 0x61, 0x75, 0x64, 0x61, 0x6c, 0, 0x63, 0x61, 0x75, 0x73, 0x61, 0, 0x63, 0x61, 0x7a, 0x6f, 0, 0x63, 0x65, 0x62, 0x6f, 0x6c, 0x6c, 0x61, 0, 0x63, 0x65, 0x64, 0x65, 0x72, 0, 0x63, 0x65, 0x64, 0x72, 0x6f, 0, 0x63, 0x65, 0x6c, 0x64, 0x61, 0, 0x63, 0x65, 0xcc, 0x81, 0x6c, 0x65, 0x62, 0x72, 0x65, 0, 0x63, 0x65, 0x6c, 0x6f, 0x73, 0x6f, 0, 0x63, 0x65, 0xcc, 0x81, 0x6c, 0x75, 0x6c, 0x61, 0, 0x63, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x6f, 0, 0x63, 0x65, 0x6e, 0x69, 0x7a, 0x61, 0, 0x63, 0x65, 0x6e, 0x74, 0x72, 0x6f, 0, 0x63, 0x65, 0x72, 0x63, 0x61, 0, 0x63, 0x65, 0x72, 0x64, 0x6f, 0, 0x63, 0x65, 0x72, 0x65, 0x7a, 0x61, 0, 0x63, 0x65, 0x72, 0x6f, 0, 0x63, 0x65, 0x72, 0x72, 0x61, 0x72, 0, 0x63, 0x65, 0x72, 0x74, 0x65, 0x7a, 0x61, 0, 0x63, 0x65, 0xcc, 0x81, 0x73, 0x70, 0x65, 0x64, 0, 0x63, 0x65, 0x74, 0x72, 0x6f, 0, 0x63, 0x68, 0x61, 0x63, 0x61, 0x6c, 0, 0x63, 0x68, 0x61, 0x6c, 0x65, 0x63, 0x6f, 0, 0x63, 0x68, 0x61, 0x6d, 0x70, 0x75, 0xcc, 0x81, 0, 0x63, 0x68, 0x61, 0x6e, 0x63, 0x6c, 0x61, 0, 0x63, 0x68, 0x61, 0x70, 0x61, 0, 0x63, 0x68, 0x61, 0x72, 0x6c, 0x61, 0, 0x63, 0x68, 0x69, 0x63, 0x6f, 0, 0x63, 0x68, 0x69, 0x73, 0x74, 0x65, 0, 0x63, 0x68, 0x69, 0x76, 0x6f, 0, 0x63, 0x68, 0x6f, 0x71, 0x75, 0x65, 0, 0x63, 0x68, 0x6f, 0x7a, 0x61, 0, 0x63, 0x68, 0x75, 0x6c, 0x65, 0x74, 0x61, 0, 0x63, 0x68, 0x75, 0x70, 0x61, 0x72, 0, 0x63, 0x69, 0x63, 0x6c, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x63, 0x69, 0x65, 0x67, 0x6f, 0, 0x63, 0x69, 0x65, 0x6c, 0x6f, 0, 0x63, 0x69, 0x65, 0x6e, 0, 0x63, 0x69, 0x65, 0x72, 0x74, 0x6f, 0, 0x63, 0x69, 0x66, 0x72, 0x61, 0, 0x63, 0x69, 0x67, 0x61, 0x72, 0x72, 0x6f, 0, 0x63, 0x69, 0x6d, 0x61, 0, 0x63, 0x69, 0x6e, 0x63, 0x6f, 0, 0x63, 0x69, 0x6e, 0x65, 0, 0x63, 0x69, 0x6e, 0x74, 0x61, 0, 0x63, 0x69, 0x70, 0x72, 0x65, 0xcc, 0x81, 0x73, 0, 0x63, 0x69, 0x72, 0x63, 0x6f, 0, 0x63, 0x69, 0x72, 0x75, 0x65, 0x6c, 0x61, 0, 0x63, 0x69, 0x73, 0x6e, 0x65, 0, 0x63, 0x69, 0x74, 0x61, 0, 0x63, 0x69, 0x75, 0x64, 0x61, 0x64, 0, 0x63, 0x6c, 0x61, 0x6d, 0x6f, 0x72, 0, 0x63, 0x6c, 0x61, 0x6e, 0, 0x63, 0x6c, 0x61, 0x72, 0x6f, 0, 0x63, 0x6c, 0x61, 0x73, 0x65, 0, 0x63, 0x6c, 0x61, 0x76, 0x65, 0, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x65, 0, 0x63, 0x6c, 0x69, 0x6d, 0x61, 0, 0x63, 0x6c, 0x69, 0xcc, 0x81, 0x6e, 0x69, 0x63, 0x61, 0, 0x63, 0x6f, 0x62, 0x72, 0x65, 0, 0x63, 0x6f, 0x63, 0x63, 0x69, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x63, 0x6f, 0x63, 0x68, 0x69, 0x6e, 0x6f, 0, 0x63, 0x6f, 0x63, 0x69, 0x6e, 0x61, 0, 0x63, 0x6f, 0x63, 0x6f, 0, 0x63, 0x6f, 0xcc, 0x81, 0x64, 0x69, 0x67, 0x6f, 0, 0x63, 0x6f, 0x64, 0x6f, 0, 0x63, 0x6f, 0x66, 0x72, 0x65, 0, 0x63, 0x6f, 0x67, 0x65, 0x72, 0, 0x63, 0x6f, 0x68, 0x65, 0x74, 0x65, 0, 0x63, 0x6f, 0x6a, 0x69, 0xcc, 0x81, 0x6e, 0, 0x63, 0x6f, 0x6a, 0x6f, 0, 0x63, 0x6f, 0x6c, 0x61, 0, 0x63, 0x6f, 0x6c, 0x63, 0x68, 0x61, 0, 0x63, 0x6f, 0x6c, 0x65, 0x67, 0x69, 0x6f, 0, 0x63, 0x6f, 0x6c, 0x67, 0x61, 0x72, 0, 0x63, 0x6f, 0x6c, 0x69, 0x6e, 0x61, 0, 0x63, 0x6f, 0x6c, 0x6c, 0x61, 0x72, 0, 0x63, 0x6f, 0x6c, 0x6d, 0x6f, 0, 0x63, 0x6f, 0x6c, 0x75, 0x6d, 0x6e, 0x61, 0, 0x63, 0x6f, 0x6d, 0x62, 0x61, 0x74, 0x65, 0, 0x63, 0x6f, 0x6d, 0x65, 0x72, 0, 0x63, 0x6f, 0x6d, 0x69, 0x64, 0x61, 0, 0x63, 0x6f, 0xcc, 0x81, 0x6d, 0x6f, 0x64, 0x6f, 0, 0x63, 0x6f, 0x6d, 0x70, 0x72, 0x61, 0, 0x63, 0x6f, 0x6e, 0x64, 0x65, 0, 0x63, 0x6f, 0x6e, 0x65, 0x6a, 0x6f, 0, 0x63, 0x6f, 0x6e, 0x67, 0x61, 0, 0x63, 0x6f, 0x6e, 0x6f, 0x63, 0x65, 0x72, 0, 0x63, 0x6f, 0x6e, 0x73, 0x65, 0x6a, 0x6f, 0, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x72, 0, 0x63, 0x6f, 0x70, 0x61, 0, 0x63, 0x6f, 0x70, 0x69, 0x61, 0, 0x63, 0x6f, 0x72, 0x61, 0x7a, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x63, 0x6f, 0x72, 0x62, 0x61, 0x74, 0x61, 0, 0x63, 0x6f, 0x72, 0x63, 0x68, 0x6f, 0, 0x63, 0x6f, 0x72, 0x64, 0x6f, 0xcc, 0x81, 0x6e, 0, 0x63, 0x6f, 0x72, 0x6f, 0x6e, 0x61, 0, 0x63, 0x6f, 0x72, 0x72, 0x65, 0x72, 0, 0x63, 0x6f, 0x73, 0x65, 0x72, 0, 0x63, 0x6f, 0x73, 0x6d, 0x6f, 0x73, 0, 0x63, 0x6f, 0x73, 0x74, 0x61, 0, 0x63, 0x72, 0x61, 0xcc, 0x81, 0x6e, 0x65, 0x6f, 0, 0x63, 0x72, 0x61, 0xcc, 0x81, 0x74, 0x65, 0x72, 0, 0x63, 0x72, 0x65, 0x61, 0x72, 0, 0x63, 0x72, 0x65, 0x63, 0x65, 0x72, 0, 0x63, 0x72, 0x65, 0x69, 0xcc, 0x81, 0x64, 0x6f, 0, 0x63, 0x72, 0x65, 0x6d, 0x61, 0, 0x63, 0x72, 0x69, 0xcc, 0x81, 0x61, 0, 0x63, 0x72, 0x69, 0x6d, 0x65, 0x6e, 0, 0x63, 0x72, 0x69, 0x7
c++
code
20,000
6,498
// Copyright (c) 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/core/crypto/tls_client_connection.h" namespace quic { TlsClientConnection::TlsClientConnection(SSL_CTX* ssl_ctx, Delegate* delegate) : TlsConnection(ssl_ctx, delegate->ConnectionDelegate()), delegate_(delegate) {} // static bssl::UniquePtr<SSL_CTX> TlsClientConnection::CreateSslCtx( bool enable_early_data) { bssl::UniquePtr<SSL_CTX> ssl_ctx = TlsConnection::CreateSslCtx(); // Configure certificate verification. SSL_CTX_set_custom_verify(ssl_ctx.get(), SSL_VERIFY_PEER, &VerifyCallback); int reverify_on_resume_enabled = 1; SSL_CTX_set_reverify_on_resume(ssl_ctx.get(), reverify_on_resume_enabled); // Configure session caching. SSL_CTX_set_session_cache_mode( ssl_ctx.get(), SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL); SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback); SSL_CTX_set_early_data_enabled(ssl_ctx.get(), enable_early_data); return ssl_ctx; } // static enum ssl_verify_result_t TlsClientConnection::VerifyCallback( SSL* ssl, uint8_t* out_alert) { return static_cast<TlsClientConnection*>(ConnectionFromSsl(ssl)) ->delegate_->VerifyCert(out_alert); } // static int TlsClientConnection::NewSessionCallback(SSL* ssl, SSL_SESSION* session) { static_cast<TlsClientConnection*>(ConnectionFromSsl(ssl)) ->delegate_->InsertSession(bssl::UniquePtr<SSL_SESSION>(session)); return 1; } } // namespace quic
c++
code
1,614
285
#include "shaders.h" namespace ou { const char* const quadVertShaderSrc = #include "shaders/quad.vert.glsl" ; const char* const hdrFragShaderSrc = #include "shaders/hdr.frag.glsl" ; const char* const skyFromSpaceVertShaderSrc = #include "shaders/skyfromspace.vert.glsl" ; const char* const skyFromSpaceFragShaderSrc = #include "shaders/skyfromspace.frag.glsl" ; const char* const planetVertShaderSrc = #include "shaders/planet.vert.glsl" ; const char* const planetFragShaderSrc = #include "shaders/planet.frag.glsl" ; const char* const terrainShaderSrc = #include "shaders/terrain.comp.glsl" ; const char* const terrain2ShaderSrc = #include "shaders/terrain2.comp.glsl" ; }
c++
code
706
105
#include "JavascriptSearchBox.h" #include "Widgets/Input/SSearchBox.h" UJavascriptSearchBox::UJavascriptSearchBox(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } TSharedRef<SWidget> UJavascriptSearchBox::RebuildWidget() { MySearchBox = SNew(SSearchBox) .OnTextChanged_Lambda([this](const FText& InText) { OnTextChanged.Broadcast(InText); }) .OnTextCommitted_Lambda([this](const FText& InText, ETextCommit::Type CommitMethod) { OnTextCommitted.Broadcast(InText, CommitMethod); }) ; return MySearchBox.ToSharedRef(); } void UJavascriptSearchBox::SetText(FText InText) { Text = InText; if (MySearchBox.IsValid()) { MySearchBox->SetText(Text); } } void UJavascriptSearchBox::SetHintText(FText InHintText) { HintText = InHintText; if (MySearchBox.IsValid()) { MySearchBox->SetHintText(HintText); } } void UJavascriptSearchBox::SynchronizeProperties() { Super::SynchronizeProperties(); TAttribute<FText> TextBinding = PROPERTY_BINDING(FText, Text); TAttribute<FText> HintTextBinding = PROPERTY_BINDING(FText, HintText); MySearchBox->SetText(TextBinding); MySearchBox->SetHintText(HintTextBinding); }
c++
code
1,157
229
/**************************************************************************\ * Copyright (c) Kongsberg Oil & Gas Technologies AS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder 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. \**************************************************************************/ /*! \class SoNormalGenerator SoNormalGenerator.h include/Inventor/misc/SoNormalGenerator.h \brief The SoNormalGenerator class is used to generate normals. \ingroup general FIXME: document properly */ #include <Inventor/misc/SoNormalGenerator.h> #include <cstdio> #include <Inventor/errors/SoDebugError.h> #include "tidbitsp.h" #include "coindefs.h" // COIN_OBSOLETED() /*! Constructor with \a isccw indicating if polygons are specified in counterclockwise order. The \a approxVertices can be used to optimize normal generation. */ SoNormalGenerator::SoNormalGenerator(const SbBool isccw, const int approxVertices) : bsp(128, approxVertices), vertexList(approxVertices), vertexFace(approxVertices), faceNormals(approxVertices / 4), vertexNormals(approxVertices), ccw(isccw), perVertex(TRUE) { } /*! Destructor. */ SoNormalGenerator::~SoNormalGenerator() { } /*! Resets the normal generator, making it possible to reuse it without allocating a new one. \COIN_FUNCTION_EXTENSION \since Coin 2.0 */ void SoNormalGenerator::reset(const SbBool ccwarg) { this->ccw = ccwarg; this->bsp.clear(); this->vertexList.truncate(0); this->vertexFace.truncate(0); this->faceNormals.truncate(0); this->vertexNormals.truncate(0); } /*! Signals the start of a new polygon. \sa SoNormalGenerator::polygonVertex() \sa SoNormalGenerator::endPolygon() */ void SoNormalGenerator::beginPolygon(void) { this->currFaceStart = this->vertexList.getLength(); } /*! Adds a vertex to the current polygon. \sa SoNormalGenerator::beginPolygon() \sa SoNormalGenerator::endPolygon() */ void SoNormalGenerator::polygonVertex(const SbVec3f &v) { this->vertexList.append(this->bsp.addPoint(v)); this->vertexFace.append(this->faceNormals.getLength()); } /*! Signals the end of a polygon. \sa SoNormalGenerator::beginPolygon() \sa SoNormalGenerator::polygonVertex() */ void SoNormalGenerator::endPolygon(void) { SbVec3f n = this->calcFaceNormal(); this->faceNormals.append(n); } /*! Convenience method for adding a triangle. */ void SoNormalGenerator::triangle(const SbVec3f &v0, const SbVec3f &v1, const SbVec3f &v2) { this->beginPolygon(); this->polygonVertex(v0); this->polygonVertex(v1); this->polygonVertex(v2); this->endPolygon(); } /*! Convenience method for adding a quad */ void SoNormalGenerator::quad(const SbVec3f &v0, const SbVec3f &v1, const SbVec3f &v2, const SbVec3f &v3) { this->beginPolygon(); this->polygonVertex(v0); this->polygonVertex(v1); this->polygonVertex(v2); this->polygonVertex(v3); this->endPolygon(); } // // calculates the normal vector for a vertex, based on the // normal vectors of all incident faces // static void calc_normal_vec(const SbVec3f *facenormals, const int facenum, SbList <int32_t> &faceArray, const float threshold, SbVec3f &vertnormal) { // start with face normal vector const SbVec3f * facenormal = &facenormals[facenum]; vertnormal = *facenormal; int n = faceArray.getLength(); int currface; for (int i = 0; i < n; i++) { currface = faceArray[i]; if (currface != facenum) { // check all but this face const SbVec3f &normal = facenormals[currface]; if ((normal.dot(*facenormal)) > threshold) { // smooth towards this face vertnormal += normal; } } } } /*! Triggers the normal generation. Normals are generated using \a creaseAngle to find which edges should be flat-shaded and which should be smooth-shaded. If normals are generated for triangle strips, the \a striplens and \a numstrips must be supplied. See src/nodes/SoTriangleStripSet.cpp (generateDefaultNormals()) for an example on how you send triangle strip information to this generator. It's not trivial, since you have to know how OpenGL/Coin generate triangles from triangle strips. */ void SoNormalGenerator::generate(const float creaseAngle, const int32_t *striplens, const int numstrips) { // just ignore the warnings from normalize(). A null vector just // means that we have an empty triangle which will be ignored by // OpenGL anyway. It's also common to have empty triangles in for // instance triangle strips (they're used as a trick to generate // longer triangle strips). int i; // for each vertex, store all faceindices the vertex is a part of SbList <int32_t> * vertexFaceArray = new SbList<int32_t>[bsp.numPoints()]; int numvi = this->vertexList.getLength(); for (i = 0; i < numvi; i++) { vertexFaceArray[vertexList[i]].append(this->vertexFace[i]); } float threshold = (float)cos(SbClamp(creaseAngle, 0.0f, (float) M_PI)); if (striplens) { i = 0; for (int j = 0; j < numstrips; j++) { assert(i+2 < numvi); SbVec3f tmpvec; calc_normal_vec(this->faceNormals.getArrayPtr(), this->vertexFace[i], vertexFaceArray[vertexList[i]], threshold, tmpvec); (void) tmpvec.normalize(); this->vertexNormals.append(tmpvec); calc_normal_vec(this->faceNormals.getArrayPtr(), this->vertexFace[i+1], vertexFaceArray[vertexList[i+1]], threshold, tmpvec); (void) tmpvec.normalize(); this->vertexNormals.append(tmpvec); int num = striplens[j] - 2; while (num--) { i += 2; assert(i < numvi); calc_normal_vec(this->faceNormals.getArrayPtr(), this->vertexFace[i], vertexFaceArray[vertexList[i]], threshold, tmpvec); (void) tmpvec.normalize(); this->vertexNormals.append(tmpvec); i++; } } } else { for (i = 0; i < numvi; i++) { SbVec3f tmpvec; calc_normal_vec(this->faceNormals.getArrayPtr(), this->vertexFace[i], vertexFaceArray[vertexList[i]], threshold, tmpvec); (void) tmpvec.normalize(); this->vertexNormals.append(tmpvec); } } delete [] vertexFaceArray; this->vertexFace.truncate(0, TRUE); this->vertexList.truncate(0, TRUE); this->faceNormals.truncate(0, TRUE); this->bsp.clear(); this->vertexNormals.fit(); // return vertex normals this->perVertex = TRUE; } /*! Generates one normal per strip by averaging face normals. */ void SoNormalGenerator::generatePerStrip(const int32_t * striplens, const int numstrips) { int cnt = 0; for (int i = 0; i < numstrips; i++) { int n = striplens[i] - 2; SbVec3f acc(0.0f, 0.0f, 0.0f); while (n > 0) { acc += this->faceNormals[cnt++]; n--; } (void) acc.normalize(); // use face normal array to store strip normals this->faceNormals[i] = acc; } // strip normals can now be found in faceNormals array this->faceNormals.truncate(numstrips, TRUE); this->perVertex = FALSE; } /*! Generates the normals per face. Use this when PER_FACE normal binding is needed. This method is not part of the OIV API. */ void SoNormalGenerator::generatePerFace(void) { // face normals have already been generated. Just set flag. this->perVertex = FALSE; this->faceNormals.fit(); } /*! Generates one overall normal by averaging all face normals. Use when normal binding is OVERALL. This method is not part of the OIV API. */ void SoNormalGenerator::generateOverall(void) { const int n = this->faceNormals.getLength(); const SbVec3f * normals = this->faceNormals.getArrayPtr(); SbVec3f acc(0.0f, 0.0f, 0.0f); for (int i = 0; i < n; i++) acc += normals[i]; (void) acc.normalize(); this->faceNormals.truncate(0, TRUE); this->faceNormals.append(acc); // normals are not per vertex this->perVertex = FALSE; } /*! Returns the number of normals generated. */ int SoNormalGenerator::getNumNormals(void) const { if (!this->perVertex) { return this->faceNormals.getLength(); } return this->vertexNormals.getLength(); } /*! Sets the number of generated normals. This method is not supported in Coin, and is provided for API compatibility only. */ void SoNormalGenerator::setNumNormals(const int /* num */) { COIN_OBSOLETED(); } /*! Returns a pointer to the generated normals. */ const SbVec3f * SoNormalGenerator::getNormals(void) const { if (!this->perVertex) { if (this->faceNormals.getLength()) return this->faceNormals.getArrayPtr(); return NULL; } if (this->vertexNormals.getLength()) return this->vertexNormals.getArrayPtr(); return NULL; } /*! Returns the normal at index \a i. \sa SoNormalGenerator::getNumNormals() */ const SbVec3f & SoNormalGenerator::getNormal(const int32_t i) const { assert(i >= 0 && i < this->getNumNormals()); return this->getNormals()[i]; } /*! Sets the normal at index \a index to \a normal. This method is not supported in Coin, and is provided for API compatibility only. */ void SoNormalGenerator::setNormal(const int32_t /* index */, const SbVec3f & /* normal */) { COIN_OBSOLETED(); } // // Calculates the face normal to the current face. // SbVec3f SoNormalGenerator::calcFaceNormal(void) { const int num = this->vertexList.getLength() - this->currFaceStart; assert(num >= 3); const int * cind = (const int *) this->vertexList.getArrayPtr() + this->currFaceStart; const SbVec3f * coords = this->bsp.getPointsArrayPtr(); SbVec3f ret; if (num == 3) { // triangle const SbVec3f v0 = coords[cind[0]] - coords[cind[1]]; const SbVec3f v1 = coords[cind[2]] - coords[cind[1]]; if (!this->ccw) { ret = v0.cross(v1); } else { ret = v1.cross(v0); } } else { // For non-triangle faces const SbVec3f *vert1, *vert2; ret.setValue(0.0f, 0.0f, 0.0f); vert2 = coords + cind[num-1]; for (int i = 0; i < num; i++) { vert1 = vert2; vert2 = coords + cind[i]; ret[0] += ((*vert1)[1] - (*vert2)[1]) * ((*vert1)[2] + (*vert2)[2]); ret[1] += ((*vert1)[2] - (*vert2)[2]) * ((*vert1)[0] + (*vert2)[0]); ret[2] += ((*vert1)[0] - (*vert2)[0]) * ((*vert1)[1] + (*vert2)[1]); } if (!this->ccw) ret = -ret; } if (ret.normalize() == 0.0f) { #if COIN_DEBUG // make this an optional warning since it's really ok (in most // cases) to have empty triangles. pederb, 2005-12-21 if (coin_debug_extra()) { SbString s; for (int i = 0; i < num; i++) { const SbVec3f v = coords[cind[i]]; SbString c; c.sprintf(" <%f, %f, %f>", v[0], v[1], v[2]); s += c; } SoDebugError::postWarning("SoNormalGenerator::calcFaceNormal", "Normal vector found to be of zero length " "for face with vertex coordinates:%s", s.getString()); } #endif // COIN_DEBUG // set to (0,0,0) so that this face will not influence normal smoothing ret.setValue(0.0f, 0.0f, 0.0f); } return ret; }
c++
code
13,018
3,077
/*============================================================================= Copyright (c) 2001-2014 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(SPIRIT_LIST_MARCH_24_2007_1031AM) #define SPIRIT_LIST_MARCH_24_2007_1031AM #include <boost/spirit/home/x3/core/parser.hpp> #include <boost/spirit/home/x3/support/traits/container_traits.hpp> #include <boost/spirit/home/x3/support/traits/attribute_of.hpp> #include <boost/spirit/home/x3/core/detail/parse_into_container.hpp> namespace boost { namespace spirit { namespace x3 { template <typename Left, typename Right> struct list : binary_parser<Left, Right, list<Left, Right>> { typedef binary_parser<Left, Right, list<Left, Right>> base_type; static bool const handles_container = true; static bool const has_attribute = true; list(Left const& left, Right const& right) : base_type(left, right) {} template <typename Iterator, typename Context , typename RContext, typename Attribute> bool parse(Iterator& first, Iterator const& last , Context const& context, RContext& rcontext, Attribute& attr) const { // in order to succeed we need to match at least one element if (!detail::parse_into_container( this->left, first, last, context, rcontext, attr)) return false; Iterator save = first; while (this->right.parse(first, last, context, rcontext, unused) && detail::parse_into_container( this->left, first, last, context, rcontext, attr)) { save = first; } first = save; return true; } }; template <typename Left, typename Right> inline list< typename extension::as_parser<Left>::value_type , typename extension::as_parser<Right>::value_type> operator%(Left const& left, Right const& right) { return { as_parser(left), as_parser(right) }; } }}} namespace boost { namespace spirit { namespace x3 { namespace traits { template <typename Left, typename Right, typename Context> struct attribute_of<x3::list<Left, Right>, Context> : traits::build_container< typename attribute_of<Left, Context>::type> {}; }}}} #endif
c++
code
2,665
432
// step 1: clarify // // step 2: solution // // 1. find the digits can be used // 2. dfs all the times // 3. check the time is valid, and choose the smallest one which is larger than the input // // step 3: coding // // step 4: testing #include <string> #include <unordered_set> #include <iostream> using namespace std; class Solution { public: string nextTime(const string& currTime) { chars.clear(); for (int i = 0; i < 5; ++i) if (i != 2) chars.emplace(currTime[i]); string ret; string buff; dfs(currTime, 0, ret, buff); return ret; } private: void dfs(const string& currTime, int id, string& ret, string& buff) { if (id == 5) { if (buff == currTime ||!isValid(buff)) return; if (ret.empty() || (ret > currTime && buff > currTime && buff < ret) || (ret < currTime && (buff < ret || buff > currTime))) { ret = buff; return; } return; } if (id == 2) { buff.push_back(':'); dfs(currTime, id + 1, ret, buff); buff.pop_back(); return; } for (auto iter: chars) { buff.push_back(iter); dfs(currTime, id + 1, ret, buff); buff.pop_back(); } } bool isValid(const string& buff) { string hour = buff.substr(0, 2); string minute = buff.substr(3, 2); return hour >= "00" && hour <= "23" && minute >= "00" && minute <= "59"; } unordered_set<char> chars; }; int main() { Solution sln; cout << "19:34 -> " << sln.nextTime("19:34") << endl; cout << "23:59 -> " << sln.nextTime("23:59") << endl; return 0; }
c++
code
1,812
455
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE416_Use_After_Free__new_delete_char_64a.cpp Label Definition File: CWE416_Use_After_Free__new_delete.label.xml Template File: sources-sinks-64a.tmpl.cpp */ /* * @description * CWE: 416 Use After Free * BadSource: Allocate data using new, initialize memory block, and Deallocate data using delete * GoodSource: Allocate data using new and initialize memory block * Sinks: * GoodSink: Do nothing * BadSink : Use data after free() * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE416_Use_After_Free__new_delete_char_64 { #ifndef OMITBAD /* bad function declaration */ void bad_sink(void * void_data_ptr); void bad() { char * data; /* Initialize data */ data = NULL; data = new char; *data = 'A'; /* POTENTIAL FLAW: Delete data in the source - the bad sink attempts to use data */ delete data; bad_sink(&data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2B_sink(void * void_data_ptr); static void goodG2B() { char * data; /* Initialize data */ data = NULL; data = new char; *data = 'A'; /* FIX: Do not delete data in the source */ goodG2B_sink(&data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2G_sink(void * void_data_ptr); static void goodB2G() { char * data; /* Initialize data */ data = NULL; data = new char; *data = 'A'; /* POTENTIAL FLAW: Delete data in the source - the bad sink attempts to use data */ delete data; goodB2G_sink(&data); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } // close namespace /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE416_Use_After_Free__new_delete_char_64; // so that we can use good and bad easily int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
c++
code
2,693
565
#include <iostream> #include <vector> #include <cmath> using namespace std; int main() { int n; while (cin >> n) { if (n == 0) break; if (n == 1) { int num; cin >> num; cout << "Jolly" << endl; continue; } vector <int> v(n); vector <char> used(n, false); int num1, num2; cin >> num1; for (int i = 1; i < n; ++i) { cin >> num2; if (abs(num2 - num1) > 0 && abs(num2 - num1) <= n) used[abs(num2 - num1) - 1] = true; num1 = num2; } bool ans = true; for (int i = 0; i < n - 1; ++i) if (!used[i]) { ans = false; break; } if (ans) cout << "Jolly"; else cout << "Not jolly"; cout << endl; } }
c++
code
712
230
// // basic_raw_socket.cpp // ~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Disable autolinking for unit tests. #if !defined(BOOST_ALL_NO_LIB) #define BOOST_ALL_NO_LIB 1 #endif // !defined(BOOST_ALL_NO_LIB) // AssetsWarpper that header file is self-contained. #include "asio/basic_raw_socket.hpp" #include "unit_test.hpp" ASIO_TEST_SUITE ( "basic_raw_socket", ASIO_TEST_CASE(null_test) )
c++
code
614
103
/***************************************************************************** * * Copyright (c) 2000 - 2019, Lawrence Livermore National Security, LLC * Produced at the Lawrence Livermore National Laboratory * LLNL-CODE-442911 * All rights reserved. * * This file is part of VisIt. For details, see https://visit.llnl.gov/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * 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 disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or other materials provided with the distribution. * - Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, * LLC, THE U.S. DEPARTMENT OF ENERGY 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. * *****************************************************************************/ // **************************************************************************** // Purpose: This file is a set of routines that can set/get values from // QWidget/DataNode. This allows us to use custom UI components. We // could even use them to create DataNodes that AttributeSubjects // could use to initialize themselves, which would open the door to // plots with UI's created with Qt designer. It would also mean that // we might not need Qt to build new UI's at all, which would be a // plus on systems where you have to pay for QT. // // // Notes: // // Programmer: Brad Whitlock // Creation: Fri Oct 6 17:35:57 PST 2006 // // Modifications: // // **************************************************************************** #include <DataNode.h> #include <QButtonGroup> #include <QCheckBox> #include <QComboBox> #include <QLineEdit> #include <QObjectList> #include <QSpinBox> #include <QTextEdit> #include <QvisColorButton.h> #include <QvisDialogLineEdit.h> #include <QvisVariableButton.h> #include <DebugStream.h> void ConvertTextToDataNodeSettings(const QString &text, DataNode *node) { } // **************************************************************************** // Function: DataNodeToBool // // Purpose: // Converts a data node value into a bool // // Arguments: // node : The node to evaluate. // // Returns: The converted bool value. // // Note: // // Programmer: Brad Whitlock // Creation: Fri Nov 17 10:37:19 PDT 2006 // // Modifications: // // **************************************************************************** static bool DataNodeToBool(DataNode *node) { bool ret = false; switch(node->GetNodeType()) { case CHAR_NODE: ret = node->AsChar() > 0; break; case UNSIGNED_CHAR_NODE: ret = node->AsUnsignedChar() > 0; break; case INT_NODE: ret = node->AsInt() > 0; break; case LONG_NODE: ret = node->AsLong() > 0L; break; case FLOAT_NODE: ret = node->AsFloat() > 0.f; break; case DOUBLE_NODE: ret = node->AsDouble() > 0.; break; case STRING_NODE: ret = node->AsString() == "TRUE" || node->AsString() == "true"; break; case BOOL_NODE: ret = node->AsBool(); break; default: ret = false; } return ret; } // **************************************************************************** // Function: DataNodeToInt // // Purpose: // Converts a data node into an int. // // Arguments: // node : The node to convert. // // Returns: The int value of the data node. // // Note: // // Programmer: Brad Whitlock // Creation: Fri Nov 17 10:37:54 PDT 2006 // // Modifications: // // **************************************************************************** static int DataNodeToInt(DataNode *node) { int ret = 0; switch(node->GetNodeType()) { case CHAR_NODE: ret = int(node->AsChar()); break; case UNSIGNED_CHAR_NODE: ret = int(node->AsUnsignedChar()); break; case INT_NODE: ret = node->AsInt(); break; case LONG_NODE: ret = int(node->AsLong()); break; case FLOAT_NODE: ret = int(node->AsFloat()); break; case DOUBLE_NODE: ret = int(node->AsDouble()); break; case STRING_NODE: { int tmp; if(sscanf(node->AsString().c_str(), "%d", &tmp) == 1) ret = tmp; else ret = 0; } break; case BOOL_NODE: ret = node->AsBool() ? 1 : 0; break; default: ret = 0; } return ret; } // **************************************************************************** // Function: DataNodeToQString // // Purpose: // Converts the data node into a QString. // // Arguments: // node : The data node to convert. // // Returns: The QString representation of the data node. // // Note: // // Programmer: Brad Whitlock // Creation: Fri Nov 17 10:38:27 PDT 2006 // // Modifications: // // **************************************************************************** QString DataNodeToQString(const DataNode *node) { QString s, tmp; int i; #define ARRAY_TO_STRING(Type, Method, Fmt, suffix)\ {\ const Type *ptr = node->Method();\ for(i = 0; i < node->GetLength(); ++i)\ {\ tmp.sprintf(Fmt, ptr[i] suffix);\ if(i > 0)\ s += " ";\ s += tmp;\ }\ } #define VECTOR_TO_STRING(Type, Method, Fmt, suffix)\ {\ const Type &vec = node->Method();\ for(size_t i = 0; i < vec.size(); ++i)\ {\ tmp.sprintf(Fmt, vec[i] suffix);\ if(i > 0)\ s += " ";\ s += tmp;\ }\ } switch(node->GetNodeType()) { case INTERNAL_NODE: break; case CHAR_NODE: s.sprintf("%d", (int)node->AsChar()); break; case UNSIGNED_CHAR_NODE: s.sprintf("%d", (int)node->AsUnsignedChar()); break; case INT_NODE: s.sprintf("%d", node->AsInt()); break; case LONG_NODE: s.sprintf("%ld", node->AsLong()); break; case FLOAT_NODE: s.sprintf("%f", node->AsFloat()); break; case DOUBLE_NODE: s.sprintf("%lg", node->AsDouble()); break; case STRING_NODE: s.sprintf("%s", node->AsString().c_str()); break; case BOOL_NODE: if(node->AsBool()) s = "true"; else s = "false"; break; case CHAR_ARRAY_NODE: { const char *cptr = node->AsCharArray(); for(i = 0; i < node->GetLength(); ++i) { tmp.sprintf("%d", (int)cptr[i]); if(i > 0) s += " "; s += tmp; } } break; case UNSIGNED_CHAR_ARRAY_NODE: { const unsigned char *cptr = node->AsUnsignedCharArray(); for(i = 0; i < node->GetLength(); ++i) { tmp.sprintf("%d", (int)cptr[i]); if(i > 0) s += " "; s += tmp; } } break; case INT_ARRAY_NODE: ARRAY_TO_STRING(int, AsIntArray, "%d",); break; case LONG_ARRAY_NODE: ARRAY_TO_STRING(long, AsLongArray, "%ld",); break; case FLOAT_ARRAY_NODE: ARRAY_TO_STRING(float, AsFloatArray, "%f",); break; case DOUBLE_ARRAY_NODE: ARRAY_TO_STRING(double, AsDoubleArray, "%lg",); break; case STRING_ARRAY_NODE: ARRAY_TO_STRING(std::string, AsStringArray, "\"%s\"", .c_str()); break; case BOOL_ARRAY_NODE: { const bool *ptr = node->AsBoolArray(); for(i = 0; i < node->GetLength(); ++i) { if(ptr[i]) tmp = "true"; else tmp = "false"; if(i > 0) s += " "; s += tmp; } } break; case CHAR_VECTOR_NODE: { const charVector &vec = node->AsCharVector(); for(size_t i = 0; i < vec.size(); ++i) { tmp.sprintf("%d", (int)vec[i]); if(i > 0) s += " "; s += tmp; } } break; case UNSIGNED_CHAR_VECTOR_NODE: { const unsignedCharVector &vec = node->AsUnsignedCharVector(); for(size_t i = 0; i < vec.size(); ++i) { tmp.sprintf("%d", (int)vec[i]); if(i > 0) s += " "; s += tmp; } } break; case INT_VECTOR_NODE: VECTOR_TO_STRING(intVector, AsIntVector, "%d",); break; case LONG_VECTOR_NODE: VECTOR_TO_STRING(longVector, AsLongVector, "%ld",); break; case FLOAT_VECTOR_NODE: VECTOR_TO_STRING(floatVector, AsFloatVector, "%f",); break; case DOUBLE_VECTOR_NODE: VECTOR_TO_STRING(doubleVector, AsDoubleVector, "%lg",); break; case STRING_VECTOR_NODE: VECTOR_TO_STRING(stringVector, AsStringVector, "\"%s\"", .c_str()); break; default: break; } #undef ARRAY_TO_STRING #undef VECTOR_TO_STRING return s; } // **************************************************************************** // Function: DataNodeToQColor // // Purpose: // Converts a data node representation of color into a QColor. // // Arguments: // node : The data to convert to QColor. // color : The return QColor object. // // Returns: True on success; False otherwise. // // Note: // // Programmer: Brad Whitlock // Creation: Thu Nov 16 13:34:12 PST 2006 // // Modifications: // // **************************************************************************** bool DataNodeToQColor(DataNode *node, QColor &color) { bool retval = true; int i, rgb[3] = {0, 0, 0}; float f_rgb[3] = {0., 0., 0.}; bool fp = false; #define ARRAY_TO_RGB(Rgb, Type, Method, Cast) \ if(node->GetLength() >= 3) \ { \ const Type *ptr = node->Method();\ for(i = 0; i < 3; ++i) \ Rgb[i] = Cast ptr[i]; \ } #define VECTOR_TO_RGB(Rgb, Type, Method, Cast) \ { \ const Type &vec = node->Method(); \ if(vec.size() >= 3) \ { \ for(i = 0; i < 3; ++i) \ Rgb[i] = Cast vec[i]; \ } \ } switch(node->GetNodeType()) { case CHAR_ARRAY_NODE: ARRAY_TO_RGB(rgb, char, AsCharArray, (int)); break; case UNSIGNED_CHAR_ARRAY_NODE: ARRAY_TO_RGB(rgb, unsigned char, AsUnsignedCharArray, (int)); break; case INT_ARRAY_NODE: ARRAY_TO_RGB(rgb, int, AsIntArray, (int)); break; case LONG_ARRAY_NODE: ARRAY_TO_RGB(rgb, long, AsLongArray, (int)); break; case FLOAT_ARRAY_NODE: ARRAY_TO_RGB(f_rgb, float, AsFloatArray, (float)); fp = true; break; case DOUBLE_ARRAY_NODE: ARRAY_TO_RGB(f_rgb, double, AsDoubleArray, (float)); fp = true; break; case CHAR_VECTOR_NODE: VECTOR_TO_RGB(rgb, charVector, AsCharVector, (int)); break; case UNSIGNED_CHAR_VECTOR_NODE: VECTOR_TO_RGB(rgb, unsignedCharVector, AsUnsignedCharVector, (int)); break; case INT_VECTOR_NODE: VECTOR_TO_RGB(rgb, intVector, AsIntVector, (int)); break; case LONG_VECTOR_NODE: VECTOR_TO_RGB(rgb, longVector, AsLongVector, (int)); break; case FLOAT_VECTOR_NODE: VECTOR_TO_RGB(f_rgb, floatVector, AsFloatVector, (float)); fp = true; break; case DOUBLE_VECTOR_NODE: VECTOR_TO_RGB(f_rgb, doubleVector, AsDoubleVector, (float)); fp = true; break; default: retval = false; break; } #undef ARRAY_TO_RGB #undef VECTOR_TO_RGB #define COLOR_CLAMP(C) (((C < 0) ? 0 : C) > 255) ? 255 : ((C < 0) ? 0 : C); if(retval) { if(fp) { rgb[0] = int(f_rgb[0] * 255.); rgb[1] = int(f_rgb[1] * 255.); rgb[2] = int(f_rgb[2] * 255.); } rgb[0] = COLOR_CLAMP(rgb[0]); rgb[1] = COLOR_CLAMP(rgb[1]); rgb[2] = COLOR_CLAMP(rgb[2]); color = QColor(rgb[0], rgb[1], rgb[2]); } #undef COLOR_CLAMP return retval; } // **************************************************************************** // Method: QColorToDataNode // // Purpose: // This function inserts a color into a data node. // // Arguments: // node : The node into which we're inserting the color. // key : The name of the new color node. // c : The color to insert. // // Programmer: Brad Whitlock // Creation: Thu Nov 16 13:35:18 PST 2006 // // Modifications: // // **************************************************************************** void QColorToDataNode(DataNode *node, const char *key, const QColor &c) { int tmp[3]; tmp[0] = c.red(); tmp[1] = c.green(); tmp[2] = c.blue(); node->RemoveNode(key); node->AddNode(new DataNode(key, tmp, 3)); } // **************************************************************************** // Method: InitializeQComboBoxFromDataNode // // Purpose: // Initializes a QComboBox from a DataNode // // Arguments: // obj : The QComboBox to initialize. // node : The DataNode to use for initialization. // // Programmer: Brad Whitlock // Creation: Thu Nov 16 14:07:48 PST 2006 // // Modifications: // Brad Whitlock, Tue Oct 7 10:32:39 PDT 2008 // Qt 4. // // **************************************************************************** static void InitializeQComboBoxFromDataNode(QComboBox *co, DataNode *node) { if(node->GetNodeType() == INT_NODE) { int index = node->AsInt(); if(index < 0 || index >= co->count()) { debug1 << node->GetKey().c_str() << " is out of range [0," << co->count() << "]" << endl; index = 0; } co->setCurrentIndex(index); } else if(node->GetNodeType() == STRING_NODE) { for(int i = 0; i < co->count(); ++i) { if(co->itemText(i).toStdString() == node->AsString()) { co->setCurrentIndex(i); return; } } debug1 << node->GetKey().c_str() << " value of " << node->AsString().c_str() << " does not match any of the items in the QComboBox." << endl; } else { debug1 << "InitializeQComboBoxFromDataNode: only supports INT_NODE, STRING_NODE" << endl; } } // **************************************************************************** // Function: InitializeDataNodeFromQComboBox // // Purpose: // Initializes a data node from the active item in a QComboBox. // // Arguments: // co : The combo box that we're considering. // node : The parent of the node that we'll create. // // Programmer: Brad Whitlock // Creation: Thu Nov 16 14:16:16 PST 2006 // // Modifications: // Brad Whitlock, Tue Oct 7 10:38:19 PDT 2008 // Qt 4. // // **************************************************************************** static void InitializeDataNodeFromQComboBox(QComboBox *co, DataNode *node) { std::string objectName(co->objectName().toStdString()); DataNode *currentNode = node->GetNode(objectName); if(currentNode != 0) { // Use int or string, depending on what the node was initially. NodeTypeEnum t = currentNode->GetNodeType(); if(t != INT_NODE && t != STRING_NODE) { debug1 << "InitializeDataNodeFromQComboBox: only supports INT_NODE, STRING_NODE" << endl; t = INT_NODE; } node->RemoveNode(objectName); if(t == INT_NODE) node->AddNode(new DataNode(objectName, co->currentIndex())); else if(t == STRING_NODE) { node->AddNode(new DataNode(objectName, co->currentText().toStdString())); } } else { // There's no preference on which type to use so use int. node->AddNode(new DataNode(objectName, co->currentIndex())); } } // **************************************************************************** // Function: InitializeQCheckBoxFromDataNode // // Purpose: // Initializes a QCheckBox from a data node. // // Arguments: // co : The check box to initialize. // node : The data node to use for values. // // Programmer: Brad Whitlock // Creation: Fri Nov 17 10:40:22 PDT 2006 // // Modifications: // // **************************************************************************** static void InitializeQCheckBoxFromDataNode(QCheckBox *co, DataNode *node) { co->setChecked(DataNodeToBool(node)); } // **************************************************************************** // Method: InitializeDataNodeFromQCheckBox // // Purpose: // Initialize a data node from a QCheckBox. // // Arguments: // co : The check box from which to get the bool. // node : The node that will get the new bool value. // // Programmer: Brad Whitlock // Creation: Fri Nov 17 10:41:00 PDT 2006 // // Modifications: // // **************************************************************************** static void InitializeDataNodeFromQCheckBox(QCheckBox *co, DataNode *node) { std::string objectName(co->objectName().toStdString()); node->RemoveNode(objectName); node->AddNode(new DataNode(objectName, co->isChecked())); } // **************************************************************************** // Function: InitializeQButtonGroupFromDataNode // // Purpose: // Initializes a QButtonGroup from a data node. // // Arguments: // co : The button group to initialize. // node : The data node to use for initialization. // // Programmer: Brad Whitlock // Creation: Fri Nov 17 10:41:50 PDT 2006 // // Modifications: // Brad Whitlock, Tue Oct 7 10:37:40 PDT 2008 // Qt 4. // // **************************************************************************** static void InitializeQButtonGroupFromDataNode(QButtonGroup *co, DataNode *node) { int index = DataNodeToInt(node); if(co->button(index) != 0) co->button(index)->setChecked(true); } // ****************************************************************************
c++
code
19,999
5,814
// Tags: Math // Difficulty: 5.5 // Priority: 1 // Date: 04-05-2021 #include <bits/stdc++.h> #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef vector <int> vi; typedef vector <ll> vll; typedef vector <pii> vpii; typedef vector <pll> vpll; int main () { ios::sync_with_stdio(false); cin.tie(0); ll p, k; cin >> p >> k; // find p in base (-k) k *= -1; vi ans; while (p != 0) { // p = q * k + r ll q = p / k; ll r = p - q * k; if (r < 0) { r += -k; q += 1; } ans.pb(r); p = q; } cout << sz(ans) << '\n'; for (int i = 0; i < sz(ans); i++) cout << ans[i] << " \n"[i + 1 == sz(ans)]; return (0); }
c++
code
867
299
//================================================================================================= /*! // \file src/mathtest/smatdmatadd/MZbMUb.cpp // \brief Source file for the MZbMUb sparse matrix/dense matrix addition math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/UniformMatrix.h> #include <blaze/math/ZeroMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatdmatadd/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MZbMUb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions using MZb = blaze::ZeroMatrix<TypeB>; using MUb = blaze::UniformMatrix<TypeB>; // Creator type definitions using CMZb = blazetest::Creator<MZb>; using CMUb = blazetest::Creator<MUb>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=6UL; ++j ) { RUN_SMATDMATADD_OPERATION_TEST( CMZb( i, j ), CMUb( i, j ) ); } } // Running tests with large matrices RUN_SMATDMATADD_OPERATION_TEST( CMZb( 67UL, 67UL ), CMUb( 67UL, 67UL ) ); RUN_SMATDMATADD_OPERATION_TEST( CMZb( 67UL, 127UL ), CMUb( 67UL, 127UL ) ); RUN_SMATDMATADD_OPERATION_TEST( CMZb( 128UL, 64UL ), CMUb( 128UL, 64UL ) ); RUN_SMATDMATADD_OPERATION_TEST( CMZb( 128UL, 128UL ), CMUb( 128UL, 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/dense matrix addition:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
c++
code
4,228
1,060
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <netaddress.h> #include <hash.h> #include <util/strencodings.h> #include <tinyformat.h> static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff }; static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43}; // 0xFD + sha256("scoutcoin")[0:5] static const unsigned char g_internal_prefix[] = { 0xFD, 0x6C, 0xE9, 0xFE, 0x45, 0x49 }; CNetAddr::CNetAddr() { memset(ip, 0, sizeof(ip)); } void CNetAddr::SetIP(const CNetAddr& ipIn) { memcpy(ip, ipIn.ip, sizeof(ip)); } void CNetAddr::SetRaw(Network network, const uint8_t *ip_in) { switch(network) { case NET_IPV4: memcpy(ip, pchIPv4, 12); memcpy(ip+12, ip_in, 4); break; case NET_IPV6: memcpy(ip, ip_in, 16); break; default: assert(!"invalid network"); } } bool CNetAddr::SetInternal(const std::string &name) { if (name.empty()) { return false; } unsigned char hash[32] = {}; CSHA256().Write((const unsigned char*)name.data(), name.size()).Finalize(hash); memcpy(ip, g_internal_prefix, sizeof(g_internal_prefix)); memcpy(ip + sizeof(g_internal_prefix), hash, sizeof(ip) - sizeof(g_internal_prefix)); return true; } bool CNetAddr::SetSpecial(const std::string &strName) { if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") { std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str()); if (vchAddr.size() != 16-sizeof(pchOnionCat)) return false; memcpy(ip, pchOnionCat, sizeof(pchOnionCat)); for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++) ip[i + sizeof(pchOnionCat)] = vchAddr[i]; return true; } return false; } CNetAddr::CNetAddr(const struct in_addr& ipv4Addr) { SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr); } CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr, const uint32_t scope) { SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr); scopeId = scope; } unsigned int CNetAddr::GetByte(int n) const { return ip[15-n]; } bool CNetAddr::IsBindAny() const { const int cmplen = IsIPv4() ? 4 : 16; for (int i = 0; i < cmplen; ++i) { if (GetByte(i)) return false; } return true; } bool CNetAddr::IsIPv4() const { return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0); } bool CNetAddr::IsIPv6() const { return (!IsIPv4() && !IsTor() && !IsInternal()); } bool CNetAddr::IsRFC1918() const { return IsIPv4() && ( GetByte(3) == 10 || (GetByte(3) == 192 && GetByte(2) == 168) || (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31))); } bool CNetAddr::IsRFC2544() const { return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19); } bool CNetAddr::IsRFC3927() const { return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254); } bool CNetAddr::IsRFC6598() const { return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127; } bool CNetAddr::IsRFC5737() const { return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) || (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) || (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113)); } bool CNetAddr::IsRFC3849() const { return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8; } bool CNetAddr::IsRFC3964() const { return (GetByte(15) == 0x20 && GetByte(14) == 0x02); } bool CNetAddr::IsRFC6052() const { static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0}; return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0); } bool CNetAddr::IsRFC4380() const { return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0); } bool CNetAddr::IsRFC4862() const { static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0}; return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0); } bool CNetAddr::IsRFC4193() const { return ((GetByte(15) & 0xFE) == 0xFC); } bool CNetAddr::IsRFC6145() const { static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0}; return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0); } bool CNetAddr::IsRFC4843() const { return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10); } bool CNetAddr::IsTor() const { return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0); } bool CNetAddr::IsLocal() const { // IPv4 loopback (127.0.0.0/8 or 0.0.0.0/8) if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0)) return true; // IPv6 loopback (::1/128) static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; if (memcmp(ip, pchLocal, 16) == 0) return true; return false; } bool CNetAddr::IsValid() const { // Cleanup 3-byte shifted addresses caused by garbage in size field // of addr messages from versions before 0.2.9 checksum. // Two consecutive addr messages look like this: // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26... // so if the first length field is garbled, it reads the second batch // of addr misaligned by 3 bytes. if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0) return false; // unspecified IPv6 address (::/128) unsigned char ipNone6[16] = {}; if (memcmp(ip, ipNone6, 16) == 0) return false; // documentation IPv6 address if (IsRFC3849()) return false; if (IsInternal()) return false; if (IsIPv4()) { // INADDR_NONE uint32_t ipNone = INADDR_NONE; if (memcmp(ip+12, &ipNone, 4) == 0) return false; // 0 ipNone = 0; if (memcmp(ip+12, &ipNone, 4) == 0) return false; } return true; } bool CNetAddr::IsRoutable() const { return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal() || IsInternal()); } bool CNetAddr::IsInternal() const { return memcmp(ip, g_internal_prefix, sizeof(g_internal_prefix)) == 0; } enum Network CNetAddr::GetNetwork() const { if (IsInternal()) return NET_INTERNAL; if (!IsRoutable()) return NET_UNROUTABLE; if (IsIPv4()) return NET_IPV4; if (IsTor()) return NET_ONION; return NET_IPV6; } std::string CNetAddr::ToStringIP() const { if (IsTor()) return EncodeBase32(&ip[6], 10) + ".onion"; if (IsInternal()) return EncodeBase32(ip + sizeof(g_internal_prefix), sizeof(ip) - sizeof(g_internal_prefix)) + ".internal"; CService serv(*this, 0); struct sockaddr_storage sockaddr; socklen_t socklen = sizeof(sockaddr); if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) { char name[1025] = ""; if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), nullptr, 0, NI_NUMERICHOST)) return std::string(name); } if (IsIPv4()) return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0)); else return strprintf("%x:%x:%x:%x:%x:%x:%x:%x", GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12), GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8), GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4), GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0)); } std::string CNetAddr::ToString() const { return ToStringIP(); } bool operator==(const CNetAddr& a, const CNetAddr& b) { return (memcmp(a.ip, b.ip, 16) == 0); } bool operator<(const CNetAddr& a, const CNetAddr& b) { return (memcmp(a.ip, b.ip, 16) < 0); } bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const { if (!IsIPv4()) return false; memcpy(pipv4Addr, ip+12, 4); return true; } bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const { if (!IsIPv6()) { return false; } memcpy(pipv6Addr, ip, 16); return true; } // get canonical identifier of an address' group // no two connections will be attempted to addresses with the same group std::vector<unsigned char> CNetAddr::GetGroup() const { std::vector<unsigned char> vchRet; int nClass = NET_IPV6; int nStartByte = 0; int nBits = 16; // all local addresses belong to the same group if (IsLocal()) { nClass = 255; nBits = 0; } // all internal-usage addresses get their own group if (IsInternal()) { nClass = NET_INTERNAL; nStartByte = sizeof(g_internal_prefix); nBits = (sizeof(ip) - sizeof(g_internal_prefix)) * 8; } // all other unroutable addresses belong to the same group else if (!IsRoutable()) { nClass = NET_UNROUTABLE; nBits = 0; } // for IPv4 addresses, '1' + the 16 higher-order bits of the IP // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix else if (IsIPv4() || IsRFC6145() || IsRFC6052()) { nClass = NET_IPV4; nStartByte = 12; } // for 6to4 tunnelled addresses, use the encapsulated IPv4 address else if (IsRFC3964()) { nClass = NET_IPV4; nStartByte = 2; } // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address else if (IsRFC4380()) { vchRet.push_back(NET_IPV4); vchRet.push_back(GetByte(3) ^ 0xFF); vchRet.push_back(GetByte(2) ^ 0xFF); return vchRet; } else if (IsTor()) { nClass = NET_ONION; nStartByte = 6; nBits = 4; } // for he.net, use /36 groups else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70) nBits = 36; // for the rest of the IPv6 network, use /32 groups else nBits = 32; vchRet.push_back(nClass); while (nBits >= 8) { vchRet.push_back(GetByte(15 - nStartByte)); nStartByte++; nBits -= 8; } if (nBits > 0) vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1)); return vchRet; } uint64_t CNetAddr::GetHash() const { uint256 hash = Hash(&ip[0], &ip[16]); uint64_t nRet; memcpy(&nRet, &hash, sizeof(nRet)); return nRet; } // private extensions to enum Network, only returned by GetExtNetwork, // and only used in GetReachabilityFrom static const int NET_UNKNOWN = NET_MAX + 0; static const int NET_TEREDO = NET_MAX + 1; int static GetExtNetwork(const CNetAddr *addr) { if (addr == nullptr) return NET_UNKNOWN; if (addr->IsRFC4380()) return NET_TEREDO; return addr->GetNetwork(); } /** Calculates a metric for how reachable (*this) is from a given partner */ int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const { enum Reachability { REACH_UNREACHABLE, REACH_DEFAULT, REACH_TEREDO, REACH_IPV6_WEAK, REACH_IPV4, REACH_IPV6_STRONG, REACH_PRIVATE }; if (!IsRoutable() || IsInternal()) return REACH_UNREACHABLE; int ourNet = GetExtNetwork(this); int theirNet = GetExtNetwork(paddrPartner); bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145(); switch(theirNet) { case NET_IPV4: switch(ourNet) { default: return REACH_DEFAULT; case NET_IPV4: return REACH_IPV4; } case NET_IPV6: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV4: return REACH_IPV4; case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled } case NET_ONION: switch(ourNet) { default: return REACH_DEFAULT; case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well case NET_ONION: return REACH_PRIVATE; } case NET_TEREDO: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; } case NET_UNKNOWN: case NET_UNROUTABLE: default: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; case NET_ONION: return REACH_PRIVATE; // either from Tor, or don't care about our address } } } CService::CService() : port(0) { } CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn) { } CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn) { } CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn) { } CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port)) { assert(addr.sin_family == AF_INET); } CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port)) { assert(addr.sin6_family == AF_INET6); } bool CService::SetSockAddr(const struct sockaddr *paddr) { switch (paddr->sa_family) { case AF_INET: *this = CService(*(const struct sockaddr_in*)paddr); return true; case AF_INET6: *this = CService(*(const struct sockaddr_in6*)paddr); return true; default: return false; } } unsigned short CService::GetPort() const { return port; } bool operator==(const CService& a, const CService& b) { return static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port == b.port; } bool operator<(const CService& a, const CService& b) { return static_cast<CNetAddr>(a) < static_cast<CNetAddr>(b) || (static_cast<CNetAddr>(a) == static_cast<CNetAddr>(b) && a.port < b.port); } bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const { if (IsIPv4()) { if (*addrlen < (socklen_t)sizeof(struct sockaddr_in)) return false; *addrlen = sizeof(struct sockaddr_in); struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr; memset(paddrin, 0, *addrlen); if (!GetInAddr(&paddrin->sin_addr)) return false; paddrin->sin_family = AF_INET; paddrin->sin_port = htons(port); return true; } if (IsIPv6()) { if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6)) return false; *addrlen = sizeof(struct sockaddr_in6); struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr; memset(paddrin6, 0, *addrlen); if (!GetIn6Addr(&paddrin6->sin6_addr)) return false; paddrin6->sin6_scope_id = scopeId; paddrin6->sin6_family = AF_INET6; paddrin6->sin6_port = htons(port); return true; } return false; } std::vector<unsigned char> CService::GetKey() const { std::vector<unsigned char> vKey; vKey.resize(18); memcpy(vKey.data(), ip, 16); vKey[16] = port / 0x100; vKey[17] = port & 0x0FF; return vKey; } std::string CService::ToStringPort() const { return strprintf("%u", port); } std::string CService::ToStringIPPort() const { if (IsIPv4() || IsTor() || IsInternal()) { return ToStringIP() + ":" + ToStringPort(); } else { return "[" + ToStringIP() + "]:" + ToStringPort(); } } std::string CService::ToString() const { return ToStringIPPort(); } CSubNet::CSubNet(): valid(false) { memset(netmask, 0, sizeof(netmask)); } CSubNet::CSubNet(const CNetAddr &addr, int32_t mask) { valid = true; network = addr; // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address memset(netmask, 255, sizeof(netmask)); // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n const int astartofs = network.IsIPv4() ? 12 : 0; int32_t n = mask; if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address { n += astartofs*8; // Clear bits [n..127] for (; n < 128; ++n) netmask[n>>3] &= ~(1<<(7-(n&7))); } else valid = false; // Normalize network according to netmask for(int x=0; x<16; ++x) network.ip[x] &= netmask[x]; } CSubNet::CSubNet(const CNetAddr &addr, const CNetAddr &mask) { valid = true; network = addr; // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address memset(netmask, 255, sizeof(netmask)); // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n const int astartofs = network.IsIPv4() ? 12 : 0; for(int x=astartofs; x<16; ++x) netmask[x] = mask.ip[x]; // Normalize network according to netmask for(int x=0; x<16; ++x) network.ip[x] &= netmask[x]; } CSubNet::CSubNet(const CNetAddr &addr): valid(addr.IsValid()) { memset(netmask, 255, sizeof(netmask)); network = addr; } bool CSubNet::Match(const CNetAddr &addr) const { if (!valid || !addr.IsValid()) return false; for(int x=0; x<16; ++x) if ((addr.ip[x] & netmask[x]) != network.ip[x]) return false; return true; } static inline int NetmaskBits(uint8_t x) { switch(x) { case 0x00: return 0; case 0x80: return 1; case 0xc0: return 2; case 0xe0: return 3; case 0xf0: return 4; case 0xf8: return 5; case 0xfc: return 6; case 0xfe: return 7; case 0xff: return 8; default: return -1; } } std::string CSubNet::ToString() const { /* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */ int cidr = 0; bool valid_cidr = true; int n = network.IsIPv4() ? 12 : 0; for (; n < 16 && netmask[n] == 0xff; ++n) cidr += 8; if (n < 16) { int bits = NetmaskBits(netmask[n]); if (bits < 0) valid_cidr = false; else cidr += bits; ++n; } for (; n < 16 && valid_cidr; ++n) if (netmask[n] != 0x00) valid_cidr = false; /* Format output */ std::string strNetmask; if (valid_cidr) { strNetmask = strprintf("%u", cidr); } else { if (network.IsIPv4()) strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]); else strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x", netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3], netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7], netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11], netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]); } return network.ToString() + "/" + strNetmask; } bool CSubNet::IsValid() const { return valid; } bool operator==(const CSubNet& a, const CSubNet& b) { return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16); } bool operator<(const CSubNet& a, const CSubNet& b) { return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0)); }
c++
code
19,923
5,113
// Copyright (C) 2020-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vector> #include "single_layer_tests/gather_tree.hpp" #include "common_test_utils/test_constants.hpp" using namespace LayerTestsDefinitions; namespace { const std::vector<InferenceEngine::Precision> netPrecisions = { InferenceEngine::Precision::FP32, InferenceEngine::Precision::FP16, InferenceEngine::Precision::I32, }; const std::vector<std::vector<size_t>> inputShapes = { {5, 1, 10}, {1, 1, 10}, {20, 1, 10}, {20, 20, 10} }; const std::vector<ngraph::helpers::InputLayerType> secondaryInputTypes = { ngraph::helpers::InputLayerType::CONSTANT, ngraph::helpers::InputLayerType::PARAMETER }; INSTANTIATE_TEST_CASE_P(smoke_GatherTree, GatherTreeLayerTest, ::testing::Combine( ::testing::ValuesIn(inputShapes), ::testing::ValuesIn(secondaryInputTypes), ::testing::ValuesIn(netPrecisions), ::testing::Values(InferenceEngine::Precision::UNSPECIFIED), ::testing::Values(InferenceEngine::Precision::UNSPECIFIED), ::testing::Values(InferenceEngine::Layout::ANY), ::testing::Values(InferenceEngine::Layout::ANY), ::testing::Values(CommonTestUtils::DEVICE_CPU)), GatherTreeLayerTest::getTestCaseName); } // namespace
c++
code
1,527
294
// // Created by DefTruth on 2021/12/30. // #include "mnn_scrfd.h" using mnncv::MNNSCRFD; MNNSCRFD::MNNSCRFD(const std::string &_mnn_path, unsigned int _num_threads) : BasicMNNHandler(_mnn_path, _num_threads) { initialize_pretreat(); initial_context(); } inline void MNNSCRFD::initialize_pretreat() { pretreat = std::shared_ptr<MNN::CV::ImageProcess>( MNN::CV::ImageProcess::create( MNN::CV::BGR, MNN::CV::RGB, mean_vals, 3, norm_vals, 3 ) ); } void MNNSCRFD::initial_context() { if (num_outputs == 6) { fmc = 3; feat_stride_fpn = {8, 16, 32}; num_anchors = 2; use_kps = false; } // kps else if (num_outputs == 9) { fmc = 3; feat_stride_fpn = {8, 16, 32}; num_anchors = 2; use_kps = true; } } inline void MNNSCRFD::transform(const cv::Mat &mat_rs) { pretreat->convert(mat_rs.data, input_width, input_height, mat_rs.step[0], input_tensor); } void MNNSCRFD::resize_unscale(const cv::Mat &mat, cv::Mat &mat_rs, int target_height, int target_width, SCRFDScaleParams &scale_params) { if (mat.empty()) return; int img_height = static_cast<int>(mat.rows); int img_width = static_cast<int>(mat.cols); mat_rs = cv::Mat(target_height, target_width, CV_8UC3, cv::Scalar(0, 0, 0)); // scale ratio (new / old) new_shape(h,w) float w_r = (float) target_width / (float) img_width; float h_r = (float) target_height / (float) img_height; float r = std::min(w_r, h_r); // compute padding int new_unpad_w = static_cast<int>((float) img_width * r); // floor int new_unpad_h = static_cast<int>((float) img_height * r); // floor int pad_w = target_width - new_unpad_w; // >=0 int pad_h = target_height - new_unpad_h; // >=0 int dw = pad_w / 2; int dh = pad_h / 2; // resize with unscaling cv::Mat new_unpad_mat = mat.clone(); cv::resize(new_unpad_mat, new_unpad_mat, cv::Size(new_unpad_w, new_unpad_h)); new_unpad_mat.copyTo(mat_rs(cv::Rect(dw, dh, new_unpad_w, new_unpad_h))); // record scale params. scale_params.ratio = r; scale_params.dw = dw; scale_params.dh = dh; scale_params.flag = true; } void MNNSCRFD::detect(const cv::Mat &mat, std::vector<types::BoxfWithLandmarks> &detected_boxes_kps, float score_threshold, float iou_threshold, unsigned int topk) { if (mat.empty()) return; auto img_height = static_cast<float>(mat.rows); auto img_width = static_cast<float>(mat.cols); // resize & unscale cv::Mat mat_rs; SCRFDScaleParams scale_params; this->resize_unscale(mat, mat_rs, input_height, input_width, scale_params); // 1. make input tensor this->transform(mat_rs); // 2. inference scores & boxes. mnn_interpreter->runSession(mnn_session); auto output_tensors = mnn_interpreter->getSessionOutputAll(mnn_session); // 3. rescale & exclude. std::vector<types::BoxfWithLandmarks> bbox_kps_collection; this->generate_bboxes_kps(scale_params, bbox_kps_collection, output_tensors, score_threshold, img_height, img_width); // 4. hard nms with topk. this->nms_bboxes_kps(bbox_kps_collection, detected_boxes_kps, iou_threshold, topk); } void MNNSCRFD::generate_points(const int target_height, const int target_width) { if (center_points_is_update) return; // 8, 16, 32 for (auto stride : feat_stride_fpn) { unsigned int num_grid_w = target_width / stride; unsigned int num_grid_h = target_height / stride; // y for (unsigned int i = 0; i < num_grid_h; ++i) { // x for (unsigned int j = 0; j < num_grid_w; ++j) { // num_anchors, col major for (unsigned int k = 0; k < num_anchors; ++k) { SCRFDPoint point; point.cx = (float) j; point.cy = (float) i; point.stride = (float) stride; center_points[stride].push_back(point); } } } } center_points_is_update = true; } void MNNSCRFD::generate_bboxes_kps(const SCRFDScaleParams &scale_params, std::vector<types::BoxfWithLandmarks> &bbox_kps_collection, const std::map<std::string, MNN::Tensor *> &output_tensors, float score_threshold, float img_height, float img_width) { // score_8,score_16,score_32,bbox_8,bbox_16,bbox_32 auto device_score_8 = output_tensors.at("score_8"); auto device_score_16 = output_tensors.at("score_16"); auto device_score_32 = output_tensors.at("score_32"); auto device_bbox_8 = output_tensors.at("bbox_8"); auto device_bbox_16 = output_tensors.at("bbox_16"); auto device_bbox_32 = output_tensors.at("bbox_32"); this->generate_points(input_height, input_width); MNN::Tensor host_score_8(device_score_8, device_score_8->getDimensionType()); MNN::Tensor host_score_16(device_score_16, device_score_16->getDimensionType()); MNN::Tensor host_score_32(device_score_32, device_score_32->getDimensionType()); MNN::Tensor host_bbox_8(device_bbox_8, device_bbox_8->getDimensionType()); MNN::Tensor host_bbox_16(device_bbox_16, device_bbox_16->getDimensionType()); MNN::Tensor host_bbox_32(device_bbox_32, device_bbox_32->getDimensionType()); device_score_8->copyToHostTensor(&host_score_8); device_score_16->copyToHostTensor(&host_score_16); device_score_32->copyToHostTensor(&host_score_32); device_bbox_8->copyToHostTensor(&host_bbox_8); device_bbox_16->copyToHostTensor(&host_bbox_16); device_bbox_32->copyToHostTensor(&host_bbox_32); bbox_kps_collection.clear(); if (use_kps) { auto device_kps_8 = output_tensors.at("kps_8"); auto device_kps_16 = output_tensors.at("kps_16"); auto device_kps_32 = output_tensors.at("kps_32"); MNN::Tensor host_kps_8(device_kps_8, device_kps_8->getDimensionType()); MNN::Tensor host_kps_16(device_kps_16, device_kps_16->getDimensionType()); MNN::Tensor host_kps_32(device_kps_32, device_kps_32->getDimensionType()); device_kps_8->copyToHostTensor(&host_kps_8); device_kps_16->copyToHostTensor(&host_kps_16); device_kps_32->copyToHostTensor(&host_kps_32); // level 8 & 16 & 32 with kps this->generate_bboxes_kps_single_stride(scale_params, host_score_8, host_bbox_8, host_kps_8, 8, score_threshold, img_height, img_width, bbox_kps_collection); this->generate_bboxes_kps_single_stride(scale_params, host_score_16, host_bbox_16, host_kps_16, 16, score_threshold, img_height, img_width, bbox_kps_collection); this->generate_bboxes_kps_single_stride(scale_params, host_score_32, host_bbox_32, host_kps_32, 32, score_threshold, img_height, img_width, bbox_kps_collection); } // no kps else { // level 8 & 16 & 32 this->generate_bboxes_single_stride(scale_params, host_score_8, host_bbox_8, 8, score_threshold, img_height, img_width, bbox_kps_collection); this->generate_bboxes_single_stride(scale_params, host_score_16, host_bbox_16, 16, score_threshold, img_height, img_width, bbox_kps_collection); this->generate_bboxes_single_stride(scale_params, host_score_32, host_bbox_32, 32, score_threshold, img_height, img_width, bbox_kps_collection); } #if LITEMNN_DEBUG std::cout << "generate_bboxes_kps num: " << bbox_kps_collection.size() << "\n"; #endif } void MNNSCRFD::generate_bboxes_single_stride( const SCRFDScaleParams &scale_params, MNN::Tensor &score_pred, MNN::Tensor &bbox_pred, unsigned int stride, float score_threshold, float img_height, float img_width, std::vector<types::BoxfWithLandmarks> &bbox_kps_collection) { unsigned int nms_pre_ = (stride / 8) * nms_pre; // 1 * 1000,2*1000,... nms_pre_ = nms_pre_ >= nms_pre ? nms_pre_ : nms_pre; auto stride_dims = score_pred.shape(); const unsigned int num_points = stride_dims.at(1); // 12800 const float *score_ptr = score_pred.host<float>(); // [1,12800,1] const float *bbox_ptr = bbox_pred.host<float>(); // [1,12800,4] float ratio = scale_params.ratio; int dw = scale_params.dw; int dh = scale_params.dh; unsigned int count = 0; auto &stride_points = center_points[stride]; for (unsigned int i = 0; i < num_points; ++i) { const float cls_conf = score_ptr[i]; if (cls_conf < score_threshold) continue; // filter auto &point = stride_points.at(i); const float cx = point.cx; // cx const float cy = point.cy; // cy const float s = point.stride; // stride // bbox const float *offsets = bbox_ptr + i * 4; float l = offsets[0]; // left float t = offsets[1]; // top float r = offsets[2]; // right float b = offsets[3]; // bottom types::BoxfWithLandmarks box_kps; float x1 = ((cx - l) * s - (float) dw) / ratio; // cx - l x1 float y1 = ((cy - t) * s - (float) dh) / ratio; // cy - t y1 float x2 = ((cx + r) * s - (float) dw) / ratio; // cx + r x2 float y2 = ((cy + b) * s - (float) dh) / ratio; // cy + b y2 box_kps.box.x1 = std::max(0.f, x1); box_kps.box.y1 = std::max(0.f, y1); box_kps.box.x2 = std::min(img_width, x2); box_kps.box.y2 = std::min(img_height, y2); box_kps.box.score = cls_conf; box_kps.box.label = 1; box_kps.box.label_text = "face"; box_kps.box.flag = true; box_kps.flag = true; bbox_kps_collection.push_back(box_kps); count += 1; // limit boxes for nms. if (count > max_nms) break; } if (bbox_kps_collection.size() > nms_pre_) { std::sort( bbox_kps_collection.begin(), bbox_kps_collection.end(), [](const types::BoxfWithLandmarks &a, const types::BoxfWithLandmarks &b) { return a.box.score > b.box.score; } ); // sort inplace // trunc bbox_kps_collection.resize(nms_pre_); } } void MNNSCRFD::generate_bboxes_kps_single_stride( const SCRFDScaleParams &scale_params, MNN::Tensor &score_pred, MNN::Tensor &bbox_pred, MNN::Tensor &kps_pred, unsigned int stride, float score_threshold, float img_height, float img_width, std::vector<types::BoxfWithLandmarks> &bbox_kps_collection) { unsigned int nms_pre_ = (stride / 8) * nms_pre; // 1 * 1000,2*1000,... nms_pre_ = nms_pre_ >= nms_pre ? nms_pre_ : nms_pre; auto stride_dims = score_pred.shape(); const unsigned int num_points = stride_dims.at(1); // 12800 const float *score_ptr = score_pred.host<float>(); // [1,12800,1] const float *bbox_ptr = bbox_pred.host<float>(); // [1,12800,4] const float *kps_ptr = kps_pred.host<float>(); // [1,12800,10] float ratio = scale_params.ratio; int dw = scale_params.dw; int dh = scale_params.dh; unsigned int count = 0; auto &stride_points = center_points[stride]; for (unsigned int i = 0; i < num_points; ++i) { const float cls_conf = score_ptr[i]; if (cls_conf < score_threshold) continue; // filter auto &point = stride_points.at(i); const float cx = point.cx; // cx const float cy = point.cy; // cy const float s = point.stride; // stride // bbox const float *offsets = bbox_ptr + i * 4; float l = offsets[0]; // left float t = offsets[1]; // top float r = offsets[2]; // right float b = offsets[3]; // bottom types::BoxfWithLandmarks box_kps; float x1 = ((cx - l) * s - (float) dw) / ratio; // cx - l x1 float y1 = ((cy - t) * s - (float) dh) / ratio; // cy - t y1 float x2 = ((cx + r) * s - (float) dw) / ratio; // cx + r x2 float y2 = ((cy + b) * s - (float) dh) / ratio; // cy + b y2 box_kps.box.x1 = std::max(0.f, x1); box_kps.box.y1 = std::max(0.f, y1); box_kps.box.x2 = std::min(img_width, x2); box_kps.box.y2 = std::min(img_height, y2); box_kps.box.score = cls_conf; box_kps.box.label = 1; box_kps.box.label_text = "face"; box_kps.box.flag = true; // landmarks const float *kps_offsets = kps_ptr + i * 10; for (unsigned int j = 0; j < 10; j += 2) { cv::Point2f kps; float kps_l = kps_offsets[j]; float kps_t = kps_offsets[j + 1]; float kps_x = ((cx + kps_l) * s - (float) dw) / ratio; // cx - l x float kps_y = ((cy + kps_t) * s - (float) dh) / ratio; // cy - t y kps.x = std::min(std::max(0.f, kps_x), img_width); kps.y = std::min(std::max(0.f, kps_y), img_height); box_kps.landmarks.points.push_back(kps); } box_kps.landmarks.flag = true; box_kps.flag = true; bbox_kps_collection.push_back(box_kps); count += 1; // limit boxes for nms. if (count > max_nms) break; } if (bbox_kps_collection.size() > nms_pre_) { std::sort( bbox_kps_collection.begin(), bbox_kps_collection.end(), [](const types::BoxfWithLandmarks &a, const types::BoxfWithLandmarks &b) { return a.box.score > b.box.score; } ); // sort inplace // trunc bbox_kps_collection.resize(nms_pre_); } } void MNNSCRFD::nms_bboxes_kps(std::vector<types::BoxfWithLandmarks> &input, std::vector<types::BoxfWithLandmarks> &output, float iou_threshold, unsigned int topk) { if (input.empty()) return; std::sort( input.begin(), input.end(), [](const types::BoxfWithLandmarks &a, const types::BoxfWithLandmarks &b) { return a.box.score > b.box.score; } ); const unsigned int box_num = input.size(); std::vector<int> merged(box_num, 0); unsigned int count = 0; for (unsigned int i = 0; i < box_num; ++i) { if (merged[i]) continue; std::vector<types::BoxfWithLandmarks> buf; buf.push_back(input[i]); merged[i] = 1; for (unsigned int j = i + 1; j < box_num; ++j) { if (merged[j]) continue; float iou = static_cast<float>(input[i].box.iou_of(input[j].box)); if (iou > iou_threshold) { merged[j] = 1; buf.push_back(input[j]); } } output.push_back(buf[0]); // keep top k count += 1; if (count >= topk) break; } }
c++
code
14,241
3,249
/* EPANET 3 * * Copyright (c) 2016 Open Water Analytics * Distributed under the MIT License (see the LICENSE file for details). * */ ///////////////////////////////////////////// // Implementation of the Project class. // //////////////////////////////////////////// #include "project.h" #include "Core/error.h" #include "Core/diagnostics.h" #include "Input/inputreader.h" #include "Output/projectwriter.h" #include "Output/reportwriter.h" #include "Utilities/utilities.h" #include <cstring> #include <fstream> using namespace std; //----------------------------------------------------------------------------- namespace Epanet { // Constructor Project::Project(): inpFileName(""), outFileName(""), tmpFileName(""), rptFileName(""), networkEmpty(true), hydEngineOpened(false), qualEngineOpened(false), outputFileOpened(false), solverInitialized(false), runQuality(false) { getNetwork()->project = this; Utilities::getTmpFileName(tmpFileName); } // Destructor Project::~Project() { //cout << "\nDestructing Project."; closeReport(); outputFile.close(); remove(tmpFileName.c_str()); //cout << "\nProject destructed.\n"; } //----------------------------------------------------------------------------- // Load a project from a file. int Project::load(const char* fname) { try { // ... clear any current project clear(); // ... check for duplicate file names string s = fname; if ( s.size() == rptFileName.size() && Utilities::match(s, rptFileName) ) { throw FileError(FileError::DUPLICATE_FILE_NAMES); } if ( s.size() == outFileName.size() && Utilities::match(s, outFileName) ) { throw FileError(FileError::DUPLICATE_FILE_NAMES); } // ... save name of input file inpFileName = fname; // ... use an InputReader to read project data from the input file InputReader inputReader; inputReader.readFile(fname, &network); networkEmpty = false; runQuality = network.option(Options::QUAL_TYPE) != Options::NOQUAL; // ... convert all network data to internal units network.convertUnits(); network.options.adjustOptions(); return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } //----------------------------------------------------------------------------- // Save the project to a file. int Project::save(const char* fname) { try { if ( networkEmpty ) return 0; ProjectWriter projectWriter; projectWriter.writeFile(fname, &network); return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } //----------------------------------------------------------------------------- // Clear the project of all data. void Project::clear() { hydEngine.close(); hydEngineOpened = false; qualEngine.close(); qualEngineOpened = false; network.clear(); networkEmpty = true; solverInitialized = false; inpFileName = ""; } void Project::clearSolver() { hydEngine.close(); hydEngineOpened = false; qualEngine.close(); qualEngineOpened = false; solverInitialized = false; } //----------------------------------------------------------------------------- // Initialize the project's solvers. int Project::initSolver(bool initFlows) { try { if ( networkEmpty ) return 0; solverInitialized = false; Diagnostics diagnostics; diagnostics.validateNetwork(&network); // ... open & initialize the hydraulic engine if ( !hydEngineOpened ) { initFlows = true; hydEngine.open(&network); hydEngineOpened = true; } hydEngine.init(initFlows); // ... open and initialize the water quality engine if ( runQuality == true ) { if ( !qualEngineOpened ) { qualEngine.open(&network); qualEngineOpened = true; } qualEngine.init(); } // ... mark solvers as being initialized solverInitialized = true; // ... initialize the binary output file outputFile.initWriter(); return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } //----------------------------------------------------------------------------- // Solve network hydraulics at the current point in time. int Project::runSolver(int* t) { try { if ( !solverInitialized ) throw SystemError(SystemError::SOLVER_NOT_INITIALIZED); hydEngine.solve(t); if ( outputFileOpened && *t % network.option(Options::REPORT_STEP) == 0 ) { outputFile.writeNetworkResults(); } return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } //----------------------------------------------------------------------------- // Advance the hydraulic solver to the next point in time while updating // water quality. int Project::advanceSolver(int* dt) { try { // ... advance to time when new hydraulics need to be computed hydEngine.advance(dt); // ... if at end of simulation (dt == 0) then finalize results if ( *dt == 0 ) finalizeSolver(); // ... otherwise update water quality over the time step else if ( runQuality ) qualEngine.solve(*dt); return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } //----------------------------------------------------------------------------- // Open a binary file that saves computed results. int Project::openOutput(const char* fname) { //... close an already opened output file if ( networkEmpty ) return 0; outputFile.close(); outputFileOpened = false; // ... save the name of the output file outFileName = fname; if ( strlen(fname) == 0 ) outFileName = tmpFileName; // ... open the file try { outputFile.open(outFileName, &network); outputFileOpened = true; return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } //----------------------------------------------------------------------------- // Save results for the current time period to the binary output file. int Project::saveOutput() { if ( !outputFileOpened ) return 0; try { outputFile.writeNetworkResults(); return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } //----------------------------------------------------------------------------- // Finalize computed quantities at the end of a run void Project::finalizeSolver() { if ( !solverInitialized ) return; // Save energy usage results to the binary output file. if ( outputFileOpened ) { double totalHrs = hydEngine.getElapsedTime() / 3600.0; double peakKwatts = hydEngine.getPeakKwatts(); outputFile.writeEnergyResults(totalHrs, peakKwatts); } // Write mass balance results for WQ constituent to message log if ( runQuality && network.option(Options::REPORT_STATUS) ) { network.qualBalance.writeBalance(network.msgLog); } } //----------------------------------------------------------------------------- // Open the project's status/report file. int Project::openReport(const char* fname) { try { //... close an already opened report file if ( rptFile.is_open() ) closeReport(); // ... check that file name is different from input file name string s = fname; if ( s.size() == inpFileName.size() && Utilities::match(s, inpFileName) ) { throw FileError(FileError::DUPLICATE_FILE_NAMES); } if ( s.size() == outFileName.size() && Utilities::match(s, outFileName) ) { throw FileError(FileError::DUPLICATE_FILE_NAMES); } // ... open the report file rptFile.open(fname); if ( !rptFile.is_open() ) { throw FileError(FileError::CANNOT_OPEN_REPORT_FILE); } ReportWriter rw(rptFile, &network); rw.writeHeading(); return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } //----------------------------------------------------------------------------- // Write a message to the project's message log. void Project::writeMsg(const std::string& msg) { network.msgLog << msg; } //----------------------------------------------------------------------------- // Write the project's title and option summary to the report file. void Project::writeSummary() { if (!rptFile.is_open()) return; ReportWriter reportWriter(rptFile, &network); reportWriter.writeSummary(inpFileName); } //----------------------------------------------------------------------------- // Close the project's report file. void Project::closeReport() { if ( rptFile.is_open() ) rptFile.close(); } //----------------------------------------------------------------------------- // Write the project's message log to an output stream. void Project::writeMsgLog(ostream& out) { out << network.msgLog.str(); network.msgLog.str(""); } //----------------------------------------------------------------------------- // Write the project's message log to the report file. void Project::writeMsgLog() { if ( rptFile.is_open() ) { rptFile << network.msgLog.str(); network.msgLog.str(""); } } //----------------------------------------------------------------------------- // Write results at the current time period to the report file. void Project::writeResults(int t) { if ( !rptFile.is_open() ) return; ReportWriter reportWriter(rptFile, &network); reportWriter.writeResults(t); } //----------------------------------------------------------------------------- // Write all results saved to the binary output file to a report file. int Project::writeReport() { try { if ( !outputFileOpened ) { throw FileError(FileError::NO_RESULTS_SAVED_TO_REPORT); } ReportWriter reportWriter(rptFile, &network); reportWriter.writeReport(inpFileName, &outputFile); return 0; } catch (ENerror const& e) { writeMsg(e.msg); return e.code; } } }
c++
code
11,915
2,575
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Copyright (c) 2006 Matthias Fink, netAllied GmbH <[email protected]> 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 "OgreStableHeaders.h" #include "OgreShadowCameraSetupFocused.h" #include "OgreRoot.h" #include "OgreSceneManager.h" #include "OgreCamera.h" #include "OgreLight.h" #include "OgrePlane.h" #include "OgreConvexBody.h" #include "OgreLogManager.h" namespace Ogre { FocusedShadowCameraSetup::FocusedShadowCameraSetup(void) { } //----------------------------------------------------------------------- FocusedShadowCameraSetup::~FocusedShadowCameraSetup(void) { } /*void FocusedShadowCameraSetup::calculateShadowMappingMatrix(const SceneManager& sm, const Camera& cam, const Light& light, Matrix4 *out_view, Matrix4 *out_proj, Camera *out_cam) const { // get the shadow frustum's far distance Real shadowDist = light.getShadowFarDistance(); if (!shadowDist) { // need a shadow distance, make one up shadowDist = cam.getNearClipDistance() * 3000; } Real shadowOffset = shadowDist * sm.getShadowDirLightTextureOffset(); if (light.getType() == Light::LT_DIRECTIONAL) { // generate view matrix if requested if (out_view != NULL) { *out_view = buildViewMatrix(cam.getDerivedPosition(), light.getDerivedDirection(), cam.getDerivedUp()); } // generate projection matrix if requested if (out_proj != NULL) { *out_proj = Matrix4::getScale(1, 1, -1); // *out_proj = Matrix4::IDENTITY; } // set up camera if requested if (out_cam != NULL) { out_cam->setProjectionType(PT_ORTHOGRAPHIC); out_cam->setDirection(light.getDerivedDirection()); out_cam->setPosition(cam.getDerivedPosition()); out_cam->setFOVy(Degree(90)); out_cam->setNearClipDistance(shadowOffset); } } else if (light.getType() == Light::LT_POINT) { const Vector3 lightDerivedPos( light.getParentNode()->_getDerivedPosition() ); // target analogue to the default shadow textures // Calculate look at position // We want to look at a spot shadowOffset away from near plane // 0.5 is a little too close for angles Vector3 target = cam.getDerivedPosition() + (cam.getDerivedDirection() * shadowOffset); Vector3 lightDir = target - lightDerivedPos; lightDir.normalise(); // generate view matrix if requested if (out_view != NULL) *out_view = buildViewMatrix( lightDerivedPos, lightDir, cam.getDerivedUp()); // generate projection matrix if requested if (out_proj != NULL) { // set FOV to 120 degrees mTempFrustum->setFOVy(Degree(120)); mTempFrustum->setNearClipDistance(light._deriveShadowNearClipDistance(&cam)); mTempFrustum->setFarClipDistance(light._deriveShadowFarClipDistance(&cam)); *out_proj = mTempFrustum->getProjectionMatrix(); } // set up camera if requested if (out_cam != NULL) { out_cam->setProjectionType(PT_PERSPECTIVE); out_cam->setDirection(lightDir); out_cam->setPosition(lightDerivedPos); out_cam->setFOVy(Degree(120)); out_cam->setNearClipDistance(light._deriveShadowNearClipDistance(&cam)); out_cam->setFarClipDistance(light._deriveShadowFarClipDistance(&cam)); } } else if (light.getType() == Light::LT_SPOTLIGHT) { const Vector3 lightDerivedPos( light.getParentNode()->_getDerivedPosition() ); // generate view matrix if requested if (out_view != NULL) { *out_view = buildViewMatrix( lightDerivedPos, light.getDerivedDirection(), cam.getDerivedUp()); } // generate projection matrix if requested if (out_proj != NULL) { // set FOV slightly larger than spotlight range mTempFrustum->setFOVy(Ogre::Math::Clamp<Radian>(light.getSpotlightOuterAngle() * 1.2, Radian(0), Radian(Math::PI/2.0f))); mTempFrustum->setNearClipDistance(light._deriveShadowNearClipDistance(&cam)); mTempFrustum->setFarClipDistance(light._deriveShadowFarClipDistance(&cam)); *out_proj = mTempFrustum->getProjectionMatrix(); } // set up camera if requested if (out_cam != NULL) { out_cam->setProjectionType(PT_PERSPECTIVE); out_cam->setDirection(light.getDerivedDirection()); out_cam->setPosition(lightDerivedPos); out_cam->setFOVy(Ogre::Math::Clamp<Radian>(light.getSpotlightOuterAngle() * 1.2, Radian(0), Radian(Math::PI/2.0f))); out_cam->setNearClipDistance(light._deriveShadowNearClipDistance(&cam)); out_cam->setFarClipDistance(light._deriveShadowFarClipDistance(&cam)); } } }*/ //----------------------------------------------------------------------- void FocusedShadowCameraSetup::getShadowCamera( const SceneManager *sm, const Camera *cam, const Light *light, Camera *texCam, size_t iteration, const Vector2 &viewportRealSize ) const { // check availability - viewport not needed OgreAssert(sm != NULL, "SceneManager is NULL"); OgreAssert(cam != NULL, "Camera (viewer) is NULL"); OgreAssert(light != NULL, "Light is NULL"); OgreAssert(texCam != NULL, "Camera (texture) is NULL"); if( light->getType() != Light::LT_DIRECTIONAL ) { DefaultShadowCameraSetup::getShadowCamera( sm, cam, light, texCam, iteration, viewportRealSize ); return; } texCam->setNearClipDistance(light->_deriveShadowNearClipDistance(cam)); texCam->setFarClipDistance(light->_deriveShadowFarClipDistance(cam)); const AxisAlignedBox &casterBox = sm->getCurrentCastersBox(); //Will be overriden, but not always (in case we early out to use uniform shadows) mMaxDistance = casterBox.getMinimum().distance( casterBox.getMaximum() ); // in case the casterBox is empty (e.g. there are no casters) simply // return the standard shadow mapping matrix if( casterBox.isNull() ) { texCam->setProjectionType( PT_ORTHOGRAPHIC ); //Anything will do, there are no casters. But we must ensure depth of the receiver //doesn't become negative else a shadow square will appear (i.e. "the sun is below the floor") const Real farDistance = Ogre::min( cam->getFarClipDistance(), light->getShadowFarDistance() ); texCam->setPosition( cam->getDerivedPosition() - light->getDerivedDirection() * farDistance ); texCam->setOrthoWindow( 1, 1 ); texCam->setNearClipDistance( 1.0f ); texCam->setFarClipDistance( 1.1f ); texCam->getWorldAabbUpdated(); mMinDistance = 1.0f; mMaxDistance = 1.1f; return; } const Node *lightNode = light->getParentNode(); const Real farDistance= Ogre::min( cam->getFarClipDistance(), light->getShadowFarDistance() ); const Quaternion scalarLightSpaceToWorld( lightNode->_getDerivedOrientation() ); const Quaternion scalarWorldToLightSpace( scalarLightSpaceToWorld.Inverse() ); ArrayQuaternion worldToLightSpace; worldToLightSpace.setAll( scalarWorldToLightSpace ); ArrayVector3 vMinBounds( Mathlib::MAX_POS, Mathlib::MAX_POS, Mathlib::MAX_POS ); ArrayVector3 vMaxBounds( Mathlib::MAX_NEG, Mathlib::MAX_NEG, Mathlib::MAX_NEG ); #define NUM_ARRAY_VECTORS (8 + ARRAY_PACKED_REALS - 1) / ARRAY_PACKED_REALS //Take the 8 camera frustum's corners, transform to //light space, and compute its AABB in light space ArrayVector3 corners[NUM_ARRAY_VECTORS]; cam->getCustomWorldSpaceCorners( corners, farDistance ); for( size_t i=0; i<NUM_ARRAY_VECTORS; ++i ) { ArrayVector3 lightSpacePoint = worldToLightSpace * corners[i]; vMinBounds.makeFloor( lightSpacePoint ); vMaxBounds.makeCeil( lightSpacePoint ); } Vector3 vMinCamFrustumLS = vMinBounds.collapseMin(); Vector3 vMaxCamFrustumLS = vMaxBounds.collapseMax(); Vector3 casterAabbCornersLS[8]; for( size_t i=0; i<8; ++i ) { casterAabbCornersLS[i] = scalarWorldToLightSpace * casterBox.getCorner( static_cast<AxisAlignedBox::CornerEnum>( i ) ); } ConvexBody convexBody; convexBody.define( casterAabbCornersLS ); Plane p; p.redefine( Vector3::NEGATIVE_UNIT_X, vMinCamFrustumLS ); convexBody.clip( p ); p.redefine( Vector3::UNIT_X, vMaxCamFrustumLS ); convexBody.clip( p ); p.redefine( Vector3::NEGATIVE_UNIT_Y, vMinCamFrustumLS ); convexBody.clip( p ); p.redefine( Vector3::UNIT_Y, vMaxCamFrustumLS ); convexBody.clip( p ); p.redefine( Vector3::NEGATIVE_UNIT_Z, vMinCamFrustumLS ); convexBody.clip( p ); Vector3 vMin( std::numeric_limits<Real>::max(), std::numeric_limits<Real>::max(), std::numeric_limits<Real>::max() ); Vector3 vMax( -std::numeric_limits<Real>::max(), -std::numeric_limits<Real>::max(), -std::numeric_limits<Real>::max() ); for( size_t i=0; i<convexBody.getPolygonCount(); ++i ) { const Polygon& polygon = convexBody.getPolygon( i ); for( size_t j=0; j<polygon.getVertexCount(); ++j ) { const Vector3 &point = polygon.getVertex( j ); vMin.makeFloor( point ); vMax.makeCeil( point ); } } if( vMin > vMax ) { //There are no casters that will affect the viewing frustum //(or something went wrong with the clipping). //Rollback to something valid vMin = vMinCamFrustumLS; vMax = vMaxCamFrustumLS; //Add some padding to prevent negative depth (i.e. "the sun is below the floor") vMax.z += 5.0f; // Backwards is towards +Z! } vMin.z = Ogre::min( vMin.z, vMinCamFrustumLS.z ); const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities(); if( caps->hasCapability( RSC_DEPTH_CLAMP ) ) { // We can only do shadow pancaking (increasing precision) if depth clamp is supported vMax.z = Ogre::max( vMax.z, vMaxCamFrustumLS.z ); } //Some padding vMax += 1.5f; vMin -= 1.5f; const float zPadding = 2.0f; texCam->setProjectionType( PT_ORTHOGRAPHIC ); Vector3 shadowCameraPos = (vMin + vMax) * 0.5f; shadowCameraPos.z = vMax.z + zPadding; // Backwards is towards +Z! // Round local x/y position based on a world-space texel; this helps to reduce // jittering caused by the projection moving with the camera const Real worldTexelSizeX = ( texCam->getOrthoWindowWidth() ) / viewportRealSize.x; const Real worldTexelSizeY = ( texCam->getOrthoWindowHeight() ) / viewportRealSize.y; // snap to nearest texel shadowCameraPos.x -= fmod( shadowCameraPos.x, worldTexelSizeX ); shadowCameraPos.y -= fmod( shadowCameraPos.y, worldTexelSizeY ); //Go back from light space to world space shadowCameraPos = scalarLightSpaceToWorld * shadowCameraPos; texCam->setPosition( shadowCameraPos ); texCam->setOrthoWindow( (vMax.x - vMin.x), (vMax.y - vMin.y) ); mMinDistance = 1.0f; mMaxDistance = vMax.z - vMin.z + zPadding; //We just went backwards, we need to enlarge our depth texCam->setNearClipDistance( mMinDistance ); texCam->setFarClipDistance( mMaxDistance ); //Update the AABB. Note: Non-shadow caster cameras are forbidden to change mid-render texCam->getWorldAabbUpdated(); } }
c++
code
14,376
2,511
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2017-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #include <folly/portability/GTest.h> #include <mcbp/mcbp.h> #include <platform/dirutils.h> TEST(ParserTest, GdbOutput) { const auto file = cb::io::sanitizePath(SOURCE_ROOT "/protocol/mcbp/gdb_output.txt"); const auto content = cb::io::loadFile(file); cb::byte_buffer buf = { const_cast<uint8_t*>( reinterpret_cast<const uint8_t*>(content.data())), content.size()}; auto data = cb::mcbp::gdb::parseDump(buf); const std::vector<uint8_t> bytes = { {0x81, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x55, 0x53, 0x5f, 0x56, 0x32, 0x5f, 0x52, 0x45, 0x43, 0x55, 0x52, 0x52, 0x49, 0x4e, 0x47, 0x5f, 0x54, 0x49, 0x45, 0x52, 0x5f, 0x43, 0x41, 0x52, 0x45, 0x45, 0x52, 0x5f, 0x53, 0x54, 0x41, 0x52, 0x53, 0x5f, 0x55, 0x5f, 0x34, 0x30, 0x37, 0x39, 0x37, 0x35, 0x33, 0x61, 0x3a, 0x31, 0x3a, 0x7b, 0x73, 0x3a, 0x31, 0x31, 0x3a, 0x22, 0x57, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x5f, 0x32, 0x30, 0x31, 0x33, 0x22, 0x3b, 0x64}}; EXPECT_EQ(bytes, data); } TEST(ParserTest, LldbOutput) { const auto file = cb::io::sanitizePath(SOURCE_ROOT "/protocol/mcbp/lldb_output.txt"); const auto content = cb::io::loadFile(file); cb::byte_buffer buf = { const_cast<uint8_t*>( reinterpret_cast<const uint8_t*>(content.data())), content.size()}; auto data = cb::mcbp::lldb::parseDump(buf); const std::vector<uint8_t> bytes = { {0x81, 0x0d, 0x00, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0x14, 0xbf, 0xf4, 0x26, 0x8a, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x61, 0x81, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x61, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x5f, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x33, 0x36, 0x81, 0x10, 0x00, 0x15, 0x00, 0x00, 0x00, 0x00}}; EXPECT_EQ(bytes, data); }
c++
code
2,928
732
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Argo Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/server.h" #include "base58.h" #include "init.h" #include "random.h" #include "sync.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include <univalue.h> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include <boost/signals2/signal.hpp> #include <boost/thread.hpp> #include <boost/algorithm/string/case_conv.hpp> // for to_upper() using namespace RPCServer; using namespace std; static bool fRPCRunning = false; static bool fRPCInWarmup = true; static std::string rpcWarmupStatus("RPC server started"); static CCriticalSection cs_rpcWarmup; /* Timer-creating functions */ static std::vector<RPCTimerInterface*> timerInterfaces; /* Map of name to timer. * @note Can be changed to std::unique_ptr when C++11 */ static std::map<std::string, boost::shared_ptr<RPCTimerBase> > deadlineTimers; static struct CRPCSignals { boost::signals2::signal<void ()> Started; boost::signals2::signal<void ()> Stopped; boost::signals2::signal<void (const CRPCCommand&)> PreCommand; boost::signals2::signal<void (const CRPCCommand&)> PostCommand; } g_rpcSignals; void RPCServer::OnStarted(boost::function<void ()> slot) { g_rpcSignals.Started.connect(slot); } void RPCServer::OnStopped(boost::function<void ()> slot) { g_rpcSignals.Stopped.connect(slot); } void RPCServer::OnPreCommand(boost::function<void (const CRPCCommand&)> slot) { g_rpcSignals.PreCommand.connect(boost::bind(slot, _1)); } void RPCServer::OnPostCommand(boost::function<void (const CRPCCommand&)> slot) { g_rpcSignals.PostCommand.connect(boost::bind(slot, _1)); } void RPCTypeCheck(const UniValue& params, const list<UniValue::VType>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(UniValue::VType t, typesExpected) { if (params.size() <= i) break; const UniValue& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.isNull())))) { string err = strprintf("Expected type %s, got %s", uvTypeName(t), uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheckObj(const UniValue& o, const map<string, UniValue::VType>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, UniValue::VType)& t, typesExpected) { const UniValue& v = find_value(o, t.first); if (!fAllowNull && v.isNull()) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!((v.type() == t.second) || (fAllowNull && (v.isNull())))) { string err = strprintf("Expected type %s for %s, got %s", uvTypeName(t.second), t.first, uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } CAmount AmountFromValue(const UniValue& value) { if (!value.isNum() && !value.isStr()) throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number or string"); CAmount amount; if (!ParseFixedPoint(value.getValStr(), 8, &amount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); if (!MoneyRange(amount)) throw JSONRPCError(RPC_TYPE_ERROR, "Amount out of range"); return amount; } UniValue ValueFromAmount(const CAmount& amount) { bool sign = amount < 0; int64_t n_abs = (sign ? -amount : amount); int64_t quotient = n_abs / COIN; int64_t remainder = n_abs % COIN; return UniValue(UniValue::VNUM, strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder)); } uint256 ParseHashV(const UniValue& v, string strName) { string strHex; if (v.isStr()) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const UniValue& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const UniValue& v, string strName) { string strHex; if (v.isStr()) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const UniValue& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } /** * Note: This interface may still be subject to change. */ std::string CRPCTable::help(const std::string& strCommand) const { string strRet; string category; set<rpcfn_type> setDone; vector<pair<string, const CRPCCommand*> > vCommands; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second)); sort(vCommands.begin(), vCommands.end()); BOOST_FOREACH(const PAIRTYPE(string, const CRPCCommand*)& command, vCommands) { const CRPCCommand *pcmd = command.second; string strMethod = pcmd->name; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand) continue; try { UniValue params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (const std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") { if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); if (category != pcmd->category) { if (!category.empty()) strRet += "\n"; category = pcmd->category; string firstLetter = category.substr(0,1); boost::to_upper(firstLetter); strRet += "== " + firstLetter + category.substr(1) + " ==\n"; } } strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand); strRet = strRet.substr(0,strRet.size()-1); return strRet; } UniValue help(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help ( \"command\" )\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" "1. \"command\" (string, optional) The command to get help on\n" "\nResult:\n" "\"text\" (string) The help text\n" ); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } UniValue stop(const UniValue& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "\nStop Argo Core server."); // Event loop will exit after current HTTP requests have been handled, so // this reply will get back to the client. StartShutdown(); return "Argo Core server stopping"; } /** * Call Table */ static const CRPCCommand vRPCCommands[] = { // category name actor (function) okSafeMode // --------------------- ------------------------ ----------------------- ---------- /* Overall control/query calls */ { "control", "getinfo", &getinfo, true }, /* uses wallet if enabled */ { "control", "debug", &debug, true }, { "control", "help", &help, true }, { "control", "stop", &stop, true }, /* P2P networking */ { "network", "getnetworkinfo", &getnetworkinfo, true }, { "network", "addnode", &addnode, true }, { "network", "disconnectnode", &disconnectnode, true }, { "network", "getaddednodeinfo", &getaddednodeinfo, true }, { "network", "getconnectioncount", &getconnectioncount, true }, { "network", "getnettotals", &getnettotals, true }, { "network", "getpeerinfo", &getpeerinfo, true }, { "network", "ping", &ping, true }, { "network", "setban", &setban, true }, { "network", "listbanned", &listbanned, true }, { "network", "clearbanned", &clearbanned, true }, { "network", "setnetworkactive", &setnetworkactive, true }, /* Block chain and UTXO */ { "blockchain", "getblockchaininfo", &getblockchaininfo, true }, { "blockchain", "getbestblockhash", &getbestblockhash, true }, { "blockchain", "getblockcount", &getblockcount, true }, { "blockchain", "getblock", &getblock, true }, { "blockchain", "getblockhashes", &getblockhashes, true }, { "blockchain", "getblockhash", &getblockhash, true }, { "blockchain", "getblockheader", &getblockheader, true }, { "blockchain", "getblockheaders", &getblockheaders, true }, { "blockchain", "getchaintips", &getchaintips, true }, { "blockchain", "getdifficulty", &getdifficulty, true }, { "blockchain", "getmempoolinfo", &getmempoolinfo, true }, { "blockchain", "getrawmempool", &getrawmempool, true }, { "blockchain", "gettxout", &gettxout, true }, { "blockchain", "gettxoutproof", &gettxoutproof, true }, { "blockchain", "verifytxoutproof", &verifytxoutproof, true }, { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true }, { "blockchain", "verifychain", &verifychain, true }, { "blockchain", "getspentinfo", &getspentinfo, false }, /* Mining */ { "mining", "getblocktemplate", &getblocktemplate, true }, { "mining", "getmininginfo", &getmininginfo, true }, { "mining", "getnetworkhashps", &getnetworkhashps, true }, { "mining", "prioritisetransaction", &prioritisetransaction, true }, { "mining", "submitblock", &submitblock, true }, /* Coin generation */ { "generating", "getgenerate", &getgenerate, true }, { "generating", "setgenerate", &setgenerate, true }, { "generating", "generate", &generate, true }, /* Raw transactions */ { "rawtransactions", "createrawtransaction", &createrawtransaction, true }, { "rawtransactions", "decoderawtransaction", &decoderawtransaction, true }, { "rawtransactions", "decodescript", &decodescript, true }, { "rawtransactions", "getrawtransaction", &getrawtransaction, true }, { "rawtransactions", "sendrawtransaction", &sendrawtransaction, false }, { "rawtransactions", "signrawtransaction", &signrawtransaction, false }, /* uses wallet if enabled */ #ifdef ENABLE_WALLET { "rawtransactions", "fundrawtransaction", &fundrawtransaction, false }, #endif /* Address index */ { "addressindex", "getaddressmempool", &getaddressmempool, true }, { "addressindex", "getaddressutxos", &getaddressutxos, false }, { "addressindex", "getaddressdeltas", &getaddressdeltas, false }, { "addressindex", "getaddresstxids", &getaddresstxids, false }, { "addressindex", "getaddressbalance", &getaddressbalance, false }, /* Utility functions */ { "util", "createmultisig", &createmultisig, true }, { "util", "validateaddress", &validateaddress, true }, /* uses wallet if enabled */ { "util", "verifymessage", &verifymessage, true }, { "util", "estimatefee", &estimatefee, true }, { "util", "estimatepriority", &estimatepriority, true }, { "util", "estimatesmartfee", &estimatesmartfee, true }, { "util", "estimatesmartpriority", &estimatesmartpriority, true }, /* Not shown in help */ { "hidden", "invalidateblock", &invalidateblock, true }, { "hidden", "reconsiderblock", &reconsiderblock, true }, { "hidden", "setmocktime", &setmocktime, true }, #ifdef ENABLE_WALLET { "hidden", "resendwallettransactions", &resendwallettransactions, true}, #endif /* Argo features */ { "argo", "masternode", &masternode, true }, { "argo", "masternodelist", &masternodelist, true }, { "argo", "masternodebroadcast", &masternodebroadcast, true }, { "argo", "gobject", &gobject, true }, { "argo", "getgovernanceinfo", &getgovernanceinfo, true }, { "argo", "getsuperblockbudget", &getsuperblockbudget, true }, { "argo", "voteraw", &voteraw, true }, { "argo", "mnsync", &mnsync, true }, { "argo", "spork", &spork, true }, { "argo", "getpoolinfo", &getpoolinfo, true }, { "argo", "sentinelping", &sentinelping, true }, #ifdef ENABLE_WALLET { "argo", "privatesend", &privatesend, false }, /* Wallet */ { "wallet", "keepass", &keepass, true }, { "wallet", "instantsendtoaddress", &instantsendtoaddress, false }, { "wallet", "addmultisigaddress", &addmultisigaddress, true }, { "wallet", "backupwallet", &backupwallet, true }, { "wallet", "dumpprivkey", &dumpprivkey, true }, { "wallet", "dumphdinfo", &dumphdinfo, true }, { "wallet", "dumpwallet", &dumpwallet, true }, { "wallet", "encryptwallet", &encryptwallet, true }, { "wallet", "getaccountaddress", &getaccountaddress, true }, { "wallet", "getaccount", &getaccount, true }, { "wallet", "getaddressesbyaccount", &getaddressesbyaccount, true }, { "wallet", "getbalance", &getbalance, false }, { "wallet", "getnewaddress", &getnewaddress, true }, { "wallet", "getrawchangeaddress", &getrawchangeaddress, true }, { "wallet", "getreceivedbyaccount", &getreceivedbyaccount, false }, { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, false }, { "wallet", "gettransaction", &gettransaction, false }, { "wallet", "abandontransaction", &abandontransaction, false }, { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, false }, { "wallet", "getwalletinfo", &getwalletinfo, false }, { "wallet", "importprivkey", &importprivkey, true }, { "wallet", "importwallet", &importwallet, true }, { "wallet", "importelectrumwallet", &importelectrumwallet, true }, { "wallet", "importaddress", &importaddress, true }, { "wallet", "importpubkey", &importpubkey, true }, { "wallet", "keypoolrefill", &keypoolrefill, true }, { "wallet", "listaccounts", &listaccounts, false }, { "wallet", "listaddressgroupings", &listaddressgroupings, false }, { "wallet", "listlockunspent", &listlockunspent, false }, { "wallet", "listreceivedbyaccount", &listreceivedbyaccount, false }, { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, false }, { "wallet", "listsinceblock", &listsinceblock, false }, { "wallet", "listtransactions", &listtransactions, false }, { "wallet", "listunspent", &listunspent, false }, { "wallet", "lockunspent", &lockunspent, true }, { "wallet", "move", &movecmd, false }, { "wallet", "sendfrom", &sendfrom, false }, { "wallet", "sendmany", &sendmany, false }, { "wallet", "sendtoaddress", &sendtoaddress, false }, { "wallet", "setaccount", &setaccount, true }, { "wallet", "settxfee", &settxfee, true }, { "wallet", "signmessage", &signmessage, true }, { "wallet", "walletlock", &walletlock, true }, { "wallet", "walletpassphrasechange", &walletpassphrasechange, true }, { "wallet", "walletpassphrase", &walletpassphrase, true }, #endif // ENABLE_WALLET }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](const std::string &name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapComm
c++
code
20,000
3,956
// written by bastiaan konings schuiling 2008 - 2015 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #include "playerhud.hpp" #include "utils/gui2/windowmanager.hpp" #include <SDL/SDL.h> #include "../../onthepitch/match.hpp" using namespace blunted; Gui2PlayerHUD::Gui2PlayerHUD(Gui2WindowManager *windowManager, const std::string &name, float x_percent, float y_percent, float width_percent, float height_percent, Match *match) : Gui2View(windowManager, name, x_percent, y_percent, width_percent, height_percent), match(match) { } Gui2PlayerHUD::~Gui2PlayerHUD() { } void Gui2PlayerHUD::GetImages(std::vector < boost::intrusive_ptr<Image2D> > &target) { target.push_back(image); Gui2View::GetImages(target); } void Gui2PlayerHUD::Redraw() { }
c++
code
938
193
/* * Neomatrix - Copyright (C) 2017 Lars Christensen * MIT Licensed * * WiFi */ #include "wifi.hpp" #include "ota.hpp" #include <ESP8266WiFiMulti.h> ESP8266WiFiMulti WiFiMulti; static bool wifiConnected = false; void wifi_init() { WiFiMulti.addAP("hal9k", ""); WiFiMulti.addAP("****", "****"); } void wifi_run() { if (WiFiMulti.run() == WL_CONNECTED) { if (!wifiConnected) { Serial.print("Connected as "); Serial.println(WiFi.localIP()); wifiConnected = true; ota_init(); } if (wifiConnected) { ota_run(); } } }
c++
code
576
146
#include <jni.h> #include <android/log.h> #include <stdio.h> #include <android/bitmap.h> #include <cstring> #include <unistd.h> #include <vector> #include <parallelme/ParallelME.hpp> #include <parallelocr/ParallelOCR.hpp> #include "br_edu_ufsj_dcomp_ocr_Controller.h" #include <time.h> using namespace parallelme; using namespace parallelocr; const static char gKernels[] = "__kernel void identification( __global uint *trainData, __global uint *dataSize, __global uint *changes, __global uint *changesSize, __global uint *rotule, __global uint *result){ /*first pass is normalize the trainData passing the normalized version to rotule*/ uint crossingRotuleSize = 0; for(uint i=0;i<(changesSize[0]-1);i++){ if(changes[i] != changes[(i+1)]){ rotule[crossingRotuleSize] = changes[i]; crossingRotuleSize++; } } /*second pass is compare the rotule with the trainData to see if will match with any letter*/ uint i = 0; uint letter; uint quantity; while(i < dataSize[0]){ letter = trainData[i]; i++; quantity = trainData[i]; i++; uint j = 0; uint isFinded = 1; if(quantity == crossingRotuleSize){ while(j < quantity && j < crossingRotuleSize){ if(trainData[i+j] != rotule[j]){ isFinded = 0; break; } j++; } if(isFinded == 1){ result[0] = letter; break; } } i += quantity; } } __kernel void fe1(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe2(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe3(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe4(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe5(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe6(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe7(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe8(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe9(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe10(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe11(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe12(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe13(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe14(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe15(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe16(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe17(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe18(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe19(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe20(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe21(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe22(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe23(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe24(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe25(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe26(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe27(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe28(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe29(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe30(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe31(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe32(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe33(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe34(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe35(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe36(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe37(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe38(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe39(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe40(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe41(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe42(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe43(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe44(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe45(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe46(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe47(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe48(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe49(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe50(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe51(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe52(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe53(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe54(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe55(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe56(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe57(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe58(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+width[0]-1);i++){ if(letter[i] != letter[i+1]){ changes++; } } } ccount[id] = changes; } __kernel void fe59(__global uint *letter,__global uint *width,__global uint *ccount){ uint id = get_global_id(0); uint changes = 0; for (uint teste = 0;teste < 1000;teste++){ changes = 0; for(uint i=(id*width[0]);i < (id*width[0]+widt
c++
code
20,000
6,766
//================================================================================================= /*! // \file src/mathtest/dvecdvecmult/VDbV3b.cpp // \brief Source file for the VDbV3b dense vector/dense vector outer product math test // // Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicVector.h> #include <blaze/math/StaticVector.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dvecdvecouter/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'VDbV3b'..." << std::endl; using blazetest::mathtest::TypeB; try { // Vector type definitions typedef blaze::DynamicVector<TypeB> VDb; typedef blaze::StaticVector<TypeB,3UL> V3b; // Creator type definitions typedef blazetest::Creator<VDb> CVDb; typedef blazetest::Creator<V3b> CV3b; // Running the tests for( size_t i=0UL; i<=5UL; ++i ) { RUN_DVECDVECOUTER_OPERATION_TEST( CVDb( i ), CV3b() ); } } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector outer product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
c++
code
3,726
951
/**************************************************************************************************************************************************** * Copyright (c) 2016 Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the Freescale Semiconductor, Inc. nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************************************************************************************/ #include <FslUtil/OpenVG/Util.hpp> #include <FslUtil/OpenVG/DebugStrings.hpp> #include <sstream> namespace Fsl { namespace OpenVG { std::string Util::ToNiceMessage(const std::string& message, const VGErrorCode errorCode) { std::stringstream stream; stream << message << " failed with error code " << Debug::ErrorCodeToString(errorCode) << " (" << errorCode << ")"; return stream.str(); } std::string Util::ToNiceMessage(const std::string& message, const VGErrorCode errorCode, const std::string& fileName, const int lineNumber) { std::stringstream stream; stream << message << " failed with error code " << Debug::ErrorCodeToString(errorCode) << " (" << errorCode << ") at " << fileName << "(" << lineNumber << ")"; return stream.str(); } } }
c++
code
2,748
779
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fxge/cfx_gemodule.h" #include "core/fxge/cfx_fontcache.h" #include "core/fxge/cfx_fontmgr.h" #include "core/fxge/ge/cfx_folderfontinfo.h" #include "core/fxge/ge/fx_text_int.h" namespace { CFX_GEModule* g_pGEModule = nullptr; } // namespace CFX_GEModule::CFX_GEModule() : m_FTLibrary(nullptr), m_pFontCache(nullptr), m_pFontMgr(new CFX_FontMgr), m_pCodecModule(nullptr), m_pPlatformData(nullptr), m_pUserFontPaths(nullptr) {} CFX_GEModule::~CFX_GEModule() { delete m_pFontCache; DestroyPlatform(); } // static CFX_GEModule* CFX_GEModule::Get() { if (!g_pGEModule) g_pGEModule = new CFX_GEModule(); return g_pGEModule; } // static void CFX_GEModule::Destroy() { ASSERT(g_pGEModule); delete g_pGEModule; g_pGEModule = nullptr; } void CFX_GEModule::Init(const char** userFontPaths, CCodec_ModuleMgr* pCodecModule) { ASSERT(g_pGEModule); m_pCodecModule = pCodecModule; m_pUserFontPaths = userFontPaths; InitPlatform(); SetTextGamma(2.2f); } CFX_FontCache* CFX_GEModule::GetFontCache() { if (!m_pFontCache) m_pFontCache = new CFX_FontCache(); return m_pFontCache; } void CFX_GEModule::SetTextGamma(float gammaValue) { gammaValue /= 2.2f; for (int i = 0; i < 256; ++i) { m_GammaValue[i] = static_cast<uint8_t>( FXSYS_pow(static_cast<float>(i) / 255, gammaValue) * 255.0f + 0.5f); } } const uint8_t* CFX_GEModule::GetTextGammaTable() const { return m_GammaValue; }
c++
code
1,740
327
#include "obfuscationconfig.h" #include "ui_obfuscationconfig.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "init.h" #include "optionsmodel.h" #include "walletmodel.h" #include <QKeyEvent> #include <QMessageBox> #include <QPushButton> #include <QSettings> ObfuscationConfig::ObfuscationConfig(QWidget* parent) : QDialog(parent), ui(new Ui::ObfuscationConfig), model(0) { ui->setupUi(this); connect(ui->buttonBasic, SIGNAL(clicked()), this, SLOT(clickBasic())); connect(ui->buttonHigh, SIGNAL(clicked()), this, SLOT(clickHigh())); connect(ui->buttonMax, SIGNAL(clicked()), this, SLOT(clickMax())); } ObfuscationConfig::~ObfuscationConfig() { delete ui; } void ObfuscationConfig::setModel(WalletModel* model) { this->model = model; } void ObfuscationConfig::clickBasic() { configure(true, 1000, 2); QString strAmount(BitcoinUnits::formatWithUnit( model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); QMessageBox::information(this, tr("Obfuscation Configuration"), tr( "Obfuscation was successfully set to basic (%1 and 2 rounds). You can change this at any time by opening SPON's configuration screen.") .arg(strAmount)); close(); } void ObfuscationConfig::clickHigh() { configure(true, 1000, 8); QString strAmount(BitcoinUnits::formatWithUnit( model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); QMessageBox::information(this, tr("Obfuscation Configuration"), tr( "Obfuscation was successfully set to high (%1 and 8 rounds). You can change this at any time by opening SPON's configuration screen.") .arg(strAmount)); close(); } void ObfuscationConfig::clickMax() { configure(true, 1000, 16); QString strAmount(BitcoinUnits::formatWithUnit( model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); QMessageBox::information(this, tr("Obfuscation Configuration"), tr( "Obfuscation was successfully set to maximum (%1 and 16 rounds). You can change this at any time by opening SPON's configuration screen.") .arg(strAmount)); close(); } void ObfuscationConfig::configure(bool enabled, int coins, int rounds) { QSettings settings; settings.setValue("nObfuscationRounds", rounds); settings.setValue("nAnonymizeSponAmount", coins); nObfuscationRounds = rounds; nAnonymizeSponAmount = coins; }
c++
code
2,559
555
/* * Convert trace to direnoIV trace format * * Created By He, Hao in 2019/5/2 */ #include <fstream> #include <iostream> bool parseParameters(int argc, char **argv); void printUsage(); const char *traceFilePath; int main(int argc, char **argv) { if (!parseParameters(argc, argv)) { return -1; } std::ifstream infile(traceFilePath); std::ofstream outfile(std::string(traceFilePath) + ".d4"); if (!infile.is_open()) { printf("Invalid file path %s\n", traceFilePath); return -1; } char type; uint32_t addr; while (infile >> type >> std::hex >> addr) { outfile << type << " " << std::hex << addr << " " << 1 << std::endl; } return 0; } bool parseParameters(int argc, char **argv) { // Read Parameters if (argc > 1) { traceFilePath = argv[1]; return true; } else { return false; } } void printUsage() { printf("Usage: CacheSim trace-file\n"); }
c++
code
908
251
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* CICalendarVAlarm.cpp Author: Description: <describe the CICalendarVAlarm class here> */ #include "CICalendarVAlarm.h" #include "CCalendarNotifier.h" #include "CICalendarCalAddressValue.h" #include "CICalendarComponentRecur.h" #include "CICalendarDefinitions.h" using namespace iCal; cdstring CICalendarVAlarm::sBeginDelimiter(cICalComponent_BEGINVALARM); cdstring CICalendarVAlarm::sEndDelimiter(cICalComponent_ENDVALARM); CICalendarVAlarm::CICalendarVAlarm(const CICalendarRef& calendar) : CICalendarComponent(calendar) { mAction = eAction_VAlarm_Display; mTriggerAbsolute = false; mTriggerOnStart = true; // Set duration default to 1 hour mTriggerBy.SetDuration(60 * 60); // Does not repeat by default mRepeats = 0; mRepeatInterval.SetDuration(5 * 60); // Five minutes // Status mStatusInit = false; mAlarmStatus = eAlarm_Status_Pending; mDoneCount = 0; // Create action data mActionData = new CICalendarVAlarmDisplay(cdstring::null_str); } void CICalendarVAlarm::_copy_CICalendarVAlarm(const CICalendarVAlarm& copy) { mAction = copy.mAction; mTriggerAbsolute = copy.mTriggerAbsolute; mTriggerOn = copy.mTriggerOn; mTriggerBy = copy.mTriggerBy; mTriggerOnStart = copy.mTriggerOnStart; mRepeats = copy.mRepeats; mRepeatInterval = copy.mRepeatInterval; mAlarmStatus = copy.mAlarmStatus; mLastTrigger = copy.mLastTrigger; mNextTrigger = copy.mNextTrigger; mDoneCount = copy.mDoneCount; mActionData = copy.mActionData->clone(); } void CICalendarVAlarm::Added() { // Added to calendar so add to calendar notifier calstore::CCalendarNotifier::sCalendarNotifier.AddAlarm(this); // Do inherited CICalendarComponent::Added(); } void CICalendarVAlarm::Removed() { // Removed from calendar so add to calendar notifier calstore::CCalendarNotifier::sCalendarNotifier.RemoveAlarm(this); // Do inherited CICalendarComponent::Removed(); } void CICalendarVAlarm::Changed() { // Always force recalc of trigger status mStatusInit = false; // Changed in calendar so change in calendar notifier calstore::CCalendarNotifier::sCalendarNotifier.ChangedAlarm(this); // Do not do inherited as this is always a sub-component and we do not // do top-level component changes //CICalendarComponent::Changed(); } void CICalendarVAlarm::Finalise() { // Do inherited CICalendarComponent::Finalise(); // Get the ACTION { cdstring temp; if (LoadValue(cICalProperty_ACTION, temp)) { if (temp == cICalProperty_ACTION_AUDIO) { mAction = eAction_VAlarm_Audio; } else if (temp == cICalProperty_ACTION_DISPLAY) { mAction = eAction_VAlarm_Display; } else if (temp == cICalProperty_ACTION_EMAIL) { mAction = eAction_VAlarm_Email; } else if (temp == cICalProperty_ACTION_PROCEDURE) { mAction = eAction_VAlarm_Procedure; } else { mAction = eAction_VAlarm_Unknown; } LoadAction(); } } // Get the trigger if (GetProperties().count(cICalProperty_TRIGGER)) { // Determine the type of the value if (LoadValue(cICalProperty_TRIGGER, mTriggerOn)) { mTriggerAbsolute = true; } else if (LoadValue(cICalProperty_TRIGGER, mTriggerBy)) { mTriggerAbsolute = false; // Get the property const CICalendarProperty& prop = (*GetProperties().find(cICalProperty_TRIGGER)).second; // Look for RELATED attribute if (prop.HasAttribute(cICalAttribute_RELATED)) { const cdstring& temp = prop.GetAttributeValue(cICalAttribute_RELATED); if (temp == cICalAttribute_RELATED_START) { mTriggerOnStart = true; } else if (temp == cICalAttribute_RELATED_END) { mTriggerOnStart = false; } } else mTriggerOnStart = true; } } // Get repeat & interval LoadValue(cICalProperty_REPEAT, mRepeats); LoadValue(cICalProperty_DURATION, mRepeatInterval); // Alarm status - private to Mulberry cdstring status; if (LoadValue(cICalProperty_ALARM_X_ALARMSTATUS, status)) { if (status == cICalProperty_ALARM_X_ALARMSTATUS_PENDING) mAlarmStatus = eAlarm_Status_Pending; else if (status == cICalProperty_ALARM_X_ALARMSTATUS_COMPLETED) mAlarmStatus = eAlarm_Status_Completed; else if (status == cICalProperty_ALARM_X_ALARMSTATUS_DISABLED) mAlarmStatus = eAlarm_Status_Disabled; else mAlarmStatus = eAlarm_Status_Pending; } // Last trigger time - private to Mulberry LoadValue(cICalProperty_ALARM_X_LASTTRIGGER, mLastTrigger); } void CICalendarVAlarm::LoadAction() { // Delete current one delete mActionData; mActionData = NULL; switch(mAction) { case eAction_VAlarm_Audio: mActionData = new CICalendarVAlarmAudio; mActionData->Load(this); break; case eAction_VAlarm_Display: mActionData = new CICalendarVAlarmDisplay; mActionData->Load(this); break; case eAction_VAlarm_Email: mActionData = new CICalendarVAlarmEmail; mActionData->Load(this); break; default: mActionData = new CICalendarVAlarmUnknown; mActionData->Load(this); break; } } void CICalendarVAlarm::EditStatus(EAlarm_Status status) { // Remove existing RemoveProperties(cICalProperty_ALARM_X_ALARMSTATUS); // Updated cached values mAlarmStatus = status; // Add new cdstring status_txt; if (mAlarmStatus == eAlarm_Status_Pending) status_txt = cICalProperty_ALARM_X_ALARMSTATUS_PENDING; else if (mAlarmStatus == eAlarm_Status_Completed) status_txt = cICalProperty_ALARM_X_ALARMSTATUS_COMPLETED; else if (mAlarmStatus == eAlarm_Status_Disabled) status_txt = cICalProperty_ALARM_X_ALARMSTATUS_DISABLED; AddProperty(CICalendarProperty(cICalProperty_ALARM_X_ALARMSTATUS, status_txt)); } void CICalendarVAlarm::EditAction(EAction_VAlarm action, CICalendarVAlarmAction* data) { // Remove existing RemoveProperties(cICalProperty_ACTION); mActionData->Remove(this); delete mActionData; mActionData = NULL; // Updated cached values mAction = action; mActionData = data; // Add new properties to alarm cdstring action_txt; switch(mAction) { case eAction_VAlarm_Audio: action_txt = cICalProperty_ACTION_AUDIO; break; case eAction_VAlarm_Display: action_txt = cICalProperty_ACTION_DISPLAY; break; case eAction_VAlarm_Email: action_txt = cICalProperty_ACTION_EMAIL; break; default: action_txt = cICalProperty_ACTION_PROCEDURE; break; } CICalendarProperty prop(cICalProperty_ACTION, action_txt); AddProperty(prop); mActionData->Add(this); } void CICalendarVAlarm::EditTrigger(const CICalendarDateTime& dt) { // Remove existing RemoveProperties(cICalProperty_TRIGGER); // Updated cached values mTriggerAbsolute = true; mTriggerOn = dt; // Add new CICalendarProperty prop(cICalProperty_TRIGGER, dt); AddProperty(prop); } void CICalendarVAlarm::EditTrigger(const CICalendarDuration& duration, bool trigger_start) { // Remove existing RemoveProperties(cICalProperty_TRIGGER); // Updated cached values mTriggerAbsolute = false; mTriggerBy = duration; mTriggerOnStart = trigger_start; // Add new (with attribute) CICalendarProperty prop(cICalProperty_TRIGGER, duration); CICalendarAttribute attr(cICalAttribute_RELATED, trigger_start ? cICalAttribute_RELATED_START : cICalAttribute_RELATED_END); prop.AddAttribute(attr); AddProperty(prop); } void CICalendarVAlarm::EditRepeats(unsigned long repeat, const CICalendarDuration& interval) { // Remove existing RemoveProperties(cICalProperty_REPEAT); RemoveProperties(cICalProperty_DURATION); // Updated cached values mRepeats = repeat; mRepeatInterval = interval; // Add new if (mRepeats > 0) { AddProperty(CICalendarProperty(cICalProperty_REPEAT, repeat)); AddProperty(CICalendarProperty(cICalProperty_DURATION, interval)); } } // Setup cache of trigger details void CICalendarVAlarm::InitNextTrigger() { // Do not bother if its completed if (mAlarmStatus == eAlarm_Status_Completed) return; mStatusInit = true; // Look for trigger immediately preceeding or equal to utc now CICalendarDateTime nowutc = CICalendarDateTime::GetNowUTC(); // Init done counter mDoneCount = 0; // Determine the first trigger CICalendarDateTime trigger; GetFirstTrigger(trigger); while(mDoneCount < mRepeats) { // See if next trigger is later than now CICalendarDateTime next_trigger = trigger + mRepeatInterval; if (next_trigger > nowutc) break; mDoneCount++; trigger = next_trigger; } // Check for completion if ((trigger == mLastTrigger) || (nowutc - trigger).GetTotalSeconds() > (24 * 60 * 60)) { if (mDoneCount == mRepeats) { mAlarmStatus = eAlarm_Status_Completed; return; } else { trigger = trigger + mRepeatInterval; mDoneCount++; } } mNextTrigger = trigger; } // Get the very first trigger for this alarm void CICalendarVAlarm::GetFirstTrigger(CICalendarDateTime& dt) { // If absolute trigger, use that if (IsTriggerAbsolute()) { // Get the trigger on dt = GetTriggerOn(); } else { // Get the parent embedder class (must be CICalendarComponentRecur type) const CICalendarComponentRecur* owner = dynamic_cast<const iCal::CICalendarComponentRecur*>(GetEmbedder()); if (owner != NULL) { // Determine time at which alarm will trigger iCal::CICalendarDateTime trigger = IsTriggerOnStart() ? owner->GetStart() : owner->GetEnd(); // Offset by duration dt = trigger + GetTriggerDuration(); } } } // return true and update dt to the next time the alarm should be triggered // if its repeating bool CICalendarVAlarm::AlarmTriggered(CICalendarDateTime& dt) { // Remove existing RemoveProperties(cICalProperty_ALARM_X_LASTTRIGGER); RemoveProperties(cICalProperty_ALARM_X_ALARMSTATUS); // Updated cached values mLastTrigger = dt; if (mDoneCount < mRepeats) { dt = mNextTrigger = mNextTrigger + mRepeatInterval; mDoneCount++; mAlarmStatus = eAlarm_Status_Pending; } else mAlarmStatus = eAlarm_Status_Completed; // Add new AddProperty(CICalendarProperty(cICalProperty_ALARM_X_LASTTRIGGER, dt)); cdstring status; if (mAlarmStatus == eAlarm_Status_Pending) status = cICalProperty_ALARM_X_ALARMSTATUS_PENDING; else if (mAlarmStatus == eAlarm_Status_Completed) status = cICalProperty_ALARM_X_ALARMSTATUS_COMPLETED; else if (mAlarmStatus == eAlarm_Status_Disabled) status = cICalProperty_ALARM_X_ALARMSTATUS_DISABLED; AddProperty(CICalendarProperty(cICalProperty_ALARM_X_ALARMSTATUS, status)); // Now update dt to the next alarm time return mAlarmStatus == eAlarm_Status_Pending; } void CICalendarVAlarm::CICalendarVAlarmAudio::Load(CICalendarVAlarm* valarm) { // Get properties valarm->LoadValue(cICalProperty_ACTION_X_SPEAKTEXT, mSpeakText); } void CICalendarVAlarm::CICalendarVAlarmAudio::Add(CICalendarVAlarm* valarm) { // Delete existing then add Remove(valarm); CICalendarProperty prop(cICalProperty_ACTION_X_SPEAKTEXT, mSpeakText); valarm->AddProperty(prop); } void CICalendarVAlarm::CICalendarVAlarmAudio::Remove(CICalendarVAlarm* valarm) { valarm->RemoveProperties(cICalProperty_ACTION_X_SPEAKTEXT); } void CICalendarVAlarm::CICalendarVAlarmDisplay::Load(CICalendarVAlarm* valarm) { // Get properties valarm->LoadValue(cICalProperty_DESCRIPTION, mDescription); } void CICalendarVAlarm::CICalendarVAlarmDisplay::Add(CICalendarVAlarm* valarm) { // Delete existing then add Remove(valarm); CICalendarProperty prop(cICalProperty_DESCRIPTION, mDescription); valarm->AddProperty(prop); } void CICalendarVAlarm::CICalendarVAlarmDisplay::Remove(CICalendarVAlarm* valarm) { valarm->RemoveProperties(cICalProperty_DESCRIPTION); } void CICalendarVAlarm::CICalendarVAlarmEmail::Load(CICalendarVAlarm* valarm) { // Get properties valarm->LoadValue(cICalProperty_DESCRIPTION, mDescription); valarm->LoadValue(cICalProperty_SUMMARY, mSummary); mAttendees.clear(); if (valarm->HasProperty(cICalProperty_ATTENDEE)) { // Get each attendee std::pair<CICalendarPropertyMap::const_iterator, CICalendarPropertyMap::const_iterator> range = valarm->GetProperties().equal_range(cICalProperty_ATTENDEE); for(CICalendarPropertyMap::const_iterator iter = range.first; iter != range.second; iter++) { // Get the attendee value const CICalendarCalAddressValue* attendee = (*iter).second.GetCalAddressValue(); if (attendee != NULL) { mAttendees.push_back(attendee->GetValue()); } } } } void CICalendarVAlarm::CICalendarVAlarmEmail::Add(CICalendarVAlarm* valarm) { // Delete existing then add Remove(valarm); { CICalendarProperty prop(cICalProperty_DESCRIPTION, mDescription); valarm->AddProperty(prop); } { CICalendarProperty prop(cICalProperty_SUMMARY, mSummary); valarm->AddProperty(prop); } for(cdstrvect::const_iterator iter = mAttendees.begin(); iter != mAttendees.end(); iter++) { CICalendarProperty prop(cICalProperty_ATTENDEE, *iter, CICalendarValue::eValueType_CalAddress); valarm->AddProperty(prop); } } void CICalendarVAlarm::CICalendarVAlarmEmail::Remove(CICalendarVAlarm* valarm) { valarm->RemoveProperties(cICalProperty_DESCRIPTION); valarm->RemoveProperties(cICalProperty_SUMMARY); valarm->RemoveProperties(cICalProperty_ATTENDEE); } void CICalendarVAlarm::CICalendarVAlarmUnknown::Load(CICalendarVAlarm* valarm) { } void CICalendarVAlarm::CICalendarVAlarmUnknown::Add(CICalendarVAlarm* valarm) { } void CICalendarVAlarm::CICalendarVAlarmUnknown::Remove(CICalendarVAlarm* valarm) { }
c++
code
13,940
2,349
// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "support/lockedpool.h" #include "support/cleanse.h" #if defined(HAVE_CONFIG_H) #include "config/build-config.h" #endif #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> #else #include <sys/mman.h> // for mmap #include <sys/resource.h> // for getrlimit #include <limits.h> // for PAGESIZE #include <unistd.h> // for sysconf #endif #include <algorithm> LockedPoolManager* LockedPoolManager::_instance = NULL; std::once_flag LockedPoolManager::init_flag; /*******************************************************************************/ // Utilities // /** Align up to power of 2 */ static inline size_t align_up(size_t x, size_t align) { return (x + align - 1) & ~(align - 1); } /*******************************************************************************/ // Implementation: Arena Arena::Arena(void *base_in, size_t size_in, size_t alignment_in): base(static_cast<char*>(base_in)), end(static_cast<char*>(base_in) + size_in), alignment(alignment_in) { // Start with one free chunk that covers the entire arena chunks_free.emplace(base, size_in); } Arena::~Arena() { } void* Arena::alloc(size_t size) { // Round to next multiple of alignment size = align_up(size, alignment); // Don't handle zero-sized chunks if (size == 0) return nullptr; // Pick a large enough free-chunk auto it = std::find_if(chunks_free.begin(), chunks_free.end(), [=](const std::map<char*, size_t>::value_type& chunk){ return chunk.second >= size; }); if (it == chunks_free.end()) return nullptr; // Create the used-chunk, taking its space from the end of the free-chunk auto alloced = chunks_used.emplace(it->first + it->second - size, size).first; if (!(it->second -= size)) chunks_free.erase(it); return reinterpret_cast<void*>(alloced->first); } /* extend the Iterator if other begins at its end */ template <class Iterator, class Pair> bool extend(Iterator it, const Pair& other) { if (it->first + it->second == other.first) { it->second += other.second; return true; } return false; } void Arena::free(void *ptr) { // Freeing the NULL pointer is OK. if (ptr == nullptr) { return; } // Remove chunk from used map auto i = chunks_used.find(static_cast<char*>(ptr)); if (i == chunks_used.end()) { throw std::runtime_error("Arena: invalid or double free"); } auto freed = *i; chunks_used.erase(i); // Add space to free map, coalescing contiguous chunks auto next = chunks_free.upper_bound(freed.first); auto prev = (next == chunks_free.begin()) ? chunks_free.end() : std::prev(next); if (prev == chunks_free.end() || !extend(prev, freed)) prev = chunks_free.emplace_hint(next, freed); if (next != chunks_free.end() && extend(prev, *next)) chunks_free.erase(next); } Arena::Stats Arena::stats() const { Arena::Stats r{ 0, 0, 0, chunks_used.size(), chunks_free.size() }; for (const auto& chunk: chunks_used) r.used += chunk.second; for (const auto& chunk: chunks_free) r.free += chunk.second; r.total = r.used + r.free; return r; } #ifdef ARENA_DEBUG void printchunk(char* base, size_t sz, bool used) { std::cout << "0x" << std::hex << std::setw(16) << std::setfill('0') << base << " 0x" << std::hex << std::setw(16) << std::setfill('0') << sz << " 0x" << used << std::endl; } void Arena::walk() const { for (const auto& chunk: chunks_used) printchunk(chunk.first, chunk.second, true); std::cout << std::endl; for (const auto& chunk: chunks_free) printchunk(chunk.first, chunk.second, false); std::cout << std::endl; } #endif /*******************************************************************************/ // Implementation: Win32LockedPageAllocator #ifdef WIN32 /** LockedPageAllocator specialized for Windows. */ class Win32LockedPageAllocator: public LockedPageAllocator { public: Win32LockedPageAllocator(); void* AllocateLocked(size_t len, bool *lockingSuccess); void FreeLocked(void* addr, size_t len); size_t GetLimit(); private: size_t page_size; }; Win32LockedPageAllocator::Win32LockedPageAllocator() { // Determine system page size in bytes SYSTEM_INFO sSysInfo; GetSystemInfo(&sSysInfo); page_size = sSysInfo.dwPageSize; } void *Win32LockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess) { len = align_up(len, page_size); void *addr = VirtualAlloc(nullptr, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (addr) { // VirtualLock is used to attempt to keep keying material out of swap. Note // that it does not provide this as a guarantee, but, in practice, memory // that has been VirtualLock'd almost never gets written to the pagefile // except in rare circumstances where memory is extremely low. *lockingSuccess = VirtualLock(const_cast<void*>(addr), len) != 0; } return addr; } void Win32LockedPageAllocator::FreeLocked(void* addr, size_t len) { len = align_up(len, page_size); memory_cleanse(addr, len); VirtualUnlock(const_cast<void*>(addr), len); } size_t Win32LockedPageAllocator::GetLimit() { // TODO is there a limit on windows, how to get it? return std::numeric_limits<size_t>::max(); } #endif /*******************************************************************************/ // Implementation: PosixLockedPageAllocator #ifndef WIN32 /** LockedPageAllocator specialized for OSes that don't try to be * special snowflakes. */ class PosixLockedPageAllocator: public LockedPageAllocator { public: PosixLockedPageAllocator(); void* AllocateLocked(size_t len, bool *lockingSuccess); void FreeLocked(void* addr, size_t len); size_t GetLimit(); private: size_t page_size; }; PosixLockedPageAllocator::PosixLockedPageAllocator() { // Determine system page size in bytes #if defined(PAGESIZE) // defined in limits.h page_size = PAGESIZE; #else // assume some POSIX OS page_size = sysconf(_SC_PAGESIZE); #endif } // Some systems (at least OS X) do not define MAP_ANONYMOUS yet and define // MAP_ANON which is deprecated #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS MAP_ANON #endif void *PosixLockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess) { void *addr; len = align_up(len, page_size); addr = mmap(nullptr, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (addr) { *lockingSuccess = mlock(addr, len) == 0; } return addr; } void PosixLockedPageAllocator::FreeLocked(void* addr, size_t len) { len = align_up(len, page_size); memory_cleanse(addr, len); munlock(addr, len); munmap(addr, len); } size_t PosixLockedPageAllocator::GetLimit() { #ifdef RLIMIT_MEMLOCK struct rlimit rlim; if (getrlimit(RLIMIT_MEMLOCK, &rlim) == 0) { if (rlim.rlim_cur != RLIM_INFINITY) { return rlim.rlim_cur; } } #endif return std::numeric_limits<size_t>::max(); } #endif /*******************************************************************************/ // Implementation: LockedPool LockedPool::LockedPool(std::unique_ptr<LockedPageAllocator> allocator_in, LockingFailed_Callback lf_cb_in): allocator(std::move(allocator_in)), lf_cb(lf_cb_in), cumulative_bytes_locked(0) { } LockedPool::~LockedPool() { } void* LockedPool::alloc(size_t size) { std::lock_guard<std::mutex> lock(mutex); // Don't handle impossible sizes if (size == 0 || size > ARENA_SIZE) return nullptr; // Try allocating from each current arena for (auto &arena: arenas) { void *addr = arena.alloc(size); if (addr) { return addr; } } // If that fails, create a new one if (new_arena(ARENA_SIZE, ARENA_ALIGN)) { return arenas.back().alloc(size); } return nullptr; } void LockedPool::free(void *ptr) { std::lock_guard<std::mutex> lock(mutex); // TODO we can do better than this linear search by keeping a map of arena // extents to arena, and looking up the address. for (auto &arena: arenas) { if (arena.addressInArena(ptr)) { arena.free(ptr); return; } } throw std::runtime_error("LockedPool: invalid address not pointing to any arena"); } LockedPool::Stats LockedPool::stats() const { std::lock_guard<std::mutex> lock(mutex); LockedPool::Stats r{0, 0, 0, cumulative_bytes_locked, 0, 0}; for (const auto &arena: arenas) { Arena::Stats i = arena.stats(); r.used += i.used; r.free += i.free; r.total += i.total; r.chunks_used += i.chunks_used; r.chunks_free += i.chunks_free; } return r; } bool LockedPool::new_arena(size_t size, size_t align) { bool locked; // If this is the first arena, handle this specially: Cap the upper size // by the process limit. This makes sure that the first arena will at least // be locked. An exception to this is if the process limit is 0: // in this case no memory can be locked at all so we'll skip past this logic. if (arenas.empty()) { size_t limit = allocator->GetLimit(); if (limit > 0) { size = std::min(size, limit); } } void *addr = allocator->AllocateLocked(size, &locked); if (!addr) { return false; } if (locked) { cumulative_bytes_locked += size; } else if (lf_cb) { // Call the locking-failed callback if locking failed if (!lf_cb()) { // If the callback returns false, free the memory and fail, otherwise consider the user warned and proceed. allocator->FreeLocked(addr, size); return false; } } arenas.emplace_back(allocator.get(), addr, size, align); return true; } LockedPool::LockedPageArena::LockedPageArena(LockedPageAllocator *allocator_in, void *base_in, size_t size_in, size_t align_in): Arena(base_in, size_in, align_in), base(base_in), size(size_in), allocator(allocator_in) { } LockedPool::LockedPageArena::~LockedPageArena() { allocator->FreeLocked(base, size); } /*******************************************************************************/ // Implementation: LockedPoolManager // LockedPoolManager::LockedPoolManager(std::unique_ptr<LockedPageAllocator> allocator_in): LockedPool(std::move(allocator_in), &LockedPoolManager::LockingFailed) { } bool LockedPoolManager::LockingFailed() { // TODO: log something but how? without including util.h return true; } void LockedPoolManager::CreateInstance() { // Using a local static instance guarantees that the object is initialized // when it's first needed and also deinitialized after all objects that use // it are done with it. I can think of one unlikely scenario where we may // have a static deinitialization order/problem, but the check in // LockedPoolManagerBase's destructor helps us detect if that ever happens. #ifdef WIN32 std::unique_ptr<LockedPageAllocator> allocator(new Win32LockedPageAllocator()); #else std::unique_ptr<LockedPageAllocator> allocator(new PosixLockedPageAllocator()); #endif static LockedPoolManager instance(std::move(allocator)); LockedPoolManager::_instance = &instance; }
c++
code
11,681
3,017
// // ssl/detail/handshake_op.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP #define BOOST_ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/ssl/detail/engine.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace ssl { namespace detail { class handshake_op { public: static BOOST_ASIO_CONSTEXPR const char* tracking_name() { return "ssl::stream<>::async_handshake"; } handshake_op(stream_base::handshake_type type) : type_(type) { } engine::want operator()(engine& eng, boost::system::error_code& ec, std::size_t& bytes_transferred) const { bytes_transferred = 0; return eng.handshake(type_, ec); } template <typename Handler> void call_handler(Handler& handler, const boost::system::error_code& ec, const std::size_t&) const { handler(ec); } private: stream_base::handshake_type type_; }; } // namespace detail } // namespace ssl } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP
c++
code
1,521
273
// 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. /********************************************************************** * tospace.cpp * * Compute fuzzy word spacing thresholds for each row. * I.e. set : max_nonspace * space_threshold * min_space * kern_size * space_size * for each row. * ONLY FOR PROPORTIONAL BLOCKS - FIXED PITCH IS ASSUMED ALREADY DONE * * Note: functions in this file were originally not members of any * class or enclosed by any namespace. Now they are all static members * of the Textord class. * **********************************************************************/ #include "drawtord.h" #include "ndminx.h" #include "statistc.h" #include "textord.h" #include "tovars.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #define MAXSPACING 128 /*max expected spacing in pix */ namespace tesseract { void Textord::to_spacing( ICOORD page_tr, //topright of page TO_BLOCK_LIST *blocks //blocks on page ) { TO_BLOCK_IT block_it; //iterator TO_BLOCK *block; //current block; TO_ROW_IT row_it; //row iterator TO_ROW *row; //current row int block_index; //block number int row_index; //row number //estimated width of real spaces for whole block int16_t block_space_gap_width; //estimated width of non space gaps for whole block int16_t block_non_space_gap_width; BOOL8 old_text_ord_proportional;//old fixed/prop result GAPMAP *gapmap = NULL; //map of big vert gaps in blk block_it.set_to_list (blocks); block_index = 1; for (block_it.mark_cycle_pt (); !block_it.cycled_list (); block_it.forward ()) { block = block_it.data (); gapmap = new GAPMAP (block); block_spacing_stats(block, gapmap, old_text_ord_proportional, block_space_gap_width, block_non_space_gap_width); // Make sure relative values of block-level space and non-space gap // widths are reasonable. The ratio of 1:3 is also used in // block_spacing_stats, to corrrect the block_space_gap_width // Useful for arabic and hindi, when the non-space gap width is // often over-estimated and should not be trusted. A similar ratio // is found in block_spacing_stats. if (tosp_old_to_method && tosp_old_to_constrain_sp_kn && (float) block_space_gap_width / block_non_space_gap_width < 3.0) { block_non_space_gap_width = (int16_t) floor (block_space_gap_width / 3.0); } row_it.set_to_list (block->get_rows ()); row_index = 1; for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) { row = row_it.data (); if ((row->pitch_decision == PITCH_DEF_PROP) || (row->pitch_decision == PITCH_CORR_PROP)) { if ((tosp_debug_level > 0) && !old_text_ord_proportional) tprintf ("Block %d Row %d: Now Proportional\n", block_index, row_index); row_spacing_stats(row, gapmap, block_index, row_index, block_space_gap_width, block_non_space_gap_width); } else { if ((tosp_debug_level > 0) && old_text_ord_proportional) tprintf ("Block %d Row %d: Now Fixed Pitch Decision:%d fp flag:%f\n", block_index, row_index, row->pitch_decision, row->fixed_pitch); } #ifndef GRAPHICS_DISABLED if (textord_show_initial_words) plot_word_decisions (to_win, (int16_t) row->fixed_pitch, row); #endif row_index++; } delete gapmap; block_index++; } } /************************************************************************* * block_spacing_stats() *************************************************************************/ void Textord::block_spacing_stats( TO_BLOCK *block, GAPMAP *gapmap, BOOL8 &old_text_ord_proportional, int16_t &block_space_gap_width, // resulting estimate int16_t &block_non_space_gap_width // resulting estimate ) { TO_ROW_IT row_it; // row iterator TO_ROW *row; // current row BLOBNBOX_IT blob_it; // iterator STATS centre_to_centre_stats (0, MAXSPACING); // DEBUG USE ONLY STATS all_gap_stats (0, MAXSPACING); STATS space_gap_stats (0, MAXSPACING); int16_t minwidth = MAXSPACING; // narrowest blob TBOX blob_box; TBOX prev_blob_box; int16_t centre_to_centre; int16_t gap_width; float real_space_threshold; float iqr_centre_to_centre; // DEBUG USE ONLY float iqr_all_gap_stats; // DEBUG USE ONLY int32_t end_of_row; int32_t row_length; row_it.set_to_list (block->get_rows ()); for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) { row = row_it.data (); if (!row->blob_list ()->empty () && (!tosp_only_use_prop_rows || (row->pitch_decision == PITCH_DEF_PROP) || (row->pitch_decision == PITCH_CORR_PROP))) { blob_it.set_to_list (row->blob_list ()); blob_it.mark_cycle_pt (); end_of_row = blob_it.data_relative (-1)->bounding_box ().right (); if (tosp_use_pre_chopping) blob_box = box_next_pre_chopped (&blob_it); else if (tosp_stats_use_xht_gaps) blob_box = reduced_box_next (row, &blob_it); else blob_box = box_next (&blob_it); row_length = end_of_row - blob_box.left (); if (blob_box.width () < minwidth) minwidth = blob_box.width (); prev_blob_box = blob_box; while (!blob_it.cycled_list ()) { if (tosp_use_pre_chopping) blob_box = box_next_pre_chopped (&blob_it); else if (tosp_stats_use_xht_gaps) blob_box = reduced_box_next (row, &blob_it); else blob_box = box_next (&blob_it); if (blob_box.width () < minwidth) minwidth = blob_box.width (); int16_t left = prev_blob_box.right(); int16_t right = blob_box.left(); gap_width = right - left; if (!ignore_big_gap(row, row_length, gapmap, left, right)) { all_gap_stats.add (gap_width, 1); centre_to_centre = (right + blob_box.right () - (prev_blob_box.left () + left)) / 2; //DEBUG centre_to_centre_stats.add (centre_to_centre, 1); // DEBUG } prev_blob_box = blob_box; } } } //Inadequate samples if (all_gap_stats.get_total () <= 1) { block_non_space_gap_width = minwidth; block_space_gap_width = -1; //No est. space width //DEBUG old_text_ord_proportional = TRUE; } else { /* For debug only ..... */ iqr_centre_to_centre = centre_to_centre_stats.ile (0.75) - centre_to_centre_stats.ile (0.25); iqr_all_gap_stats = all_gap_stats.ile (0.75) - all_gap_stats.ile (0.25); old_text_ord_proportional = iqr_centre_to_centre * 2 > iqr_all_gap_stats; /* .......For debug only */ /* The median of the gaps is used as an estimate of the NON-SPACE gap width. This RELIES on the assumption that there are more gaps WITHIN words than BETWEEN words in a block Now try to estimate the width of a real space for all real spaces in the block. Do this by using a crude threshold to ignore "narrow" gaps, then find the median of the "wide" gaps and use this. */ block_non_space_gap_width = (int16_t) floor (all_gap_stats.median ()); // median gap row_it.set_to_list (block->get_rows ()); for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) { row = row_it.data (); if (!row->blob_list ()->empty () && (!tosp_only_use_prop_rows || (row->pitch_decision == PITCH_DEF_PROP) || (row->pitch_decision == PITCH_CORR_PROP))) { real_space_threshold = MAX (tosp_init_guess_kn_mult * block_non_space_gap_width, tosp_init_guess_xht_mult * row->xheight); blob_it.set_to_list (row->blob_list ()); blob_it.mark_cycle_pt (); end_of_row = blob_it.data_relative (-1)->bounding_box ().right (); if (tosp_use_pre_chopping) blob_box = box_next_pre_chopped (&blob_it); else if (tosp_stats_use_xht_gaps) blob_box = reduced_box_next (row, &blob_it); else blob_box = box_next (&blob_it); row_length = blob_box.left () - end_of_row; prev_blob_box = blob_box; while (!blob_it.cycled_list ()) { if (tosp_use_pre_chopping) blob_box = box_next_pre_chopped (&blob_it); else if (tosp_stats_use_xht_gaps) blob_box = reduced_box_next (row, &blob_it); else blob_box = box_next (&blob_it); int16_t left = prev_blob_box.right(); int16_t right = blob_box.left(); gap_width = right - left; if ((gap_width > real_space_threshold) && !ignore_big_gap(row, row_length, gapmap, left, right)) { /* If tosp_use_cert_spaces is enabled, the estimate of the space gap is restricted to obvious spaces - those wider than half the xht or those with wide blobs on both sides - i.e not things that are suspect 1's or punctuation that is sometimes widely spaced. */ if (!tosp_block_use_cert_spaces || (gap_width > tosp_fuzzy_space_factor2 * row->xheight) || ((gap_width > tosp_fuzzy_space_factor1 * row->xheight) && (!tosp_narrow_blobs_not_cert || (!narrow_blob (row, prev_blob_box) && !narrow_blob (row, blob_box)))) || (wide_blob (row, prev_blob_box) && wide_blob (row, blob_box))) space_gap_stats.add (gap_width, 1); } prev_blob_box = blob_box; } } } //Inadequate samples if (space_gap_stats.get_total () <= 2) block_space_gap_width = -1;//No est. space width else block_space_gap_width = MAX ((int16_t) floor (space_gap_stats.median ()), 3 * block_non_space_gap_width); } } /************************************************************************* * row_spacing_stats() * Set values for min_space, max_non_space based on row stats only * If failure - return 0 values. *************************************************************************/ void Textord::row_spacing_stats( TO_ROW *row, GAPMAP *gapmap, int16_t block_idx, int16_t row_idx, int16_t block_space_gap_width, //estimate for block int16_t block_non_space_gap_width //estimate for block ) { //iterator BLOBNBOX_IT blob_it = row->blob_list (); STATS all_gap_stats (0, MAXSPACING); STATS cert_space_gap_stats (0, MAXSPACING); STATS all_space_gap_stats (0, MAXSPACING); STATS small_gap_stats (0, MAXSPACING); TBOX blob_box; TBOX prev_blob_box; int16_t gap_width; int16_t real_space_threshold = 0; int16_t max = 0; int16_t index; int16_t large_gap_count = 0; BOOL8 suspected_table; int32_t max_max_nonspace; //upper bound BOOL8 good_block_space_estimate = block_space_gap_width > 0; int32_t end_of_row; int32_t row_length = 0; float sane_space; int32_t sane_threshold; /* Collect first pass stats for row */ if (!good_block_space_estimate) block_space_gap_width = int16_t (floor (row->xheight / 2)); if (!row->blob_list ()->empty ()) { if (tosp_threshold_bias1 > 0) real_space_threshold = block_non_space_gap_width + int16_t (floor (0.5 + tosp_threshold_bias1 * (block_space_gap_width - block_non_space_gap_width))); else real_space_threshold = //Old TO method (block_space_gap_width + block_non_space_gap_width) / 2; blob_it.set_to_list (row->blob_list ()); blob_it.mark_cycle_pt (); end_of_row = blob_it.data_relative (-1)->bounding_box ().right (); if (tosp_use_pre_chopping) blob_box = box_next_pre_chopped (&blob_it); else if (tosp_stats_use_xht_gaps) blob_box = reduced_box_next (row, &blob_it); else blob_box = box_next (&blob_it); row_length = end_of_row - blob_box.left (); prev_blob_box = blob_box; while (!blob_it.cycled_list ()) { if (tosp_use_pre_chopping) blob_box = box_next_pre_chopped (&blob_it); else if (tosp_stats_use_xht_gaps) blob_box = reduced_box_next (row, &blob_it); else blob_box = box_next (&blob_it); int16_t left = prev_blob_box.right(); int16_t right = blob_box.left(); gap_width = right - left; if (ignore_big_gap(row, row_length, gapmap, left, right)) { large_gap_count++; } else { if (gap_width >= real_space_threshold) { if (!tosp_row_use_cert_spaces || (gap_width > tosp_fuzzy_space_factor2 * row->xheight) || ((gap_width > tosp_fuzzy_space_factor1 * row->xheight) && (!tosp_narrow_blobs_not_cert || (!narrow_blob (row, prev_blob_box) && !narrow_blob (row, blob_box)))) || (wide_blob (row, prev_blob_box) && wide_blob (row, blob_box))) cert_space_gap_stats.add (gap_width, 1); all_space_gap_stats.add (gap_width, 1); } else small_gap_stats.add (gap_width, 1); all_gap_stats.add (gap_width, 1); } prev_blob_box = blob_box; } } suspected_table = (large_gap_count > 1) || ((large_gap_count > 0) && (all_gap_stats.get_total () <= tosp_few_samples)); /* Now determine row kern size, space size and threshold */ if ((cert_space_gap_stats.get_total () >= tosp_enough_space_samples_for_median) || ((suspected_table || all_gap_stats.get_total () <= tosp_short_row) && cert_space_gap_stats.get_total () > 0)) { old_to_method(row, &all_gap_stats, &cert_space_gap_stats, &small_gap_stats, block_space_gap_width, block_non_space_gap_width); } else { if (!tosp_recovery_isolated_row_stats || !isolated_row_stats (row, gapmap, &all_gap_stats, suspected_table, block_idx, row_idx)) { if (tosp_row_use_cert_spaces && (tosp_debug_level > 5)) tprintf ("B:%d R:%d -- Inadequate certain spaces.\n", block_idx, row_idx); if (tosp_row_use_cert_spaces1 && good_block_space_estimate) { //Use block default row->space_size = block_space_gap_width; if (all_gap_stats.get_total () > tosp_redo_kern_limit) row->kern_size = all_gap_stats.median (); else row->kern_size = block_non_space_gap_width; row->space_threshold = int32_t (floor ((row->space_size + row->kern_size) / tosp_old_sp_kn_th_factor)); } else old_to_method(row, &all_gap_stats, &all_space_gap_stats, &small_gap_stats, block_space_gap_width, block_non_space_gap_width); } } if (tosp_improve_thresh && !suspected_table) improve_row_threshold(row, &all_gap_stats); /* Now lets try to be careful not to do anything silly with tables when we are ignoring big gaps*/ if (tosp_sanity_method == 0) { if (suspected_table && (row->space_size < tosp_table_kn_sp_ratio * row->kern_size)) { if (tosp_debug_level > 5) tprintf("B:%d R:%d -- DON'T BELIEVE SPACE %3.2f %d %3.2f.\n", block_idx, row_idx, row->kern_size, row->space_threshold, row->space_size); row->space_threshold = (int32_t) (tosp_table_kn_sp_ratio * row->kern_size); row->space_size = MAX (row->space_threshold + 1, row->xheight); } } else if (tosp_sanity_method == 1) { sane_space = row->space_size; /* NEVER let space size get too close to kern size */ if ((row->space_size < tosp_min_sane_kn_sp * MAX (row->kern_size, 2.5)) || ((row->space_size - row->kern_size) < (tosp_silly_kn_sp_gap * row->xheight))) { if (good_block_space_estimate && (block_space_gap_width >= tosp_min_sane_kn_sp * row->kern_size)) sane_space = block_space_gap_width; else sane_space = MAX (tosp_min_sane_kn_sp * MAX (row->kern_size, 2.5), row->xheight / 2); if (tosp_debug_level > 5) tprintf("B:%d R:%d -- DON'T BELIEVE SPACE %3.2f %d %3.2f -> %3.2f.\n", block_idx, row_idx, row->kern_size, row->space_threshold, row->space_size, sane_space); row->space_size = sane_space; row->space_threshold = int32_t (floor ((row->space_size + row->kern_size) / tosp_old_sp_kn_th_factor)); } /* NEVER let threshold get VERY far away from kern */ sane_threshold = int32_t (floor (tosp_max_sane_kn_thresh * MAX (row->kern_size, 2.5))); if (row->space_threshold > sane_threshold) { if (tosp_debug_level > 5) tprintf("B:%d R:%d -- DON'T BELIEVE THRESH %3.2f %d %3.2f->%d.\n", block_idx, row_idx, row->kern_size, row->space_threshold, row->space_size, sane_threshold); row->space_threshold = sane_threshold; if (row->space_size <= sane_threshold) row->space_size = row->space_threshold + 1.0f; } /* Beware of tables - there may be NO spaces */ if (suspected_table) { sane_space = MAX (tosp_table_kn_sp_ratio * row->kern_size, tosp_table_xht_sp_ratio * row->xheight); sane_threshold = int32_t (floor ((sane_space + row->kern_size) / 2)); if ((row->space_size < sane_space) || (row->space_threshold < sane_threshold)) { if (tosp_debug_level > 5) tprintf ("B:%d R:%d -- SUSPECT NO SPACES %3.2f %d %3.2f.\n", block_idx, row_idx, row->kern_size, row->space_threshold, row->space_size); //the minimum sane value row->space_threshold = (int32_t) sane_space; row->space_size = MAX (row->space_threshold + 1, row->xheight); } } } /* Now lets try to put some error limits on the threshold */ if (tosp_old_to_method) { /* Old textord made a space if gap >= threshold */ //NO FUZZY SPACES YET row->max_nonspace = row->space_threshold; //NO FUZZY SPACES YET row->min_space = row->space_threshold + 1; } else { /* Any gap greater than 0.6 x-ht is bound to be a space (isn't it:-) */ row->min_space = MIN (int32_t (ceil (tosp_fuzzy_space_factor * row->xheight)), int32_t (row->space_size)); if (row->min_space <= row->space_threshold) // Don't be silly row->min_space = row->space_threshold + 1; /* Lets try to guess the max certain kern gap by looking at the cluster of kerns for the row. The ro
c++
code
20,000
3,915
#pragma once #include "frame.hh" #include "media.hh" #include "queue.hh" namespace uvg_rtp { namespace formats { class h26x : public media { public: h26x(uvg_rtp::socket *socket, uvg_rtp::rtp *rtp, int flags); virtual ~h26x(); /* Find H26x start code from "data" * This process is the same for H26{4,5,6} * * Return the offset of the start code on success * Return -1 if no start code was found */ ssize_t find_h26x_start_code(uint8_t *data, size_t len, size_t offset, uint8_t& start_len); /* Top-level push_frame() called by the Media class * Sets up the frame queue for the send operation * * Return RTP_OK on success * Return RTP_INVALID_VALUE if one of the parameters is invalid */ rtp_error_t push_media_frame(uint8_t *data, size_t data_len, int flags); /* Last push_frame() on the call stack which splits the input frame ("data") * into NAL units using find_h26x_start_code() and fragments the NAL unit * into Fragmentation Units (FUs) which are pushed to frame queue * * Return RTP_OK on success * Return RTP_INVALID_VALUE if one the parameters is invalid */ rtp_error_t push_h26x_frame(uint8_t *data, size_t data_len); protected: /* Each H26x class overrides this function with their custom NAL pushing function */ virtual rtp_error_t push_nal_unit(uint8_t *data, size_t data_len, bool more); }; }; };
c++
code
1,746
285
/* * Copyright (C) 2017, Yuyu Hsueh. * * 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 OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file turtleCtrl.cpp * @brief This is the source code for the turtleCtrller node, which has a simple * PD controller that takes the displacement value as input. The output is * published to the turtlebot actuator in terms of linear and angular velocities. * @author Yuyu Hsueh * @Copyright 2017, Yuyu Hsueh */ #include <ros/ros.h> #include <ros/spinner.h> #include <ros/callback_queue.h> #include "TurtleCtrl.hpp" int main(int argc, char **argv) { ros::init(argc, argv, "turtleCtrller"); TurtleCtrl turtleCtrlObj; ros::Rate loop_rate(5); // 5 Htz while (ros::ok()) { ros::spinOnce(); loop_rate.sleep(); if (turtleCtrlObj.terminate) break; } ROS_INFO("Shutting down"); ros::shutdown(); }
c++
code
2,091
427
// 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 "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/metrics/field_trial.h" #include "base/metrics/statistics_recorder.h" #include "chrome/browser/net/prediction_options.h" #include "chrome/browser/predictors/resource_prefetch_common.h" #include "chrome/browser/predictors/resource_prefetch_predictor.h" #include "chrome/browser/predictors/resource_prefetch_predictor_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_profile.h" #include "components/prefs/pref_service.h" #include "components/variations/entropy_provider.h" #include "content/public/test/test_browser_thread.h" #include "net/base/network_change_notifier.h" #include "testing/gtest/include/gtest/gtest.h" using chrome_browser_net::NetworkPredictionOptions; using net::NetworkChangeNotifier; namespace { class MockNetworkChangeNotifierWIFI : public NetworkChangeNotifier { public: ConnectionType GetCurrentConnectionType() const override { return NetworkChangeNotifier::CONNECTION_WIFI; } }; class MockNetworkChangeNotifier4G : public NetworkChangeNotifier { public: ConnectionType GetCurrentConnectionType() const override { return NetworkChangeNotifier::CONNECTION_4G; } }; } // namespace namespace predictors { class ResourcePrefetchCommonTest : public testing::Test { public: ResourcePrefetchCommonTest(); void SetUp() override; void CreateTestFieldTrial(const std::string& name, const std::string& group_name) { base::FieldTrial* trial = base::FieldTrialList::CreateFieldTrial( name, group_name); trial->group(); } void SetPreference(NetworkPredictionOptions value) { profile_->GetPrefs()->SetInteger(prefs::kNetworkPredictionOptions, value); } void TestIsPrefetchDisabled(ResourcePrefetchPredictorConfig& config) { EXPECT_FALSE(config.IsLearningEnabled()); EXPECT_FALSE(config.IsPrefetchingEnabled(profile_.get())); EXPECT_FALSE(config.IsURLLearningEnabled()); EXPECT_FALSE(config.IsHostLearningEnabled()); EXPECT_FALSE(config.IsURLPrefetchingEnabled(profile_.get())); EXPECT_FALSE(config.IsHostPrefetchingEnabled(profile_.get())); } void TestIsPrefetchEnabled(ResourcePrefetchPredictorConfig& config) { EXPECT_TRUE(config.IsLearningEnabled()); EXPECT_TRUE(config.IsPrefetchingEnabled(profile_.get())); EXPECT_TRUE(config.IsURLLearningEnabled()); EXPECT_TRUE(config.IsHostLearningEnabled()); EXPECT_TRUE(config.IsURLPrefetchingEnabled(profile_.get())); EXPECT_TRUE(config.IsHostPrefetchingEnabled(profile_.get())); } void TestIsPrefetchLearning(ResourcePrefetchPredictorConfig& config) { EXPECT_TRUE(config.IsLearningEnabled()); EXPECT_FALSE(config.IsPrefetchingEnabled(profile_.get())); EXPECT_TRUE(config.IsURLLearningEnabled()); EXPECT_TRUE(config.IsHostLearningEnabled()); EXPECT_FALSE(config.IsURLPrefetchingEnabled(profile_.get())); EXPECT_FALSE(config.IsHostPrefetchingEnabled(profile_.get())); } void TestIsDefaultExtraConfig(ResourcePrefetchPredictorConfig& config) { EXPECT_FALSE(config.IsLowConfidenceForTest()); EXPECT_FALSE(config.IsHighConfidenceForTest()); EXPECT_FALSE(config.IsMoreResourcesEnabledForTest()); EXPECT_FALSE(config.IsSmallDBEnabledForTest()); } protected: base::MessageLoop loop_; content::TestBrowserThread ui_thread_; std::unique_ptr<TestingProfile> profile_; private: std::unique_ptr<base::FieldTrialList> field_trial_list_; }; ResourcePrefetchCommonTest::ResourcePrefetchCommonTest() : loop_(base::MessageLoop::TYPE_DEFAULT), ui_thread_(content::BrowserThread::UI, &loop_), profile_(new TestingProfile()) { } void ResourcePrefetchCommonTest::SetUp() { field_trial_list_.reset(new base::FieldTrialList( base::MakeUnique<metrics::SHA1EntropyProvider>( "ResourcePrefetchCommonTest"))); base::StatisticsRecorder::Initialize(); } TEST_F(ResourcePrefetchCommonTest, FieldTrialNotSpecified) { ResourcePrefetchPredictorConfig config; EXPECT_FALSE( IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchDisabled(config); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingDisabled) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Disabled"); ResourcePrefetchPredictorConfig config; EXPECT_FALSE( IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchDisabled(config); } TEST_F(ResourcePrefetchCommonTest, FieldTrialLearningHost) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Learning:Predictor=Host"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); EXPECT_TRUE(config.IsLearningEnabled()); EXPECT_FALSE(config.IsPrefetchingEnabled(profile_.get())); EXPECT_FALSE(config.IsURLLearningEnabled()); EXPECT_TRUE(config.IsHostLearningEnabled()); EXPECT_FALSE(config.IsURLPrefetchingEnabled(profile_.get())); EXPECT_FALSE(config.IsHostPrefetchingEnabled(profile_.get())); TestIsDefaultExtraConfig(config); } TEST_F(ResourcePrefetchCommonTest, FieldTrialLearningURL) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Learning:Predictor=Url"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); EXPECT_TRUE(config.IsLearningEnabled()); EXPECT_FALSE(config.IsPrefetchingEnabled(profile_.get())); EXPECT_TRUE(config.IsURLLearningEnabled()); EXPECT_FALSE(config.IsHostLearningEnabled()); EXPECT_FALSE(config.IsURLPrefetchingEnabled(profile_.get())); EXPECT_FALSE(config.IsHostPrefetchingEnabled(profile_.get())); TestIsDefaultExtraConfig(config); } TEST_F(ResourcePrefetchCommonTest, FieldTrialLearning) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Learning"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchLearning(config); TestIsDefaultExtraConfig(config); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingHost) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled:Predictor=Host"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); EXPECT_TRUE(config.IsLearningEnabled()); EXPECT_TRUE(config.IsPrefetchingEnabled(profile_.get())); EXPECT_FALSE(config.IsURLLearningEnabled()); EXPECT_TRUE(config.IsHostLearningEnabled()); EXPECT_FALSE(config.IsURLPrefetchingEnabled(profile_.get())); EXPECT_TRUE(config.IsHostPrefetchingEnabled(profile_.get())); TestIsDefaultExtraConfig(config); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingURL) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled:Predictor=Url"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); EXPECT_TRUE(config.IsLearningEnabled()); EXPECT_TRUE(config.IsPrefetchingEnabled(profile_.get())); EXPECT_TRUE(config.IsURLLearningEnabled()); EXPECT_FALSE(config.IsHostLearningEnabled()); EXPECT_TRUE(config.IsURLPrefetchingEnabled(profile_.get())); EXPECT_FALSE(config.IsHostPrefetchingEnabled(profile_.get())); TestIsDefaultExtraConfig(config); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetching) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchEnabled(config); TestIsDefaultExtraConfig(config); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingLowConfidence) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled:Confidence=Low"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchEnabled(config); EXPECT_TRUE(config.IsLowConfidenceForTest()); EXPECT_FALSE(config.IsHighConfidenceForTest()); EXPECT_FALSE(config.IsMoreResourcesEnabledForTest()); EXPECT_FALSE(config.IsSmallDBEnabledForTest()); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingHighConfidence) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled:Confidence=High"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchEnabled(config); EXPECT_FALSE(config.IsLowConfidenceForTest()); EXPECT_TRUE(config.IsHighConfidenceForTest()); EXPECT_FALSE(config.IsMoreResourcesEnabledForTest()); EXPECT_FALSE(config.IsSmallDBEnabledForTest()); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingMoreResources) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Learning:MoreResources=Enabled"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchLearning(config); EXPECT_FALSE(config.IsLowConfidenceForTest()); EXPECT_FALSE(config.IsHighConfidenceForTest()); EXPECT_TRUE(config.IsMoreResourcesEnabledForTest()); EXPECT_FALSE(config.IsSmallDBEnabledForTest()); } TEST_F(ResourcePrefetchCommonTest, FieldTrialLearningSmallDB) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Learning:SmallDB=Enabled"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchLearning(config); EXPECT_FALSE(config.IsLowConfidenceForTest()); EXPECT_FALSE(config.IsHighConfidenceForTest()); EXPECT_FALSE(config.IsMoreResourcesEnabledForTest()); EXPECT_TRUE(config.IsSmallDBEnabledForTest()); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingSmallDB) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled:SmallDB=Enabled"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchEnabled(config); EXPECT_FALSE(config.IsLowConfidenceForTest()); EXPECT_FALSE(config.IsHighConfidenceForTest()); EXPECT_FALSE(config.IsMoreResourcesEnabledForTest()); EXPECT_TRUE(config.IsSmallDBEnabledForTest()); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingSmallDBLowConfidence) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled:SmallDB=Enabled:Confidence=Low"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchEnabled(config); EXPECT_TRUE(config.IsLowConfidenceForTest()); EXPECT_FALSE(config.IsHighConfidenceForTest()); EXPECT_FALSE(config.IsMoreResourcesEnabledForTest()); EXPECT_TRUE(config.IsSmallDBEnabledForTest()); } TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingSmallDBHighConfidence) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled:SmallDB=Enabled:Confidence=High"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchEnabled(config); EXPECT_FALSE(config.IsLowConfidenceForTest()); EXPECT_TRUE(config.IsHighConfidenceForTest()); EXPECT_FALSE(config.IsMoreResourcesEnabledForTest()); EXPECT_TRUE(config.IsSmallDBEnabledForTest()); } // Verifies whether prefetching in the field trial is disabled according to // the network type. But learning should not be disabled by network. TEST_F(ResourcePrefetchCommonTest, FieldTrialPrefetchingDisabledByNetwork) { CreateTestFieldTrial("SpeculativeResourcePrefetching", "Prefetching=Enabled"); ResourcePrefetchPredictorConfig config; EXPECT_TRUE(IsSpeculativeResourcePrefetchingEnabled(profile_.get(), &config)); TestIsPrefetchEnabled(config); // Set preference to WIFI_ONLY: prefetch when not on cellular. SetPreference(NetworkPredictionOptions::NETWORK_PREDICTION_WIFI_ONLY); { std::unique_ptr<NetworkChangeNotifier> mock( new MockNetworkChangeNotifierWIFI); TestIsPrefetchEnabled(config); } { std::unique_ptr<NetworkChangeNotifier> mock( new MockNetworkChangeNotifier4G); TestIsPrefetchLearning(config); } // Set preference to NEVER: never prefetch. SetPreference(NetworkPredictionOptions::NETWORK_PREDICTION_NEVER); { std::unique_ptr<NetworkChangeNotifier> mock( new MockNetworkChangeNotifierWIFI); TestIsPrefetchLearning(config); } { std::unique_ptr<NetworkChangeNotifier> mock( new MockNetworkChangeNotifier4G); TestIsPrefetchLearning(config); } } } // namespace predictors
c++
code
13,381
2,059