hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
fa404ef86985f3f5f1cc24dbb2268bc6f72c6bc1
5,512
cpp
C++
nucleo_boy_fw/src/ap/EngineMETA/Object.cpp
chcbaram/nucleo_boy
5a2d19f927e6f3b9ac6a86ab7e91825a0ddb7b6d
[ "Apache-2.0" ]
null
null
null
nucleo_boy_fw/src/ap/EngineMETA/Object.cpp
chcbaram/nucleo_boy
5a2d19f927e6f3b9ac6a86ab7e91825a0ddb7b6d
[ "Apache-2.0" ]
null
null
null
nucleo_boy_fw/src/ap/EngineMETA/Object.cpp
chcbaram/nucleo_boy
5a2d19f927e6f3b9ac6a86ab7e91825a0ddb7b6d
[ "Apache-2.0" ]
null
null
null
#include "Object.h" #include "Engine.h" #include "Toolbox.h" Object::Object() { init(); } Object::Object(float X, float Y, float W, float H, float VX, float VY) { init(); x = X; y = Y; vx = VX; vy = VY; width = W; height = H; } void Object::init() { x = random(8, 72); y = random(8, 56); vx = 0; vy = 0; ax = 0; ay = 0; width = 6; height = 6; bounce = 0.8; friction = 0.9; density = 1.2; life = 10; collideMap = true; collideObjects = true; justCreated = true; color = GRAY; } void Object::die() { Engine::addObject(new Particle(x, y , vx, -3, width, height, false)); } void Object::update() { updatePhysics(); //limit speeds vx = constrain(vx, -7, 7); vy = constrain(vy, -7, 7); if (abs(vx) < 0.02) vx = 0; if (abs(vy) < 0.02) vy = 0; vx += ax; x += vx; collideMapX(); vy += ay; y += vy; collideMapY(); } void Object::updatePhysics() { //water physics if (collideMap && (Engine::map->getTile(getCenterX(), getCenterY()) == 2)) { vy += (Engine::gravity * (density - 1)); vy *= 0.6; vx *= 0.6; } else { //normal physics vy += (Engine::gravity * density); } } int Object::collideMapX() { if (collideMap) { if (vx > 0) { if ((Engine::map->getTile(x + width, y) == 1) || (Engine::map->getTile(x + width, y + height) == 1)) { int tileX = (((int)(x + width) / (int)Engine::map->tileWidth) * (int)Engine::map->tileWidth); x = tileX - width - 0.01; vx *= - bounce; vy *= friction; return 1; } } else { if ((Engine::map->getTile(x, y) == 1) || (Engine::map->getTile(x, y + height) == 1)) { int tileX = (((int)x / (int)Engine::map->tileWidth) * (int)Engine::map->tileWidth); x = tileX + Engine::map->tileWidth + 0.01; vx *= - bounce; vy *= friction; return 1; } } } return 0; } int Object::collideMapY() { if (collideMap) { if (vy > 0) { if ((Engine::map->getTile(x, y + height) == 1) || (Engine::map->getTile(x + width, y + height) == 1)) { int tileY = (((int)(y + height) / (int)Engine::map->tileHeight) * (int)Engine::map->tileHeight); y = tileY - height - 0.01; vy *= - bounce; vx *= friction; return 1; } } else { if ((Engine::map->getTile(x, y) == 1) || (Engine::map->getTile(x + width, y) == 1)) { int tileY = (((int)y / (int)Engine::map->tileHeight) * (int)Engine::map->tileHeight); y = tileY + Engine::map->tileHeight + 0.01; vy *= - bounce; vx *= friction; return 1; } } } return 0; } void Object::interact(Object * obj) { if (collideObjects && obj->collideObjects) { if (colliding(obj)) { if ((vx == 0) && (vy == 0)) { return; } //distance between centers float dx, dy; //penetration depth float px, py; dx = obj->getCenterX() - getCenterX(); dy = obj->getCenterY() - getCenterY(); if ((dx >= 0) && (dy >= 0)) { //bottom right corner px = (x + width) - obj->x; py = (y + height) - obj->y; } else if ((dx >= 0) && (dy <= 0)) { //top right corner px = (x + width) - obj->x; py = y - (obj->y + obj->height); } else if ((dx <= 0) && (dy <= 0)) { //top left corner px = x - (obj->x + obj->width); py = y - (obj->y + obj->height); } else { //bottom left corner px = x - (obj->x + obj->width); py = (y + height) - obj->y; } if (abs(px) < abs(py)) { //horizontal collision x -= (px + 0.01); float v1 = vx; float m1 = width * height * density; float v2 = obj->vx; float m2 = obj->width * obj->height * obj->density; vx = v1 * (m1 - m2) / (m1 + m2) + v2 * 2 * m2 / (m1 + m2); obj->vx = v1 * 2 * m1 / (m1 + m2) + v2 * (m2 - m1) / (m1 + m2); vx *= obj->bounce * bounce; obj->vx *= obj->bounce * bounce; //friction float fvy = (vy - obj->vy) * (friction + obj->friction) / 2; vy -= fvy; obj->vy += fvy; } else { //vertical collision y -= (py + 0.01); float v1 = vy; float m1 = width * height * density; float v2 = obj->vx; float m2 = obj->width * obj->height * obj->density; vy = v1 * (m1 - m2) / (m1 + m2) + v2 * 2 * m2 / (m1 + m2); obj->vy = v1 * 2 * m1 / (m1 + m2) + v2 * (m2 - m1) / (m1 + m2); vy *= obj->bounce * bounce; obj->vy *= obj->bounce * bounce; //friction float fvx = (vx - obj->vx) * (friction + obj->friction) / 2; vx -= fvx; obj->vx += fvx; } } } } void Object::draw() { gb.display.setColor(color); gb.display.drawRect((int)(x + 0.05) - (int)Engine::cameraX, (int)(y + 0.05) - (int)Engine::cameraY, width, height); } int Object::collidingTile() { int tile = -1; int temp = Engine::map->getTile(x, y); if (temp > tile) tile = temp; temp = Engine::map->getTile(x + width, y); if (temp > tile) tile = temp; temp = Engine::map->getTile(x, y + height); if (temp > tile) tile = temp; temp = Engine::map->getTile(x + width, y + height); if (temp > tile) tile = temp; return tile; } int Object::colliding(Object * obj) { return collideRectRect(x, y, width, height, obj->x, obj->y, obj->width, obj->height); } float Object::getCenterX() { return (x + width / 2); } float Object::getCenterY() { return (y + height / 2); }
25.518519
117
0.496916
[ "object" ]
fa4f6b2b742f60cfb3f0ef06973ea09bdf1e507a
2,039
hh
C++
include/tchecker/variables/static_analysis.hh
karthik-314/PDTA_Reachability
86c380ed8558a40ae75d5634d68273902d59399d
[ "MIT" ]
4
2019-04-09T16:28:45.000Z
2021-09-21T08:25:40.000Z
include/tchecker/variables/static_analysis.hh
karthik-314/PDTA_Reachability
86c380ed8558a40ae75d5634d68273902d59399d
[ "MIT" ]
8
2019-04-05T12:53:12.000Z
2019-06-22T05:49:31.000Z
include/tchecker/variables/static_analysis.hh
karthik-314/PDTA_Reachability
86c380ed8558a40ae75d5634d68273902d59399d
[ "MIT" ]
3
2019-04-01T21:23:51.000Z
2021-03-03T14:16:18.000Z
/* * This file is a part of the TChecker project. * * See files AUTHORS and LICENSE for copyright details. * */ #ifndef TCHECKER_VARIABLES_STATIC_ANALYSIS_HH #define TCHECKER_VARIABLES_STATIC_ANALYSIS_HH #include "tchecker/variables/access.hh" /*! \file static_analysis.hh \brief Static analysis for variables */ namespace tchecker { namespace details { /*! \brief Add accesses to variables in expression \param expr : an expression \param pid : a process ID \param map : a variable access map \post All accesses to variables in `expr` have been added as READ accesses by process `pid` to `map` */ void add_accesses(tchecker::typed_expression_t const & expr, tchecker::process_id_t pid, tchecker::variable_access_map_t & map); /*! \brief Add accesses to variables in a statement \param stmt : a statement \param pid : a process ID \param map : a variable access map \post All accesses to variables in `stmt` have been added as READ (if right-hand side) or WRITE (if left-hand side) accesses by process `pid` to `map` */ void add_accesses(tchecker::typed_statement_t const & stmt, tchecker::process_id_t pid, tchecker::variable_access_map_t & map); } // end of namespace details /*! \brief Compute variable access map from a model \tparam MODEL : type of model, should inherit from tchecker::fsm::details::model_t \param model : a model \return the map of variable accesses from model */ template <class MODEL> tchecker::variable_access_map_t variable_access(MODEL const & model) { tchecker::variable_access_map_t map; for (auto const * edge : model.system().edges()) { tchecker::details::add_accesses(model.typed_guard(edge->id()), edge->pid(), map); tchecker::details::add_accesses(model.typed_statement(edge->id()), edge->pid(), map); } for (auto const * loc : model.system().locations()) tchecker::details::add_accesses(model.typed_invariant(loc->id()), loc->pid(), map); return map; } } // end of namespace tchecker #endif // TCHECKER_VARIABLES_STATIC_ANALYSIS_HH
29.550725
151
0.734674
[ "model" ]
fa5725fb2bcfab2d3cdf3d77ca2874c1ee4f9b10
1,275
cpp
C++
tt.cpp
kawgit/VisionChess
977fa5c51483c816c06869e365a254037f316d76
[ "MIT" ]
null
null
null
tt.cpp
kawgit/VisionChess
977fa5c51483c816c06869e365a254037f316d76
[ "MIT" ]
null
null
null
tt.cpp
kawgit/VisionChess
977fa5c51483c816c06869e365a254037f316d76
[ "MIT" ]
null
null
null
#include "pos.h" #include "bits.h" #include "tt.h" #include "search.h" void TTEntry::save(BB _hashkey, Eval _eval, Bound _bound, Depth _depth, Move _move, Gen _gen) { if ( _gen > gen || (bound != EXACT && (_bound == EXACT || depth < _depth)) || (bound == EXACT && (_bound == EXACT && depth < _depth))) { hashkey32 = _hashkey>>32; eval = _eval; bound = _bound; depth = _depth; move = _move; gen = _gen; } } void TTEntry::forcesave(BB _hashkey, Eval _eval, Bound _bound, Depth _depth, Move _move, Gen _gen) { hashkey32 = _hashkey>>32; eval = _eval; bound = _bound; depth = _depth; move = _move; gen = _gen; } TTEntry* TT::probe(BB hashkey, bool& found) { TTEntry* entry = &table[hashkey & HASHMASK]; found = entry->hashkey32 == hashkey>>32; return entry; } void TT::clear() { gen = 0; for (int i = 0; i < TABLESIZE; i++) { table[i].forcesave(0, 0, LB, 0, 0, 0); } } vector<Move> TT::getPV(Pos p) { vector<Move> pv; addPV(p, pv); return pv; } void TT::addPV(Pos& p, vector<Move>& pv) { bool found = false; TTEntry* entry = probe(p.hashkey, found); Move move = entry->move; Bound bound = entry->bound; if (found && bound == EXACT) { p.makeMove(move); pv.push_back(move); if (!p.isGameOver()) addPV(p, pv); p.undoMove(); } }
21.610169
100
0.621176
[ "vector" ]
fa5b03134a838c2f2fae5c9f5c06521881566836
276
cpp
C++
LEDServer/C++/ColorCalculator.cpp
nordicway/Calamarity
8cac2afb3ac20144ddcc468cdaf4bcdd2dd000a2
[ "MIT" ]
null
null
null
LEDServer/C++/ColorCalculator.cpp
nordicway/Calamarity
8cac2afb3ac20144ddcc468cdaf4bcdd2dd000a2
[ "MIT" ]
null
null
null
LEDServer/C++/ColorCalculator.cpp
nordicway/Calamarity
8cac2afb3ac20144ddcc468cdaf4bcdd2dd000a2
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ColorCalculator.h" ColorCalculator::ColorCalculator(void) { } ColorCalculator::~ColorCalculator(void) { } std::vector<unsigned char> ColorCalculator::calc(RGBLED* rgbLED, float value) { return std::vector<unsigned char>(); }
16.235294
78
0.702899
[ "vector" ]
fa5db64bb107e59d7e332cb83c981d2ef326e609
1,592
hpp
C++
Simulation/Drawable/DrawableVehicle.hpp
devmichalek/Autonomous-Vehicles-Simulator
7edc16e5b03392f407b800cbc10922f158ebfb59
[ "MIT" ]
null
null
null
Simulation/Drawable/DrawableVehicle.hpp
devmichalek/Autonomous-Vehicles-Simulator
7edc16e5b03392f407b800cbc10922f158ebfb59
[ "MIT" ]
null
null
null
Simulation/Drawable/DrawableVehicle.hpp
devmichalek/Autonomous-Vehicles-Simulator
7edc16e5b03392f407b800cbc10922f158ebfb59
[ "MIT" ]
null
null
null
#pragma once #include "DrawableInterface.hpp" #include "MathContext.hpp" #include "VehicleBuilder.hpp" class DrawableVehicle : public DrawableInterface { protected: sf::ConvexShape m_bodyShape; std::vector<EdgeShape> m_beams; sf::CircleShape m_sensorShape; sf::Color m_defaultColor; // Default color representing mass DrawableVehicle(size_t numberOfBodyPoints, size_t numberOfSensors) { m_bodyShape.setPointCount(numberOfBodyPoints); m_beams.resize(numberOfSensors); for (auto& beam : m_beams) { beam[0].color = ColorContext::BeamBeggining; beam[1].color = ColorContext::BeamEnd; } m_sensorShape.setRadius(VehicleBuilder::GetDefaultSensorSize().x); m_sensorShape.setFillColor(ColorContext::VehicleSensorDefault); } ~DrawableVehicle() { } // Sets default color that will be used to color body inline void SetDefaultColor(const float mass) { m_defaultColor = VehicleBuilder::CalculateDefaultColor(mass); m_bodyShape.setFillColor(m_defaultColor); } public: // Set this vehicle with follower color inline void SetAsFollower() { m_bodyShape.setFillColor(m_defaultColor); } // Set this vehicle with leader color inline void SetAsLeader() { m_bodyShape.setFillColor(ColorContext::LeaderVehicle); } // Draws vehicle void Draw() { // Draw body CoreWindow::Draw(m_bodyShape); // Draw sensors and its beams for (auto& beam : m_beams) { CoreWindow::Draw(beam.data(), beam.size(), sf::Lines); m_sensorShape.setPosition(beam[0].position - VehicleBuilder::GetDefaultSensorSize()); CoreWindow::Draw(m_sensorShape); } } };
23.072464
88
0.748744
[ "vector" ]
fa5fac66ab501cf21547b0c22367a613d967231c
5,251
cc
C++
src/speech_recog.cc
CPqD/asr-sdk-cpp
ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1
[ "Apache-2.0" ]
4
2017-10-12T20:09:31.000Z
2021-05-24T13:46:26.000Z
src/speech_recog.cc
CPqD/asr-sdk-cpp
ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1
[ "Apache-2.0" ]
null
null
null
src/speech_recog.cc
CPqD/asr-sdk-cpp
ca1d0a81a250f54c272b6bc39d2a1c5a1c9f58a1
[ "Apache-2.0" ]
4
2017-10-04T14:30:11.000Z
2022-02-25T10:13:06.000Z
/***************************************************************************** * Copyright 2017 CPqD. 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 <cpqd/asr-client/speech_recog.h> #include <mutex> #include <vector> #include <cpqd/asr-client/recognition_exception.h> #include "src/asr_message_request.h" #include "src/speech_recog_impl.h" #include "src/send_message.h" SpeechRecognizer::SpeechRecognizer(std::unique_ptr<Properties> properties) : properties_(std::move(properties)) { resetImpl(); } void SpeechRecognizer::resetImpl() { impl_ = std::make_shared<Impl>(); if (properties_->recog_config_) { impl_->config_ = std::move(properties_->recog_config_); properties_->recog_config_ = nullptr; } else impl_->config_ = nullptr; if (!properties_->listener_.empty()) impl_->listener_ = std::move(properties_->listener_); impl_->out_.open((properties_->log_path_).c_str(), std::fstream::app); impl_->logger_.set_ostream(&impl_->out_); impl_->logger_.set_channels(websocketpp::log::alevel::all); // Only connect if connect_on_recognize_ is false, i.e. if we are in the // default behaviour if(!properties_->connect_on_recognize_) { impl_->open(properties_->url_, properties_->user_, properties_->passwd_); // connect_on_recognize_ = false and auto_close_ = true has // undefined behaviour, so we force both true after 1st connection if(properties_->auto_close_){ properties_->connect_on_recognize_ = true; } } } SpeechRecognizer::~SpeechRecognizer() { impl_->out_.close(); close(); } void SpeechRecognizer::close() { if (!impl_->open_) return; impl_->close(); } void SpeechRecognizer::cancelRecognition() { // TODO(brunog): check if session state is listening ASRMessageRequest request(Method::CancelRecognition); std::string raw_message = request.raw(); impl_->logger_.write(websocketpp::log::elevel::info, "[SEND] " + raw_message); impl_->sendMessage(raw_message); if(impl_->sendAudioMessage_thread_.joinable()){ impl_->sendAudioMessage_terminate_ = true; impl_->sendAudioMessage_thread_.join(); } impl_->sendAudioMessage_terminate_ = false; // Close after canceled recognition if(properties_->auto_close_ && impl_->open_){ impl_->close(); } } void SpeechRecognizer::recognize( const std::shared_ptr<AudioSource> &audio_src, std::unique_ptr<LanguageModelList> lm) { if(impl_->recognizing_){ throw RecognitionException(RecognitionError::Code::ACTIVE_RECOGNITION, "There is a recognition already running in this recognizier!" ); } start_ = std::chrono::system_clock::now(); impl_->recognizing_ = true; impl_->eptr_ = nullptr; impl_->result_.clear(); impl_->audio_src_ = audio_src; impl_->lm_ = std::move(lm); // Only try to connect if connection is closed. This will be true // if connect_on_recognize_ is true or if auto_close is true and we already // performed one recognition if(!impl_->open_){ impl_->open(properties_->url_, properties_->user_, properties_->passwd_); } ASRSendMessage send_msg_; if (impl_->session_status_ == SpeechRecognizer::Impl::SessionStatus::kNone) { send_msg_.createSession(*impl_); return; } send_msg_.startRecognition(*impl_); } std::vector<RecognitionResult> SpeechRecognizer::waitRecognitionResult() { if (!impl_->open_){ auto ret = impl_->result_; impl_->result_.clear(); if (impl_->eptr_) std::rethrow_exception(impl_->eptr_); // Close after successful recognition if(properties_->auto_close_ && impl_->open_){ resetImpl(); } return ret; } std::unique_lock<std::mutex> lk(impl_->lock_); auto end = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(end - start_); auto time_waiting = std::chrono::seconds( properties_->max_wait_seconds_ ) - duration; if (impl_->cv_.wait_for(lk, time_waiting, [this]() { return impl_->result_.size() > 0 || impl_->eptr_ || !impl_->recognizing_; })) { impl_->terminateSendMessageThread(); auto ret = impl_->result_; impl_->result_.clear(); if (impl_->eptr_){ std::rethrow_exception(impl_->eptr_); } // Close after successful recognition if(properties_->auto_close_ && impl_->open_){ resetImpl(); } return ret; } else { throw RecognitionException( RecognitionError::Code::FAILURE, "Timeout on speech recog" ); } return {}; } bool SpeechRecognizer::isOpen() { return impl_->open_; }
30.178161
79
0.671301
[ "vector" ]
fa6a2800f8ffe4f8759a219780d5e62c1654f997
753
cpp
C++
lib/3d/blanks/QinitFunc.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
lib/3d/blanks/QinitFunc.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
lib/3d/blanks/QinitFunc.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
#include "tensors.h" // *REQUIRED* // // This is a user-required routine that defines the initial conditions for the // problem. // // Each application is REQUIRED to define one of these. // // Input: // // xpts( 1:numpts, 1:ndim ) - The x,y, and z-coordinates for a list of points // // Output: // // qvals( 1:numpts, 1:meqn ) - The vector of conserved variables, q at // each point. // // See also: AuxFunc. void QinitFunc(const dTensor2& xpts, dTensor2& qvals) { const int numpts=xpts.getsize(1); for (int i=1; i<=numpts; i++) { const double x = xpts.get(i,1); const double y = xpts.get(i,2); const double z = xpts.get(i,3); { qvals.set(i,1, 0.0 ); } } }
22.147059
82
0.572377
[ "vector" ]
fa6a56f46ec3fedcfeef6cb9a1039e541647071e
15,719
cpp
C++
lib/Dialect/Stencil/PeelOddIterationsPass.cpp
havogt/open-earth-compiler
1e48dee6a1a021bc11d6621432450406349b3733
[ "Apache-2.0" ]
40
2020-07-16T17:30:00.000Z
2022-03-30T02:15:11.000Z
lib/Dialect/Stencil/PeelOddIterationsPass.cpp
JackMoriarty/open-earth-compiler
1e48dee6a1a021bc11d6621432450406349b3733
[ "Apache-2.0" ]
25
2020-08-18T18:14:24.000Z
2022-03-09T14:19:51.000Z
lib/Dialect/Stencil/PeelOddIterationsPass.cpp
JackMoriarty/open-earth-compiler
1e48dee6a1a021bc11d6621432450406349b3733
[ "Apache-2.0" ]
9
2020-08-04T08:05:50.000Z
2022-03-28T03:55:22.000Z
#include "Dialect/Stencil/Passes.h" #include "Dialect/Stencil/StencilDialect.h" #include "Dialect/Stencil/StencilOps.h" #include "Dialect/Stencil/StencilTypes.h" #include "Dialect/Stencil/StencilUtils.h" #include "PassDetail.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/IR/Diagnostics.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/OperationSupport.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/UseDefLists.h" #include "mlir/IR/Value.h" #include "mlir/IR/Visitors.h" #include "mlir/Pass/Pass.h" #include "mlir/Support/LLVM.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "mlir/Transforms/Passes.h" #include "mlir/Transforms/Utils.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" using namespace mlir; using namespace stencil; namespace { // Introduce a peel loop if the shape is not a multiple of the unroll factor struct PeelRewrite : public stencil::ApplyOpPattern { using ApplyOpPattern::ApplyOpPattern; LogicalResult makePeelIteration(stencil::ApplyOp applyOp, int64_t peelSize, PatternRewriter &rewriter) const { // Get shape and terminator of the apply operation auto returnOp = cast<stencil::ReturnOp>(applyOp.getBody()->getTerminator()); auto shapeOp = cast<ShapeOp>(applyOp.getOperation()); // Compute count of left or right empty stores auto leftCount = peelSize < 0 ? -peelSize : 0; auto rightCount = peelSize > 0 ? returnOp.getUnrollFac() - peelSize : returnOp.getUnrollFac(); // Create empty store for all iterations that exceed the trip count unsigned numOfOperands = 0; SmallVector<Value, 16> newOperands; for (auto en : llvm::enumerate(returnOp.getOperands())) { int64_t unrollIdx = en.index() % returnOp.getUnrollFac(); if (unrollIdx < leftCount || unrollIdx >= rightCount) { auto resultOp = en.value().getDefiningOp(); numOfOperands += resultOp->getNumOperands(); rewriter.updateRootInPlace(resultOp, [&]() { resultOp->setOperands({}); }); } } // Extend the shape for negative peel sizes if (peelSize < 0) { auto lb = shapeOp.getLB(); lb[returnOp.getUnrollDim()] += peelSize; shapeOp.updateShape(lb, shapeOp.getUB()); return success(); } return numOfOperands == 0 ? failure() : success(); } LogicalResult addPeelIteration(stencil::ApplyOp applyOp, stencil::ReturnOp returnOp, int64_t peelSize, PatternRewriter &rewriter) const { // Get the unroll factor and dimension auto unrollFac = returnOp.getUnrollFac(); auto unrollDim = returnOp.getUnrollDim(); // Compute the domain size auto shapeOp = cast<ShapeOp>(applyOp.getOperation()); auto domainSize = shapeOp.getUB()[unrollDim] - shapeOp.getLB()[unrollDim]; // Introduce peel iterations if (domainSize <= unrollFac) { return makePeelIteration(applyOp, peelSize, rewriter); } else { // Clone a peel and a body operation auto leftOp = cast<stencil::ApplyOp>(rewriter.clone(*applyOp)); auto rightOp = cast<stencil::ApplyOp>(rewriter.clone(*applyOp)); // Adapt the shape of the two apply ops auto lb = shapeOp.getLB(); auto ub = shapeOp.getUB(); int64_t split = peelSize < 0 ? lb[unrollDim] + peelSize + unrollFac : ub[unrollDim] + peelSize - unrollFac; lb[unrollDim] = split; ub[unrollDim] = split; // Introduce a second apply to handle the peel domain cast<ShapeOp>(leftOp.getOperation()).updateShape(shapeOp.getLB(), ub); cast<ShapeOp>(rightOp.getOperation()).updateShape(lb, shapeOp.getUB()); // Remove stores that exceed the domain auto peelOp = peelSize < 0 ? leftOp : rightOp; makePeelIteration(peelOp, peelSize, rewriter); // Introduce a stencil combine to replace the apply operation auto combineOp = rewriter.create<stencil::CombineOp>( applyOp.getLoc(), applyOp.getResultTypes(), unrollDim, split, leftOp.getResults(), rightOp.getResults(), ValueRange(), ValueRange(), applyOp.lbAttr(), applyOp.ubAttr()); rewriter.replaceOp(applyOp, combineOp.getResults()); return success(); } } LogicalResult matchAndRewrite(stencil::ApplyOp applyOp, PatternRewriter &rewriter) const override { // Get the return operation and the shape of the apply operation auto returnOp = cast<stencil::ReturnOp>(applyOp.getBody()->getTerminator()); auto shapeOp = cast<ShapeOp>(applyOp.getOperation()); // Compute the domain size auto unrollDim = returnOp.getUnrollDim(); auto unrollFac = returnOp.getUnrollFac(); if (unrollFac == 1) return failure(); // Get the combine tree root and determine to base offset auto rootOp = applyOp.getCombineTreeRootShape(); auto rootOrigin = rootOp.getLB()[unrollDim]; // Add left or right peel iterations if the bound is unaligned auto leftSize = (shapeOp.getLB()[unrollDim] - rootOrigin) % unrollFac; auto rightSize = (shapeOp.getUB()[unrollDim] - rootOrigin) % unrollFac; if (leftSize != 0) return addPeelIteration(applyOp, returnOp, -leftSize, rewriter); if (rightSize != 0) return addPeelIteration(applyOp, returnOp, unrollFac - rightSize, rewriter); return failure(); } }; // Fuse peel loops of neighboring apply operations in unroll direction struct FuseRewrite : public stencil::CombineOpPattern { using CombineOpPattern::CombineOpPattern; Operation *getLowerDefiningOp(stencil::CombineOp combineOp) const { // Get the lower defining operation if (combineOp.lower().empty()) return nullptr; return combineOp.lower().front().getDefiningOp(); } Operation *getUpperDefiningOp(stencil::CombineOp combineOp) const { // Get the upper defining operation if (combineOp.upper().empty()) return nullptr; return combineOp.upper().front().getDefiningOp(); } // Create an apply operation that fuses the left and right peel iterations stencil::ApplyOp fusePeelIterations(stencil::ApplyOp leftOp, stencil::ApplyOp rightOp, PatternRewriter &rewriter) const { // Compute the operands of the fused apply op // (run canonicalization after the pass to cleanup arguments) SmallVector<Value, 10> newOperands = leftOp.getOperands(); newOperands.append(rightOp.getOperands().begin(), rightOp.getOperands().end()); // Get return operations auto leftReturnOp = cast<stencil::ReturnOp>(leftOp.getBody()->getTerminator()); auto rightReturnOp = cast<stencil::ReturnOp>(rightOp.getBody()->getTerminator()); assert(leftReturnOp.unroll() == rightReturnOp.unroll() && "expected unroll of the left and right apply to match"); // Create a new operation that has the size of auto newOp = rewriter.create<stencil::ApplyOp>( rewriter.getFusedLoc({leftOp.getLoc(), rightOp.getLoc()}), leftOp.getResultTypes(), newOperands, leftOp.lb(), rightOp.ub()); rewriter.mergeBlocks( leftOp.getBody(), newOp.getBody(), newOp.getBody()->getArguments().take_front(leftOp.getNumOperands())); rewriter.mergeBlocks( rightOp.getBody(), newOp.getBody(), newOp.getBody()->getArguments().take_back(rightOp.getNumOperands())); // Compute the split between left and right op operands auto unrollDim = leftReturnOp.getUnrollDim(); auto unrollFac = leftReturnOp.getUnrollFac(); unsigned split = cast<ShapeOp>(leftOp.getOperation()).getUB()[unrollDim] - cast<ShapeOp>(leftOp.getOperation()).getLB()[unrollDim]; // Update the operands of the second return operation SmallVector<Value, 10> newReturnOperands = rightReturnOp.getOperands(); for (auto en : llvm::enumerate(leftReturnOp.getOperands())) { if (en.index() % unrollFac < split) newReturnOperands[en.index()] = en.value(); } rewriter.updateRootInPlace(rightReturnOp, [&]() { rightReturnOp->setOperands(newReturnOperands); }); rewriter.eraseOp(leftReturnOp); // Update the shape of the apply operation cast<ShapeOp>(newOp.getOperation()) .updateShape(cast<ShapeOp>(leftOp.getOperation()).getLB(), cast<ShapeOp>(rightOp.getOperation()).getUB()); return newOp; } // Introduce a peel loop if the shape is not a multiple of the unroll factor LogicalResult matchAndRewrite(stencil::CombineOp combineOp, PatternRewriter &rewriter) const override { // Search the lower and upper defining ops and exit if none exists Operation *currLeftCombineOp = getLowerDefiningOp(combineOp); Operation *currRightCombineOp = getUpperDefiningOp(combineOp); if (!currLeftCombineOp || !currRightCombineOp) return failure(); // Walk up the combine tree SmallVector<Operation *, 4> leftCombineOps; SmallVector<Operation *, 4> rightCombineOps; while (auto combineOp = dyn_cast_or_null<stencil::CombineOp>(currLeftCombineOp)) { leftCombineOps.push_back(combineOp); currLeftCombineOp = getUpperDefiningOp(combineOp); } while (auto combineOp = dyn_cast_or_null<stencil::CombineOp>(currRightCombineOp)) { rightCombineOps.push_back(combineOp); currRightCombineOp = getLowerDefiningOp(combineOp); } // Get the left and right apply operations auto leftOp = dyn_cast_or_null<stencil::ApplyOp>(currLeftCombineOp); auto rightOp = dyn_cast_or_null<stencil::ApplyOp>(currRightCombineOp); if (!leftOp || !rightOp) return failure(); // Check if the shapes overlap auto returnOp = cast<stencil::ReturnOp>(leftOp.getBody()->getTerminator()); if (returnOp.getUnrollFac() == 1) return failure(); if (cast<ShapeOp>(leftOp.getOperation()).getLB()[returnOp.getUnrollDim()] != cast<ShapeOp>(rightOp.getOperation()).getLB()[returnOp.getUnrollDim()]) return failure(); // Merge the two apply operations in case they overlap auto newOp = fusePeelIterations(leftOp, rightOp, rewriter); auto newShape = cast<ShapeOp>(newOp.getOperation()); // Update the shape of the left and right combines for (auto leftCombineOp : leftCombineOps) { auto leftShape = cast<ShapeOp>(leftCombineOp); auto ub = leftShape.getUB(); ub[returnOp.getUnrollDim()] = newShape.getLB()[returnOp.getUnrollDim()]; leftShape.updateShape(leftShape.getLB(), ub); } for (auto rightCombineOp : rightCombineOps) { auto rightShape = cast<ShapeOp>(rightCombineOp); auto lb = rightShape.getLB(); lb[returnOp.getUnrollDim()] = newShape.getUB()[returnOp.getUnrollDim()]; rightShape.updateShape(lb, rightShape.getUB()); } // Disconnect the left and right apply operations from the combine tree SmallVector<Value, 10> leftOperands; SmallVector<Value, 10> rightOperands; if (!leftCombineOps.empty()) { rewriter.replaceOp( leftCombineOps.back(), cast<stencil::CombineOp>(leftCombineOps.back()).lower()); leftOperands = combineOp.lower(); } if (!rightCombineOps.empty()) { rewriter.replaceOp( rightCombineOps.back(), cast<stencil::CombineOp>(rightCombineOps.back()).upper()); rightOperands = combineOp.upper(); } // Replace the combine op by the results computed by the fused apply SmallVector<Value, 10> newResults = newOp.getResults(); auto currShape = cast<ShapeOp>(newOp.getOperation()); auto unrollDim = returnOp.getUnrollDim(); if (!leftOperands.empty()) { // Introduce a combine ob to connect to the left combine subtree auto newCombineOp = rewriter.create<stencil::CombineOp>( combineOp.getLoc(), combineOp.getResultTypes(), unrollDim, currShape.getLB()[unrollDim], leftOperands, newResults, ValueRange(), ValueRange(), combineOp.lbAttr(), combineOp.ubAttr()); newResults = newCombineOp.getResults(); // Get the lower and upper bounds of the children auto lb = cast<ShapeOp>(getLowerDefiningOp(newCombineOp)).getLB(); auto ub = cast<ShapeOp>(getUpperDefiningOp(newCombineOp)).getUB(); currShape = cast<ShapeOp>(newCombineOp.getOperation()); currShape.updateShape(lb, ub); } if (!rightOperands.empty()) { // Introduce a combine ob to connect to the right combine subtree auto newCombineOp = rewriter.create<stencil::CombineOp>( combineOp.getLoc(), combineOp.getResultTypes(), unrollDim, currShape.getUB()[unrollDim], newResults, rightOperands, ValueRange(), ValueRange(), combineOp.lbAttr(), combineOp.ubAttr()); newResults = newCombineOp.getResults(); // Get the lower and upper bounds of the children auto lb = cast<ShapeOp>(getLowerDefiningOp(newCombineOp)).getLB(); auto ub = cast<ShapeOp>(getUpperDefiningOp(newCombineOp)).getUB(); currShape = cast<ShapeOp>(newCombineOp.getOperation()); currShape.updateShape(lb, ub); } rewriter.replaceOp(combineOp, newResults); rewriter.eraseOp(leftOp); rewriter.eraseOp(rightOp); return success(); } }; struct PeelOddIterationsPass : public PeelOddIterationsPassBase<PeelOddIterationsPass> { void runOnFunction() override; }; void PeelOddIterationsPass::runOnFunction() { FuncOp funcOp = getFunction(); // Only run on functions marked as stencil programs if (!StencilDialect::isStencilProgram(funcOp)) return; // Check the combine to ifelse preparations have been run auto result = funcOp.walk([&](stencil::CombineOp combineOp) { if (!combineOp.lowerext().empty() || !combineOp.upperext().empty()) { combineOp.emitOpError("expected no lower or upper extra operands"); return WalkResult::interrupt(); } // Check the producer in the operand range are unique auto haveUniqueProducer = [](OperandRange operands) { Operation *lastOp = nullptr; for (auto operand : operands) { auto definingOp = operand.getDefiningOp(); if (lastOp && definingOp && lastOp != definingOp) return false; lastOp = definingOp ? definingOp : lastOp; } return true; }; if (!(haveUniqueProducer(combineOp.lower()) && haveUniqueProducer(combineOp.upper()))) { combineOp.emitOpError( "expected unique lower and upper producer operations"); return WalkResult::interrupt(); } return WalkResult::advance(); }); if (result.wasInterrupted()) return signalPassFailure(); // Check shape inference has been executed result = funcOp->walk([&](stencil::ShapeOp shapeOp) { if (!shapeOp.hasShape()) return WalkResult::interrupt(); return WalkResult::advance(); }); if (result.wasInterrupted()) { funcOp.emitOpError("execute shape inference before bounds unrolling"); signalPassFailure(); return; } // Populate the pattern list depending on the config OwningRewritePatternList patterns; patterns.insert<PeelRewrite, FuseRewrite>(&getContext()); applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); } } // namespace std::unique_ptr<OperationPass<FuncOp>> mlir::createPeelOddIterationsPass() { return std::make_unique<PeelOddIterationsPass>(); }
40.722798
80
0.676061
[ "shape" ]
fa6aaf769622aea666b9e2afcb41eda8fdc73966
98,191
cpp
C++
tests/localization/22.locale.num.put.cpp
isabella232/stdcxx
b0b0cab391b7b1f2d17ef4342aeee6b792bde63c
[ "Apache-2.0" ]
53
2015-01-13T05:46:43.000Z
2022-02-24T23:46:04.000Z
tests/localization/22.locale.num.put.cpp
mann-patel/stdcxx
a22c5192f4b2a8b0b27d3588ea8f6d1faf8b037a
[ "Apache-2.0" ]
1
2021-11-04T12:35:39.000Z
2021-11-04T12:35:39.000Z
tests/localization/22.locale.num.put.cpp
isabella232/stdcxx
b0b0cab391b7b1f2d17ef4342aeee6b792bde63c
[ "Apache-2.0" ]
33
2015-07-09T13:31:00.000Z
2021-11-04T12:12:20.000Z
/*************************************************************************** * * 22.locale.num.put.cpp - tests exercising the std::num_put facet * * $Id$ * *************************************************************************** * * 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 2001-2008 Rogue Wave Software, Inc. * **************************************************************************/ #ifdef __GNUG__ // prevent gcc -Wshadow warnings for convenience types # define ushort __rw_ushort # define uint __rw_uint # define ulong __rw_ulong # include <sys/types.h> # undef ushort # undef uint # undef ulong #endif // __GNUG__ #include <ios> #include <locale> #include <cerrno> // for ERANGE, errno #include <cfloat> // for floating limits macros #include <climits> // for integral limits macros #include <clocale> // for LC_NUMERIC, setlocale() #include <cstdio> // for sprintf() #include <cstring> // for strcmp(), strlen() #include <rw_any.h> // for TOSTR() #include <rw_cmdopt.h> // for rw_enabled #include <rw_driver.h> // for rw_test #include <rw_locale.h> // for rw_locales #include <rw_valcmp.h> // for rw_equal /**************************************************************************/ // set by the command line option handler in response to: static int rw_opt_enable_num_get = 0; // --enable-num_get static int rw_opt_no_errno = 0; // --no-errno static int rw_opt_no_grouping = 0; // --no-grouping static int rw_opt_no_widen = 0; // --no-widen /**************************************************************************/ // replacement ctype facet template <class charT> struct Ctype: std::ctype<charT> { typedef std::ctype<charT> Base; typedef typename Base::char_type char_type; static int n_widen_; Ctype (): Base (0, 0, 1) { } virtual char_type do_widen (char c) const { ++n_widen_; switch (c) { case '0': c = '9'; break; case '1': c = '8'; break; case '2': c = '7'; break; case '3': c = '6'; break; case '4': c = '5'; break; case '5': c = '4'; break; case '6': c = '3'; break; case '7': c = '2'; break; case '8': c = '1'; break; case '9': c = '0'; break; default: break; } return char_type (c); } virtual const char_type* do_widen (const char *lo, const char *hi, char_type *dst) const { return Base::do_widen (lo, hi, dst); } }; template <class charT> int Ctype<charT>::n_widen_; /**************************************************************************/ // replacement numpunct facet template <class charT> struct Punct: std::numpunct<charT> { typedef typename std::numpunct<charT>::char_type char_type; typedef typename std::numpunct<charT>::string_type string_type; static char_type decimal_point_; static char_type thousands_sep_; static const char *grouping_; static const char_type *truename_; static const char_type *falsename_; static int n_objs_; // number of facet objects in existence static int n_thousands_sep_; // number of calls to do_thousands_sep() Punct (std::size_t ref = 0) : std::numpunct<charT>(ref) { ++n_objs_; } ~Punct () { --n_objs_; } virtual char_type do_decimal_point () const { return decimal_point_; } virtual std::string do_grouping () const { return grouping_; } virtual char_type do_thousands_sep () const { ++n_thousands_sep_; return thousands_sep_; } virtual string_type do_truename () const { return truename_ ? string_type (truename_) : string_type (); } virtual string_type do_falsename () const { return falsename_ ? string_type (falsename_) : string_type (); } }; template <class charT> const char* Punct<charT>::grouping_ = ""; template <class charT> typename Punct<charT>::char_type Punct<charT>::decimal_point_ = '.'; template <class charT> typename Punct<charT>::char_type Punct<charT>::thousands_sep_ = ','; template <class charT> const typename Punct<charT>::char_type* Punct<charT>::truename_; template <class charT> const typename Punct<charT>::char_type* Punct<charT>::falsename_; template <class charT> int Punct<charT>::n_thousands_sep_; template <class charT> int Punct<charT>::n_objs_; /**************************************************************************/ template <class charT> struct Ios: std::basic_ios<charT> { Ios () { this->init (0); } }; template <class charT> struct NumGet: std::num_get<charT, const charT*> { NumGet () { } }; template <class charT> struct NumPut: std::num_put<charT, charT*> { typedef std::num_put<charT, charT*> Base; typedef typename Base::char_type char_type; typedef typename Base::iter_type iter_type; enum { test_bool, test_short, test_ushort, test_int, test_uint, test_long, test_ulong, test_llong, test_ullong, test_pvoid, test_float, test_double, test_ldouble }; static int ncalls_ [13]; NumPut (std::size_t ref = 0): Base (ref) { } #ifndef _RWSTD_NO_BOOL virtual iter_type do_put (iter_type it, std::ios_base &f, char_type fill, bool v) const { ++ncalls_ [test_bool]; return Base::do_put (it, f, fill, v); } #endif // _RWSTD_NO_BOOL virtual iter_type do_put (iter_type it, std::ios_base &f, char_type fill, long v) const { ++ncalls_ [test_long]; return Base::do_put (it, f, fill, v); } virtual iter_type do_put (iter_type it, std::ios_base &f, char_type fill, unsigned long v) const { ++ncalls_ [test_ulong]; return Base::do_put (it, f, fill, v); } #ifdef _RWSTD_LONG_LONG // provided as an extension unless _RWSTD_NO_LONG_LONG is #defined virtual iter_type do_put (iter_type it, std::ios_base &f, char_type fill, unsigned _RWSTD_LONG_LONG v) const { ++ncalls_ [test_ullong]; return Base::do_put (it, f, fill, v); } // provided as an extension unless _RWSTD_NO_LONG_LONG is #defined virtual iter_type do_put (iter_type it, std::ios_base &f, char_type fill, _RWSTD_LONG_LONG v) const { ++ncalls_ [test_llong]; return Base::do_put (it, f, fill, v); } #endif // _RWSTD_LONG_LONG virtual iter_type do_put (iter_type it, std::ios_base &f, char_type fill, double v) const { ++ncalls_ [test_double]; return Base::do_put (it, f, fill, v); } #ifndef _RWSTD_NO_LONG_DOUBLE virtual iter_type do_put (iter_type it, std::ios_base &f, char_type fill, long double v) const { ++ncalls_ [test_ldouble]; return Base::do_put (it, f, fill, v); } #endif // _RWSTD_NO_LONG_DOUBLE virtual iter_type do_put (iter_type it, std::ios_base &f, char_type fill, const void *v) const { ++ncalls_ [test_pvoid]; return Base::do_put (it, f, fill, v); } }; // explicit initialization of the static array below used // to work around a SunPro 5.4 bug (PR #27293) template <class charT> /* static */ int NumPut<charT>::ncalls_ [13] = { 0 }; /**************************************************************************/ template <class charT, class T> void do_test (charT /* dummy */, const char *cname, // charT name const char *tname, // T name int lineno, // line number T val, // value to format int flags, // ios flags std::streamsize prec, // precision std::streamsize width, // field width char fill, // fill character const char *grouping, // grouping string const char *str, // expected output int err_expect = -1, // expected iostate T val_expect = T () /* expected num_get result */) { if (!rw_enabled (lineno)) { rw_note (0, __FILE__, __LINE__, "test on line %d disabled", lineno); return; } // create a distinct punctuation facet for each iteration to make sure // any data cached in between successive calls to the facet's public // member functions are flushed const Punct<charT> pun (1); Ios<charT> ios; NumPut<charT> np; ios.imbue (std::locale (ios.getloc (), (const std::numpunct<charT>*)&pun)); ios.flags (std::ios_base::fmtflags (flags)); ios.precision (prec); ios.width (width); pun.grouping_ = grouping; #if defined (_RWSTD_LDBL_MAX_10_EXP) charT buf [_RWSTD_LDBL_MAX_10_EXP + 2] = { 0 }; #else // if !defined (_RWSTD_LDBL_MAX_10_EXP) charT buf [4096] = { 0 }; #endif // _RWSTD_LDBL_MAX_10_EXP // cast the narrow fill character to unsigned char before // converting it to charT to avoid potential sign extension typedef unsigned char UChar; const charT wfill = charT (UChar (fill)); const charT* const bufend = np.put (buf, ios, wfill, val); // verify 22.2.2.2.2, p21 if (ios.width ()) { static int width_fail = 0; // fail at most once for each specialization rw_assert (!width_fail++, 0, lineno, "line %d: num_put<%s>::put (..., %s = %s) " "failed to reset width from %d; width() = %d", __LINE__, cname, tname, TOSTR (val), TOSTR (buf), width, ios.width ()); } /******************************************************************/ if (str) { char cbuf [sizeof buf / sizeof *buf] = { '\0' }; if ('%' == *str) { std::sprintf (cbuf, str, val); str = cbuf; #ifdef _WIN32 std::size_t len = std::strlen (str); if ( ('e' == cbuf [len - 5] || 'E' == cbuf [len - 5]) && ('-' == cbuf [len - 4] || '+' == cbuf [len - 4]) && ('0' == cbuf [len - 3])) { cbuf [len - 3] = cbuf [len - 2]; cbuf [len - 2] = cbuf [len - 1]; cbuf [len - 1] = cbuf [len]; } #endif // _WIN32 } // compare output produced by num_put with that produced by printf() rw_assert (0 == rw_strncmp (buf, str), 0, lineno, "line %d: num_put<%s>::put (..., %s = %s) " "wrote %{*Ac}, expected %{*Ac}, " "flags = %{If}, precision = %d" "%{?}, grouping = \"%#s\"%{;}", __LINE__, cname, tname, TOSTR (val), sizeof *buf, buf, sizeof *str, str, flags, prec, grouping && *grouping, grouping); } /******************************************************************/ #ifndef NO_NUM_GET if (!rw_opt_enable_num_get) return; // skip negative precision (extension requiring special treatment) if (prec < 0) return; const charT *next = buf; // skip leading fill characters (if any) for ( ; *next == fill; ++next); // find the first non-fill character if it exists const charT *last = next; for ( ; *last && *last != fill; ++last); for ( ; *last && *last == fill; ++last); // do not perform extraction if there are any fill characters // in the middle of output (they serve as punctuators and break // up the input sequence) if (next != last && *last) return; // do not perform extraction if the fill character is the minus // sign, the plus sign, the thousands separator, the decimal point, // or a digit if ( '-' == fill || '+' == fill || pun.thousands_sep_ == fill || pun.decimal_point_ == fill || (fill >= '0' && fill <= '9')) return; // do not perform extraction if there is no data to extract // (unless this is an extraction-only test) if (!*next && str) return; NumGet<charT> ng; T x = T (); std::ios_base::iostate err = std::ios_base::goodbit; if (-1 == err_expect) { // lwg issue 17: special treatment for bool: // The in iterator is always left pointing one position beyond // the last character successfully matched. If val is set, then // err is set to str.goodbit; or to str.eofbit if, when seeking // another character to match, it is found that (in==end). If // val is not set, then err is set to str.failbit; or to // (str.failbit|str.eofbit) if the reason for the failure was // that (in==end). [Example: for targets true:"a" and false:"abb", // the input sequence "a" yields val==true and err==str.eofbit; // the input sequence "abc" yields err=str.failbit, with in ending // at the 'c' element. For targets true:"1" and false:"0", the // input sequence "1" yields val==true and err=str.goodbit. For // empty targets (""), any input sequence yields err==str.failbit. // --end example] err_expect = T (1) == T (2) && flags & std::ios::boolalpha ? std::ios::goodbit : last == bufend && last [-1] != fill ? std::ios::eofbit : std::ios::goodbit; val_expect = val; } last = ng.get (next, bufend, ios, err, x); // verify the state rw_assert (err == err_expect, 0, lineno, "line %d: num_get<%s>::get (%s, ..., %s&) " "flags = %{If}, " "%{?}grouping = \"%#s\", %{;}" "iostate = %{Is}, expected %{Is}", __LINE__, cname, TOSTR (next), tname, flags, grouping && *grouping, grouping, err, err_expect); // verify the parsed value rw_assert (rw_equal (x, val_expect), 0, lineno, "line %d: num_get<%s>::get (%s, ..., %s&) got %s, " "expected %s, flags = %{If}, " "%{?}grouping = \"%#s\", %{;}", __LINE__, cname, TOSTR (next), tname, TOSTR (x), TOSTR (val_expect), flags, grouping && *grouping, grouping); #else _RWSTD_UNUSED (bufend); _RWSTD_UNUSED (err_expect); _RWSTD_UNUSED (val_expect); #endif // NO_NUM_GET } /**************************************************************************/ template <class charT> struct Streambuf: std::basic_streambuf<charT, std::char_traits<charT> > { }; template <class charT> void direct_use_test (charT, const char *cname) { _RWSTD_UNUSED (cname); // verify that num_put objects can be used directly w/o first // having been installed in a locale object; the behavior of // such facets is unspecified (but not undefined) Ios<charT> ios; const std::num_put<charT> np; Streambuf<charT> sb; #define DIRECT_USE_TEST(T) \ np.put (std::ostreambuf_iterator<charT>(&sb), ios, charT (), (T)0) #ifndef _RWSTD_NO_BOOL DIRECT_USE_TEST (bool); #endif // _RWSTD_NO_BOOL DIRECT_USE_TEST (unsigned long); DIRECT_USE_TEST (long); DIRECT_USE_TEST (double); #ifndef _RWSTD_NO_LONG_DOUBLE DIRECT_USE_TEST (long double); #endif DIRECT_USE_TEST (void*); } /**************************************************************************/ // for convenience #define boolalpha std::ios_base::boolalpha #define dec std::ios_base::dec #define fixed std::ios_base::fixed #define hex std::ios_base::hex #define internal std::ios_base::internal #define left std::ios_base::left #define oct std::ios_base::oct #define right std::ios_base::right #define scientific std::ios_base::scientific #define showbase std::ios_base::showbase #define showpoint std::ios_base::showpoint #define showpos std::ios_base::showpos #define skipws std::ios_base::skipws #define unitbuf std::ios_base::unitbuf #define uppercase std::ios_base::uppercase #define bin std::ios_base::bin #define adjustfield std::ios_base::adjustfield #define basefield std::ios_base::basefield #define floatfield std::ios_base::floatfield #define nolock std::ios_base::nolock #define nolockbuf std::ios_base::nolockbuf #define Bad std::ios_base::badbit #define Eof std::ios_base::eofbit #define Fail std::ios_base::failbit #define Good std::ios_base::goodbit template <class charT> void bool_test (charT, const char *cname) { #ifndef _RWSTD_NO_BOOL rw_info (0, 0, __LINE__, "std::num_put<%s>::put (..., bool)", cname); const char* const tname = "bool"; static const charT boolnames[][4] = { { 'y', 'e', 's', '\0' }, { 'n', 'o', '.', '\0' }, // unusual strings to try to trip up the formatting algorithm { '+', '1', '\0' }, { '-', '2', '\0' }, { '-', '+', '1', '\0' }, { '+', '-', '0', '\0' }, { '\001', '\0' }, { '\0' } }; Punct<charT>::decimal_point_ = '*'; Punct<charT>::truename_ = boolnames [0]; Punct<charT>::falsename_ = boolnames [1]; // set line number to __LINE__ and perform test so that // assertion output will point to the failed TEST line #define TEST do_test #define T charT (), cname, tname, __LINE__ TEST (T, false, 0, 0, 0, ' ', "", "0"); TEST (T, true, 0, 0, 0, ' ', "", "1"); TEST (T, false, 0, 0, 0, ' ', "", "%d"); TEST (T, true, 0, 0, 0, ' ', "", "%d"); TEST (T, false, showpos, 0, 0, ' ', "", "%+d"); TEST (T, true, showpos, 0, 0, ' ', "", "%+d"); TEST (T, false, oct, 0, 0, ' ', "", "%o"); TEST (T, true, oct, 0, 0, ' ', "", "%o"); TEST (T, false, dec, 0, 0, ' ', "", "%d"); TEST (T, true, dec, 0, 0, ' ', "", "%d"); TEST (T, false, hex, 0, 0, ' ', "", "%x"); TEST (T, true, hex, 0, 0, ' ', "", "%x"); rw_info (0, 0, __LINE__, "std::ios::boolalpha"); TEST (T, false, boolalpha, 0, 0, ' ', "", "no."); TEST (T, true, boolalpha, 0, 0, ' ', "", "yes"); // left justified boolalpha TEST (T, false, boolalpha | left, 0, 6, ' ', "", "no. "); TEST (T, true, boolalpha | left, 0, 6, ' ', "", "yes "); // right justified boolalpha TEST (T, false, boolalpha | right, 0, 6, ' ', "", " no."); TEST (T, true, boolalpha | right, 0, 6, ' ', "", " yes"); // implied right justified boolalpha (internal bit set) TEST (T, false, boolalpha | internal, 0, 4, ' ', "", " no."); TEST (T, true, boolalpha | internal, 0, 4, ' ', "", " yes"); Punct<charT>::truename_ = boolnames [2]; Punct<charT>::falsename_ = boolnames [3]; TEST (T, false, boolalpha, 0, 1, ' ', "", "-2"); TEST (T, true, boolalpha, 0, 1, ' ', "", "+1"); TEST (T, false, boolalpha | internal, 0, 4, ' ', "", " -2"); TEST (T, true, boolalpha | internal, 0, 4, ' ', "", " +1"); Punct<charT>::truename_ = boolnames [4]; Punct<charT>::falsename_ = boolnames [5]; TEST (T, false, boolalpha, 0, 1, ' ', "", "+-0"); TEST (T, true, boolalpha, 0, 1, ' ', "", "-+1"); TEST (T, false, boolalpha | internal, 0, 4, ' ', "", " +-0"); TEST (T, true, boolalpha | internal, 0, 4, ' ', "", " -+1"); Punct<charT>::truename_ = boolnames [6]; Punct<charT>::falsename_ = boolnames [7]; TEST (T, false, boolalpha, 0, 0, ' ', "", ""); TEST (T, true, boolalpha, 0, 0, ' ', "", "\001"); TEST (T, false, boolalpha, 0, 1, ' ', "", " "); TEST (T, true, boolalpha, 0, 1, ' ', "", "\001"); TEST (T, false, boolalpha, 0, 1, ',', "", ","); TEST (T, true, boolalpha, 0, 1, ',', "", "\001"); TEST (T, false, boolalpha | internal, 0,4, ',', "", ",,,,"); TEST (T, true, boolalpha | internal, 0,4, ',', "", ",,,\001"); #endif // _RWSTD_NO_BOOL } /**************************************************************************/ template <class charT> void long_test (charT, const char *cname) { const char* const tname = "long"; rw_info (0, 0, __LINE__, "std::num_put<%s>::put (..., %s)", cname, tname); // working around a VAC++/AIX bug where LONG_{MIN,MAX} are // of type int rather than long as required (see PR #28798) #undef LONG_MIN #define LONG_MIN _RWSTD_LONG_MIN #undef LONG_MAX #define LONG_MAX _RWSTD_LONG_MAX #undef GET_FAIL #define GET_FAIL (Eof | Fail), LONG_MAX ////////////////////////////////////////////////////////////////// // implicit decimal output rw_info (0, 0, __LINE__, "std::ios::fmtflags ()"); TEST (T, 0L, 0, 0, 0, ' ', "", "%ld"); TEST (T, 1L, 0, 0, 0, ' ', "", "%ld"); TEST (T, 2L, 0, 0, 0, ' ', "", "%ld"); TEST (T, -3L, 0, 0, 0, ' ', "", "%ld"); TEST (T, 12L, 0, 0, 0, ' ', "", "%ld"); TEST (T, -13L, 0, 0, 0, ' ', "", "%ld"); TEST (T, 345L, 0, 0, 0, ' ', "", "%ld"); TEST (T, -456L, 0, 0, 0, ' ', "", "%ld"); TEST (T, 6789L, 0, 0, 0, ' ', "", "%ld"); TEST (T, -7890L, 0, 0, 0, ' ', "", "%ld"); TEST (T, 98765L, 0, 0, 0, ' ', "", "%ld"); TEST (T, -98766L, 0, 0, 0, ' ', "", "%ld"); TEST (T, LONG_MAX, 0, 0, 0, ' ', "", "%ld"); TEST (T, LONG_MIN, 0, 0, 0, ' ', "", "%ld"); ////////////////////////////////////////////////////////////////// // explicit decimal ouptut rw_info (0, 0, __LINE__, "std::ios::dec"); TEST (T, 0L, dec, 0, 0, ' ', "", "%ld"); TEST (T, 1L, dec, 0, 0, ' ', "", "%ld"); TEST (T, 2L, dec, 0, 0, ' ', "", "%ld"); TEST (T, 12L, dec, 0, 0, ' ', "", "%ld"); TEST (T, 345L, dec, 0, 0, ' ', "", "%ld"); TEST (T, 6789L, dec, 0, 0, ' ', "", "%ld"); TEST (T, 98765L, dec, 0, 0, ' ', "", "%ld"); TEST (T, LONG_MAX, dec, 0, 0, ' ', "", "%ld"); TEST (T, ~0L, dec, 0, 0, ' ', "", "%ld"); TEST (T, -1L, dec, 0, 0, ' ', "", "%ld"); TEST (T, -2L, dec, 0, 0, ' ', "", "%ld"); TEST (T, -12L, dec, 0, 0, ' ', "", "%ld"); TEST (T, -345L, dec, 0, 0, ' ', "", "%ld"); TEST (T, -6789L, dec, 0, 0, ' ', "", "%ld"); TEST (T, -98765L, dec, 0, 0, ' ', "", "%ld"); TEST (T, LONG_MIN, dec, 0, 0, ' ', "", "%ld"); rw_info (0, 0, __LINE__, "std::ios::dec | std::ios::showbase"); TEST (T, 0L, dec | showbase, 0, 0, ' ', "", "%#ld"); TEST (T, 1234L, dec | showbase, 0, 0, ' ', "", "%#ld"); TEST (T, -1235L, dec | showbase, 0, 0, ' ', "", "%#ld"); TEST (T, LONG_MAX, dec | showbase, 0, 0, ' ', "", "%#ld"); TEST (T, LONG_MIN, dec | showbase, 0, 0, ' ', "", "%#ld"); rw_info (0, 0, __LINE__, "std::ios::dec | std::ios::showpos"); TEST (T, 0L, dec | showpos, 0, 0, ' ', "", "%+ld"); TEST (T, 1236L, dec | showpos, 0, 0, ' ', "", "%+ld"); TEST (T, -1237L, dec | showpos, 0, 0, ' ', "", "%+ld"); TEST (T, LONG_MAX, dec | showpos, 0, 0, ' ', "", "%+ld"); TEST (T, LONG_MIN, dec | showpos, 0, 0, ' ', "", "%+ld"); rw_info (0, 0, __LINE__, "std::ios::dec | std::ios::showbase | std::ios::showpos"); TEST (T, 0L, dec | showbase | showpos, 0, 0, ' ', "", "%#+ld"); TEST (T, 1238L, dec | showbase | showpos, 0, 0, ' ', "", "%#+ld"); TEST (T, -1239L, dec | showbase | showpos, 0, 0, ' ', "", "%#+ld"); TEST (T, LONG_MAX, dec | showbase | showpos, 0, 0, ' ', "", "%#+ld"); TEST (T, LONG_MIN, dec | showbase | showpos, 0, 0, ' ', "", "%#+ld"); // left justfication rw_info (0, 0, __LINE__, "std::ios::dec | std::ios::left"); TEST (T, 0L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 1L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 12L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 123L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 1234L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 12345L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 123456L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 1234567L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 12345678L, dec | left, 0, 10, ' ', "", "%-10ld"); TEST (T, 123456789L, dec | left, 0, 10, ' ', "", "%-10ld"); // left justfication, signed dec TEST (T, -1L, dec | left, 0, 10, ' ', "", "-1 "); TEST (T, -12L, dec | left, 0, 10, ' ', "", "-12 "); TEST (T, -123L, dec | left, 0, 10, ' ', "", "-123 "); TEST (T, -1234L, dec | left, 0, 10, ' ', "", "-1234 "); TEST (T, -12345L, dec | left, 0, 10, ' ', "", "-12345 "); TEST (T, -123456L, dec | left, 0, 10, ' ', "", "-123456 "); TEST (T, -1234567L, dec | left, 0, 10, ' ', "", "-1234567 "); TEST (T, -12345678L, dec | left, 0, 10, ' ', "", "-12345678 "); TEST (T, -123456789L, dec | left, 0, 10, ' ', "", "-123456789"); // left justification with fill char TEST (T, -1L, dec | left, 0, 10, '#', "", "-1########"); TEST (T, -12L, dec | left, 0, 10, '@', "", "-12@@@@@@@"); TEST (T, -123L, dec | left, 0, 10, '*', "", "-123******"); TEST (T, -1234L, dec | left, 0, 10, '=', "", "-1234====="); TEST (T, -12345L, dec | left, 0, 10, '.', "", "-12345...."); TEST (T, -123456L, dec | left, 0, 10, ',', "", "-123456,,,"); TEST (T, -1234567L, dec | left, 0, 10, '-', "", "-1234567--"); TEST (T, -12345678L, dec | left, 0, 10, '+', "", "-12345678+"); TEST (T, -123456789L, dec | left, 0, 10, ';', "", "-123456789"); // left justfication with grouping TEST (T, 1L, dec | left, 0, 14, ' ', "\2", "1 "); TEST (T, 12L, dec | left, 0, 14, ' ', "\2", "12 "); TEST (T, 123L, dec | left, 0, 14, ' ', "\2", "1,23 "); TEST (T, 1234L, dec | left, 0, 14, ' ', "\2", "12,34 "); TEST (T, 12345L, dec | left, 0, 14, ' ', "\2", "1,23,45 "); TEST (T, 123456L, dec | left, 0, 14, ' ', "\2", "12,34,56 "); TEST (T, 1234567L, dec | left, 0, 14, ' ', "\2", "1,23,45,67 "); TEST (T, 12345678L, dec | left, 0, 14, ' ', "\2", "12,34,56,78 "); TEST (T, 123456789L, dec | left, 0, 14, ' ', "\2", "1,23,45,67,89 "); TEST (T, 123456789L, dec | left, 0, 14, ',', "\2", "1,23,45,67,89,"); TEST (T, 1L, dec | left, 0, 14, ' ', "\2\1\3", "1 "); TEST (T, 12L, dec | left, 0, 14, ' ', "\2\1\3", "12 "); TEST (T, 123L, dec | left, 0, 14, ' ', "\2\1\3", "1,23 "); TEST (T, 1234L, dec | left, 0, 14, ' ', "\2\1\3", "1,2,34 "); TEST (T, 12345L, dec | left, 0, 14, ' ', "\2\1\3", "12,3,45 "); TEST (T, 123456L, dec | left, 0, 14, ' ', "\2\1\3", "123,4,56 "); TEST (T, 1234567L, dec | left, 0, 14, ' ', "\2\1\3", "1,234,5,67 "); TEST (T, 12345678L, dec | left, 0, 14, ' ', "\2\1\3", "12,345,6,78 "); TEST (T, 123456789L, dec | left, 0, 14, ' ', "\2\1\3", "123,456,7,89 "); TEST (T, 123456789L, dec | left, 0, 14, '0', "\2\1\3", "123,456,7,8900"); TEST (T, -1L, dec | left, 0, 14, ' ', "\1\2\3", "-1 "); TEST (T, -12L, dec | left, 0, 14, ' ', "\1\2\3", "-1,2 "); TEST (T, -123L, dec | left, 0, 14, ' ', "\1\2\3", "-12,3 "); TEST (T, -1234L, dec | left, 0, 14, ' ', "\1\2\3", "-1,23,4 "); TEST (T, -12345L, dec | left, 0, 14, ' ', "\1\2\3", "-12,34,5 "); TEST (T, -123456L, dec | left, 0, 14, ' ', "\1\2\3", "-123,45,6 "); TEST (T, -1234567L, dec | left, 0, 14, ' ', "\1\2\3", "-1,234,56,7 "); TEST (T, -12345678L, dec | left, 0, 14, ' ', "\1\2\3", "-12,345,67,8 "); TEST (T, -123456789L, dec | left, 0, 14, ' ', "\1\2\3", "-123,456,78,9 "); TEST (T, -123456789L, dec | left, 0, 14, ' ', "\3\1\2", "-1,23,45,6,789"); TEST (T, -123456780L, dec | left, 0, 14, ' ', "\x1", "-1,2,3,4,5,6,7,8,0"); TEST (T, -123456781L, dec | left, 0, 14, ' ', "\x2", "-1,23,45,67,81"); TEST (T, -123456782L, dec | left, 0, 14, ' ', "\x3", "-123,456,782 "); TEST (T, -123456783L, dec | left, 0, 14, ' ', "\x4", "-1,2345,6783 "); TEST (T, -123456784L, dec | left, 0, 14, ' ', "\x5", "-1234,56784 "); TEST (T, -123456785L, dec | left, 0, 14, ' ', "\x6", "-123,456785 "); TEST (T, -123456786L, dec | left, 0, 14, ' ', "\x7", "-12,3456786 "); TEST (T, -123456787L, dec | left, 0, 14, ' ', "\x8", "-1,23456787 "); TEST (T, -123456788L, dec | left, 0, 14, ' ', "\x9", "-123456788 "); #ifndef _RWSTD_NO_EXT_BIN_IO rw_info (0, 0, __LINE__, "std::ios::dec | std::ios::bin [extension]"); TEST (T, 33333333L, bin | dec, 0, 0, ' ', "", "%ld"); #endif // _RWSTD_NO_EXT_BIN_IO ////////////////////////////////////////////////////////////////// // explicit octal ouptut rw_info (0, 0, __LINE__, "std::ios::oct"); TEST (T, 0L, oct, 0, 0, ' ', "", "%lo"); TEST (T, 1L, oct, 0, 0, ' ', "", "%lo"); TEST (T, 2L, oct, 0, 0, ' ', "", "%lo"); TEST (T, 12L, oct, 0, 0, ' ', "", "%lo"); TEST (T, 345L, oct, 0, 0, ' ', "", "%lo"); TEST (T, 6789L, oct, 0, 0, ' ', "", "%lo"); TEST (T, 98765L, oct, 0, 0, ' ', "", "%lo"); TEST (T, LONG_MAX, oct, 0, 0, ' ', "", "%lo"); TEST (T, LONG_MAX - 1, oct, 0, 0, ' ', "", "%lo"); // negative values formatted as oct cause overflow on input (lwg issue 23) TEST (T, ~0L, oct, 0, 0, ' ', "", "%lo", GET_FAIL); TEST (T, -1L, oct, 0, 0, ' ', "", "%lo", GET_FAIL); TEST (T, -2L, oct, 0, 0, ' ', "", "%lo", GET_FAIL); TEST (T, -12L, oct, 0, 0, ' ', "", "%lo", GET_FAIL); TEST (T, -345L, oct, 0, 0, ' ', "", "%lo", GET_FAIL); TEST (T, -6789L, oct, 0, 0, ' ', "", "%lo", GET_FAIL); TEST (T, -98765L, oct, 0, 0, ' ', "", "%lo", GET_FAIL); TEST (T, LONG_MIN, oct, 0, 0, ' ', "", "%lo", GET_FAIL); rw_info (0, 0, __LINE__, "std::ios::oct | std::ios::dec"); TEST (T, 13579L, oct | dec, 0, 0, ' ', "", "%ld"); rw_info (0, 0, __LINE__, "std::ios::oct | std::ios::showbase"); TEST (T, 0L, oct | showbase, 0, 0, ' ', "", "%#lo"); TEST (T, 2345L, oct | showbase, 0, 0, ' ', "", "%#lo"); TEST (T, -2346L, oct | showbase, 0, 0, ' ', "", "%#lo", GET_FAIL); TEST (T, LONG_MAX, oct | showbase, 0, 0, ' ', "", "%#+lo"); TEST (T, LONG_MIN, oct | showbase, 0, 0, ' ', "", "%#+lo", GET_FAIL); rw_info (0, 0, __LINE__, "std::ios::oct | std::ios::showpos"); TEST (T, 0L, oct | showpos, 0, 0, ' ', "", "%+lo"); TEST (T, 2347L, oct | showpos, 0, 0, ' ', "", "%+lo"); TEST (T, -2348L, oct | showpos, 0, 0, ' ', "", "%+lo", GET_FAIL); TEST (T, LONG_MAX, oct | showpos, 0, 0, ' ', "", "%+lo"); TEST (T, LONG_MIN, oct | showpos, 0, 0, ' ', "", "%+lo", GET_FAIL); rw_info (0, 0, __LINE__, "std::ios::oct | std::ios::showbase | std::ios::showpos"); TEST (T, 0L, oct | showbase | showpos, 0, 0, ' ', "", "%#+lo"); TEST (T, 2349L, oct | showbase | showpos, 0, 0, ' ', "", "%#+lo"); TEST (T, -2350L, oct | showbase | showpos, 0, 0, ' ', "", "%#+lo", GET_FAIL); TEST (T, LONG_MAX, oct | showbase | showpos, 0, 0, ' ', "", "%#+lo"); TEST (T, LONG_MIN, oct | showbase | showpos, 0, 0, ' ', "", "%#+lo", GET_FAIL); #ifndef _RWSTD_NO_EXT_BIN_IO rw_info (0, 0, __LINE__, "std::ios::oct | std::ios::bin [extension]"); TEST (T, 22222222L, bin | oct, 0, 0, ' ', "", "%ld"); #endif // _RWSTD_NO_EXT_BIN_IO ////////////////////////////////////////////////////////////////// // explicit hexadecimal ouptut rw_info (0, 0, __LINE__, "std::ios::hex"); TEST (T, 0L, hex, 0, 0, ' ', "", "%lx"); TEST (T, 1L, hex, 0, 0, ' ', "", "%lx"); TEST (T, 2L, hex, 0, 0, ' ', "", "%lx"); TEST (T, 12L, hex, 0, 0, ' ', "", "%lx"); TEST (T, 345L, hex, 0, 0, ' ', "", "%lx"); TEST (T, 6789L, hex, 0, 0, ' ', "", "%lx"); TEST (T, 98765L, hex, 0, 0, ' ', "", "%lx"); TEST (T, LONG_MAX, hex, 0, 0, ' ', "", "%lx"); TEST (T, LONG_MAX - 1, hex, 0, 0, ' ', "", "%lx"); TEST (T, LONG_MAX - 2, hex, 0, 0, ' ', "", "%lx"); // negative values formatted as hex cause overflow on input (lwg issue 23) TEST (T, ~0L, hex, 0, 0, ' ', "", "%lx", GET_FAIL); TEST (T, -1L, hex, 0, 0, ' ', "", "%lx", GET_FAIL); TEST (T, -2L, hex, 0, 0, ' ', "", "%lx", GET_FAIL); TEST (T, -12L, hex, 0, 0, ' ', "", "%lx", GET_FAIL); TEST (T, -345L, hex, 0, 0, ' ', "", "%lx", GET_FAIL); TEST (T, -6789L, hex, 0, 0, ' ', "", "%lx", GET_FAIL); TEST (T, -98765L, hex, 0, 0, ' ', "", "%lx", GET_FAIL); TEST (T, LONG_MIN, hex, 0, 0, ' ', "", "%lx", GET_FAIL); rw_info (0, 0, __LINE__, "std::ios::hex | std::ios::uppercase"); TEST (T, 0L, hex | uppercase, 0, 0, ' ', "", "%lX"); TEST (T, 1L, hex | uppercase, 0, 0, ' ', "", "%lX"); TEST (T, 0XABCDL, hex | uppercase, 0, 0, ' ', "", "%lX"); TEST (T, 0XBCDEL, hex | uppercase, 0, 0, ' ', "", "%lX"); TEST (T, 0XCDEFL, hex | uppercase, 0, 0, ' ', "", "%lX"); rw_info (0, 0, __LINE__, "std::ios::hex | std::ios::showbase"); TEST (T, 0L, hex | showbase, 0, 0, ' ', "", "%#lx"); TEST (T, 1L, hex | showbase, 0, 0, ' ', "", "%#lx"); TEST (T, 0xdef1L, hex | showbase, 0, 0, ' ', "", "%#lx"); rw_info (0, 0, __LINE__, "std::ios::hex | std::ios::uppercase | std::ios::showbase"); TEST (T, 0L, hex | uppercase | showbase, 0, 0, ' ', "", "%#lX"); TEST (T, 1L, hex | uppercase | showbase, 0, 0, ' ', "", "%#lX"); TEST (T, 0XEF02L, hex | uppercase | showbase, 0, 0, ' ', "", "%#lX"); rw_info (0, 0, __LINE__, "std::ios::hex | std::ios::oct"); TEST (T, 0L, oct | hex, 0, 0, ' ', "", "%ld"); TEST (T, 97531L, oct | hex, 0, 0, ' ', "", "%ld"); rw_info (0, 0, __LINE__, "std::ios::hex | std::ios::dec"); TEST (T, 86420L, dec | hex, 0, 0, ' ', "", "%ld"); rw_info (0, 0, __LINE__, "std::ios::hex | std::ios::dec | std::ios::oct"); TEST (T, 11111111L, oct | dec | hex, 0, 0, ' ', "", "%ld"); #ifndef _RWSTD_NO_EXT_BIN_IO rw_info (0, 0, __LINE__, "std::ios::hex | std::ios::bin [extension]"); TEST (T, 44444444L, bin | hex, 0, 0, ' ', "", "%ld"); rw_info (0, 0, __LINE__, "std::ios::hex | std::ios::dec | " "std::ios::oct | std::ios::bin [extension]"); TEST (T, 55555555L, bin | oct | dec | hex, 0, 0, ' ', "", "%ld"); #endif // _RWSTD_NO_EXT_BIN_IO ////////////////////////////////////////////////////////////////// // extension: fixed and negative precision rw_info (0, 0, __LINE__, "std::ios::fixed with negative precision [extension]"); TEST (T, 987654321L, 0, -1, 0, ' ', "", "987654321"); TEST (T, 987654322L, fixed, 0, 0, ' ', "", "987654322"); TEST (T, 987654323L, fixed, -1, 0, ' ', "", "98765432*3"); TEST (T, -987654323L, fixed, -1, 0, ' ', "", "-98765432*3"); TEST (T, 987654324L, fixed, -2, 0, ' ', "", "9876543*24"); TEST (T, -987654324L, fixed, -2, 0, ' ', "", "-9876543*24"); TEST (T, 987654325L, fixed, -3, 0, ' ', "", "987654*325"); TEST (T, -987654325L, fixed, -3, 0, ' ', "", "-987654*325"); TEST (T, 987654326L, fixed, -4, 0, ' ', "", "98765*4326"); TEST (T, -987654326L, fixed, -4, 0, ' ', "", "-98765*4326"); TEST (T, 987654327L, fixed, -5, 0, ' ', "", "9876*54327"); TEST (T, -987654327L, fixed, -5, 0, ' ', "", "-9876*54327"); TEST (T, 987654328L, fixed, -6, 0, ' ', "", "987*654328"); TEST (T, -987654328L, fixed, -6, 0, ' ', "", "-987*654328"); TEST (T, 987654329L, fixed, -7, 0, ' ', "", "98*7654329"); TEST (T, -987654329L, fixed, -7, 0, ' ', "", "-98*7654329"); TEST (T, 987654330L, fixed, -8, 0, ' ', "", "9*87654330"); TEST (T, -987654330L, fixed, -8, 0, ' ', "", "-9*87654330"); TEST (T, 987654331L, fixed, -9, 0, ' ', "", "0*987654331"); TEST (T, -987654331L, fixed, -9, 0, ' ', "", "-0*987654331"); TEST (T, 987654332L, fixed, -10, 0, ' ', "", "0*0987654332"); TEST (T, -987654332L, fixed, -10, 0, ' ', "", "-0*0987654332"); TEST (T, 987654333L, fixed, -11, 0, ' ', "", "0*00987654333"); TEST (T, -987654333L, fixed, -11, 0, ' ', "", "-0*00987654333"); TEST (T, 0L, fixed, -12, 0, ' ', "", "0*000000000000"); ////////////////////////////////////////////////////////////////// // second group is the last group (i.e., prevent repetition) #if CHAR_MAX == UCHAR_MAX # define GROUPING "\2\1\xff" #else # define GROUPING "\2\1\x7f" #endif TEST (T, 123456789L, dec | left, 0, 0, ' ', GROUPING, "123456,7,89"); TEST (T, -123456789L, dec | left, 0, 0, ' ', GROUPING, "-123456,7,89"); #undef GROUPING #if CHAR_MAX == UCHAR_MAX # define GROUPING "\2\3\xff" #else # define GROUPING "\2\3\x7f" #endif TEST (T, 123456789L, dec | left, 0, 0, ' ', GROUPING, "1234,567,89"); TEST (T, -123456789L, dec | left, 0, 0, ' ', GROUPING, "-1234,567,89"); TEST (T, 0x12345678L, hex | showbase, 0, 0, ' ', GROUPING, "0x123,456,78"); ////////////////////////////////////////////////////////////////// // right justfication rw_info (0, 0, __LINE__, "std::ios::right"); TEST (T, 1L, dec | right, 0, 10, ' ', "", " 1"); TEST (T, 12L, dec | right, 0, 10, ' ', "", " 12"); TEST (T, 123L, dec | right, 0, 10, ' ', "", " 123"); TEST (T, 1234L, dec | right, 0, 10, ' ', "", " 1234"); TEST (T, 12345L, dec | right, 0, 10, ' ', "", " 12345"); TEST (T, 123456L, dec | right, 0, 10, ' ', "", " 123456"); TEST (T, 1234567L, dec | right, 0, 10, ' ', "", " 1234567"); TEST (T, 12345678L, dec | right, 0, 10, ' ', "", " 12345678"); TEST (T, 123456789L, dec | right, 0, 10, ' ', "", " 123456789"); TEST (T, 123456789L, dec | right, 0, 10, '0', "", "0123456789"); TEST (T, 123456789L, dec | right, 0, 10, '+', "", "+123456789"); TEST (T, 123456789L, dec | right, 0, 10, '-', "", "-123456789"); // right justification, oct TEST (T, 0L, oct | right, 0, 10, ' ', "", " 0"); TEST (T, 01L, oct | right, 0, 10, ' ', "", " 1"); TEST (T, 012L, oct | right, 0, 10, ' ', "", " 12"); TEST (T, 0123L, oct | right, 0, 10, ' ', "", " 123"); TEST (T, 01234L, oct | right, 0, 10, ' ', "", " 1234"); TEST (T, 012345L, oct | right, 0, 10, ' ', "", " 12345"); TEST (T, 0123456L, oct | right, 0, 10, ' ', "", " 123456"); TEST (T, 01234567L, oct | right, 0, 10, ' ', "", " 1234567"); TEST (T, 012345670L, oct | right, 0, 10, ' ', "", " 12345670"); TEST (T, 012345670L, oct | right, 0, 10, '1', "", "1112345670"); // right justification with grouping TEST (T, 0L, oct | right, 0, 10, ' ', "\2", " 0"); TEST (T, 01L, oct | right, 0, 10, ' ', "\2", " 1"); TEST (T, 012L, oct | right, 0, 10, ' ', "\2", " 12"); TEST (T, 0123L, oct | right, 0, 10, ' ', "\2", " 1,23"); TEST (T, 01234L, oct | right, 0, 10, ' ', "\2", " 12,34"); TEST (T, 012345L, oct | right, 0, 10, ' ', "\2", " 1,23,45"); TEST (T, 0123456L, oct | right, 0, 10, ' ', "\2", " 12,34,56"); TEST (T, 01234567L, oct | right, 0, 10, ' ', "\2", "1,23,45,67"); TEST (T, 012345670L, oct | right, 0, 10, ' ', "\2", "12,34,56,70"); #undef FLAGS #define flags hex | showbase | internal #define FLAGS flags | uppercase // internal justfication, hex rw_info (0, 0, __LINE__, "std::ios::internal"); TEST (T, 0X1L, FLAGS, 0, 10, ' ', "", "0X 1"); TEST (T, 0x12L, flags, 0, 10, ' ', "", "0x 12"); TEST (T, 0X123L, FLAGS, 0, 10, ' ', "", "0X 123"); TEST (T, 0x1234L, flags, 0, 10, ' ', "", "0x 1234"); TEST (T, 0X12345L, FLAGS, 0, 10, ' ', "", "0X 12345"); TEST (T, 0x123abcL, flags, 0, 10, ' ', "", "0x 123abc"); TEST (T, 0x123abcL, flags, 0, 10, '0', "", "0x00123abc"); TEST (T, 0X1234ABCL, FLAGS, 0, 10, ' ', "", "0X 1234ABC"); TEST (T, 0X12345678L, FLAGS, 0, 10, ' ', "", "0X12345678"); TEST (T, 0X12345678L, FLAGS, 0, 10, '0', "", "0X12345678"); // internal justfication, hex, grouping TEST (T, 0X1L, FLAGS, 0, 10, ' ', "\1\2", "0X 1"); TEST (T, 0x12L, flags, 0, 10, ' ', "\1\2", "0x 1,2"); TEST (T, 0X123L, FLAGS, 0, 10, ' ', "\1\2", "0X 12,3"); TEST (T, 0x1234L, flags, 0, 10, ' ', "\1\2", "0x 1,23,4"); TEST (T, 0X12345L, FLAGS, 0, 10, ' ', "\1\2", "0X 12,34,5"); TEST (T, 0X12345L, FLAGS, 0, 10, ',', "\1\2", "0X,12,34,5"); TEST (T, 0x123abcL, flags, 0, 10, ' ', "\1\2", "0x1,23,ab,c"); TEST (T, 0X1234ABCL, FLAGS, 0, 10, ' ', "\1\2", "0X12,34,AB,C"); TEST (T, 0X12345678L, FLAGS, 0, 10, ' ', "\1\2", "0X1,23,45,67,8"); TEST (T, 0X12345678L, FLAGS, 0, 10, '0', "\1\2", "0X1,23,45,67,8"); #undef flags #undef FLAGS #define FLAGS dec | showpos | internal // internal justfication, signed dec TEST (T, 0L, FLAGS, 0, 10, ' ', "", "+ 0"); TEST (T, -1L, FLAGS, 0, 10, ' ', "", "- 1"); TEST (T, +12L, FLAGS, 0, 10, ' ', "", "+ 12"); TEST (T, -123L, FLAGS, 0, 10, ' ', "", "- 123"); TEST (T, +1234L, FLAGS, 0, 10, ' ', "", "+ 1234"); TEST (T, -12345L, FLAGS, 0, 10, ' ', "", "- 12345"); TEST (T, +123456L, FLAGS, 0, 10, ' ', "", "+ 123456"); TEST (T, -1234567L, FLAGS, 0, 10, ' ', "", "- 1234567"); TEST (T, +12345678L, FLAGS, 0, 10, ' ', "", "+ 12345678"); TEST (T, -123456789L, FLAGS, 0, 10, '0', "", "-123456789"); TEST (T, +1L, FLAGS, 0, 10, '-', "", "+--------1"); TEST (T, -12L, FLAGS, 0, 10, '-', "", "--------12"); TEST (T, +123L, FLAGS, 0, 10, '+', "", "+++++++123"); TEST (T, -1234L, FLAGS, 0, 10, '+', "", "-+++++1234"); TEST (T, +12345L, FLAGS, 0, 10, '0', "", "+000012345"); TEST (T, -123456L, FLAGS, 0, 10, '1', "", "-111123456"); TEST (T, +1234567L, FLAGS, 0, 10, '2', "", "+221234567"); TEST (T, -12345678L, FLAGS, 0, 10, '3', "", "-312345678"); TEST (T, +123456789L, FLAGS, 0, 10, '4', "", "+123456789"); #ifndef _RWSTD_NO_EXT_BIN_IO // bin rw_info (0, 0, __LINE__, "std::ios::bin [extension]"); TEST (T, 0L, bin, 0, 16, '.', "\4", "...............0"); TEST (T, 1L, bin, 0, 16, '.', "\4", "...............1"); TEST (T, 2L, bin, 0, 16, '.', "\4", "..............10"); TEST (T, 3L, bin, 0, 16, '.', "\4", "..............11"); TEST (T, 4L, bin, 0, 16, '.', "\4", ".............100"); TEST (T, 5L, bin, 0, 16, '.', "\4", ".............101"); TEST (T, 6L, bin, 0, 16, '.', "\4", ".............110"); TEST (T, 7L, bin, 0, 16, '.', "\4", ".............111"); TEST (T, 8L, bin, 0, 16, '.', "\4", "............1000"); TEST (T, 9L, bin, 0, 16, '.', "\4", "............1001"); TEST (T, 0x0aL, bin, 0, 16, '.', "\4", "............1010"); TEST (T, 0x0bL, bin, 0, 16, '.', "\4", "............1011"); TEST (T, 0x0cL, bin, 0, 16, '.', "\4", "............1100"); TEST (T, 0x0dL, bin, 0, 16, '.', "\4", "............1101"); TEST (T, 0x0eL, bin, 0, 16, '.', "\4", "............1110"); TEST (T, 0x0fL, bin, 0, 16, '.', "\4", "............1111"); TEST (T, 0xf0L, bin, 0, 16, '.', "\4", ".......1111,0000"); TEST (T, 0xf1L, bin, 0, 16, '.', "\4", ".......1111,0001"); TEST (T, 0xf2L, bin, 0, 16, '.', "\4", ".......1111,0010"); TEST (T, 0xf3L, bin, 0, 16, '.', "\4", ".......1111,0011"); TEST (T, 0xf4L, bin, 0, 16, '.', "\4", ".......1111,0100"); TEST (T, 0xf5L, bin, 0, 16, '.', "\4", ".......1111,0101"); TEST (T, 0x12345678L, bin, 0, 0, '.', "\4", "1,0010,0011,0100,0101,0110,0111,1000"); TEST (T, 0xfedcba98L, bin, 0, 0, '\0', "\010", "11111110,11011100,10111010,10011000"); #endif // _RWSTD_NO_EXT_BIN_IO // locale 3.0 extension #define BASE(n) int (unsigned (n) << _RWSTD_IOS_BASEOFF) // bases 0 and 10 are both base 10 // base 1 is roman (values 1 through 4999) // bases 2 through 36 are what they are // anything else is unspecified rw_info (0, 0, __LINE__, "base 1 (Roman), and 2 through 36 [extension]"); TEST (T, 1234L, BASE ( 0), 0, 0, '\0', "", "1234"); TEST (T, 1234L, BASE ( 1), 0, 0, '\0', "", "mccxxxiv"); TEST (T, 0x1234L, BASE ( 2), 0, 0, '\0', "", "1001000110100"); TEST (T, 01234L, oct | BASE ( 8), 0, 0, '\0', "", "1234"); TEST (T, 1234L, dec | BASE (10), 0, 0, '\0', "", "1234"); TEST (T, 0x1234L, hex | BASE (16), 0, 0, '\0', "", "1234"); TEST (T, 1234L, BASE ( 2), 0, 0, '\0', "", "10011010010"); TEST (T, 1234L, BASE ( 3), 0, 0, '\0', "", "1200201"); TEST (T, 1234L, BASE ( 4), 0, 0, '\0', "", "103102"); TEST (T, 1234L, BASE ( 5), 0, 0, '\0', "", "14414"); TEST (T, 1234L, BASE ( 6), 0, 0, '\0', "", "5414"); TEST (T, 1234L, BASE ( 7), 0, 0, '\0', "", "3412"); TEST (T, 1234L, BASE ( 9), 0, 0, '\0', "", "1621"); TEST (T, 1234L, dec | BASE (10), 0, 0, '\0', "", "1234"); TEST (T, 1234L, BASE (11), 0, 0, '\0', "", "a22"); TEST (T, 1234L, BASE (12), 0, 0, '\0', "", "86a"); TEST (T, 1234L, BASE (13), 0, 0, '\0', "", "73c"); TEST (T, 1234L, BASE (14), 0, 0, '\0', "", "642"); TEST (T, 1234L, BASE (15), 0, 0, '\0', "", "574"); TEST (T, 1234L, hex | BASE (16), 0, 0, '\0', "", "4d2"); TEST (T, 1234L, BASE (17), 0, 0, '\0', "", "44a"); TEST (T, 1234L, BASE (18), 0, 0, '\0', "", "3ea"); TEST (T, 1234L, BASE (19), 0, 0, '\0', "", "37i"); TEST (T, 1234L, BASE (20), 0, 0, '\0', "", "31e"); TEST (T, 1234L, BASE (21), 0, 0, '\0', "", "2gg"); TEST (T, 1234L, BASE (22), 0, 0, '\0', "", "2c2"); TEST (T, 1234L, BASE (23), 0, 0, '\0', "", "27f"); TEST (T, 1234L, BASE (24), 0, 0, '\0', "", "23a"); TEST (T, 1234L, BASE (25), 0, 0, '\0', "", "1o9"); TEST (T, 1234L, BASE (26), 0, 0, '\0', "", "1lc"); TEST (T, 1234L, BASE (27), 0, 0, '\0', "", "1ij"); TEST (T, 1234L, BASE (28), 0, 0, '\0', "", "1g2"); TEST (T, 1234L, BASE (29), 0, 0, '\0', "", "1dg"); TEST (T, 1234L, BASE (30), 0, 0, '\0', "", "1b4"); TEST (T, 1234L, BASE (31), 0, 0, '\0', "", "18p"); TEST (T, 1234L, BASE (32), 0, 0, '\0', "", "16i"); TEST (T, 1234L, BASE (33), 0, 0, '\0', "", "14d"); TEST (T, 1234L, BASE (34), 0, 0, '\0', "", "12a"); TEST (T, 1234L, BASE (35), 0, 0, '\0', "", "109"); TEST (T, 1234L, BASE (36), 0, 0, '\0', "", "ya"); // effect of non-empty grouping is unspecified TEST (T, 0L, BASE (1), 0, 0, '\0', "", "0"); TEST (T, 1L, BASE (1), 0, 0, '\0', "", "i"); TEST (T, 2L, BASE (1), 0, 0, '\0', "", "ii"); TEST (T, 3L, BASE (1), 0, 0, '\0', "", "iii"); TEST (T, 4L, BASE (1), 0, 0, '\0', "", "iv"); TEST (T, 5L, BASE (1), 0, 0, '\0', "", "v"); TEST (T, 6L, BASE (1), 0, 0, '\0', "", "vi"); TEST (T, 7L, BASE (1), 0, 0, '\0', "", "vii"); TEST (T, 8L, BASE (1), 0, 0, '\0', "", "viii"); TEST (T, 9L, BASE (1), 0, 0, '\0', "", "ix"); TEST (T, 10L, BASE (1), 0, 0, '\0', "", "x"); TEST (T, 50L, BASE (1), 0, 0, '\0', "", "l"); TEST (T, 100L, BASE (1), 0, 0, '\0', "", "c"); TEST (T, 500L, BASE (1), 0, 0, '\0', "", "d"); TEST (T, 1000L, BASE (1), 0, 0, '\0', "", "m"); TEST (T, 49L, BASE (1), 0, 0, '\0', "", "xlix"); TEST (T, 88L, BASE (1), 0, 0, '\0', "", "lxxxviii"); TEST (T, 99L, BASE (1), 0, 0, '\0', "", "xcix"); TEST (T, 1999L, BASE (1), 0, 0, '\0', "", "mcmxcix"); TEST (T, 2000L, BASE (1), 0, 0, '\0', "", "mm"); TEST (T, 2001L, BASE (1), 0, 0, '\0', "", "mmi"); TEST (T, 4999L, BASE (1), 0, 0, '\0', "", "mmmmcmxcix"); TEST (T, 5000L, BASE (1), 0, 0, '\0', "", "5000"); TEST (T, 1492L, BASE (1), 0, 10, '*', "", "***mcdxcii"); TEST (T, 1776L, BASE (1) | uppercase, 0, 0, '\0', "", "MDCCLXXVI"); } /**************************************************************************/ template <class charT> void ulong_test (charT, const char *cname) { const char* const tname = "unsigned long"; rw_info (0, 0, __LINE__, "std::num_put<%s>::put (..., %s)", cname, tname); typedef unsigned long ULong; ////////////////////////////////////////////////////////////////// rw_info (0, 0, __LINE__, "std::ios::dec"); TEST (T, 0UL, dec, 0, 0, ' ', "", "%lu"); TEST (T, ULong (LONG_MAX), dec, 0, 0, ' ', "", "%lu"); rw_info (0, 0, __LINE__, "std::ios::dec | std::ios::shopos"); TEST (T, 0UL, dec | showpos, 0, 0, ' ', "", "%+lu"); TEST (T, 1UL, dec | showpos, 0, 0, ' ', "", "%+lu"); TEST (T, ULong (LONG_MAX), dec | showpos, 0, 0, ' ', "", "%+lu"); ////////////////////////////////////////////////////////////////// rw_info (0, 0, __LINE__, "std::ios::oct"); TEST (T, ULong (CHAR_MAX), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (UCHAR_MAX), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (SCHAR_MAX), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (SHRT_MAX), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (USHRT_MAX), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (INT_MAX), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (UINT_MAX), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (LONG_MAX), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (CHAR_MIN), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (SCHAR_MIN), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (SHRT_MIN), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (INT_MIN), oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (LONG_MIN), oct, 0, 0, ' ', "", "%lo"); // no overflow TEST (T, 1UL, oct, 0, 0, ' ', "", "%lo"); TEST (T, ~0UL, oct, 0, 0, ' ', "", "%lo"); TEST (T, ULong (ULONG_MAX), oct, 0, 0, ' ', "", "%lo"); ////////////////////////////////////////////////////////////////// rw_info (0, 0, __LINE__, "std::ios::hex"); TEST (T, ULong (CHAR_MAX), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (UCHAR_MAX), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (SCHAR_MAX), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (SHRT_MAX), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (USHRT_MAX), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (INT_MAX), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (UINT_MAX), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (LONG_MAX), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (CHAR_MIN), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (SCHAR_MIN), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (SHRT_MIN), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (INT_MIN), hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (LONG_MIN), hex, 0, 0, ' ', "", "%lx"); TEST (T, 1UL, hex, 0, 0, ' ', "", "%lx"); TEST (T, ~0UL, hex, 0, 0, ' ', "", "%lx"); TEST (T, ULong (ULONG_MAX), hex, 0, 0, ' ', "", "%lx"); } /**************************************************************************/ template <class charT> void llong_test (charT, const char *cname) { const char* const tname = "long long"; rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s)", cname, tname); #ifndef _RWSTD_NO_LONG_LONG # define STDIO_FMAT "%" _RWSTD_LLONG_PRINTF_PREFIX "d" # ifndef _MSC_VER # define LL(number) number ## LL # else // if defined (_MSC_VER) // MSVC 7.0 doesn't recognize the LL suffix # define LL(number) number ## I64 # endif // _MSC_VER TEST (T, LL (0), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (1), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (21), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (4321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (54321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (654321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (7654321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (87654321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, LL (987654321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, ~LL (0), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (1), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (21), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (4321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (54321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (654321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (7654321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (87654321), dec, 0, 0, ' ', "", STDIO_FMAT); TEST (T, -LL (987654321), dec, 0, 0, ' ', "", STDIO_FMAT); # undef FLAGS # define FLAGS hex | showbase | internal # undef OPTS # define OPTS FLAGS, 0, 20, ' ', "\1\2\3\4\1\2\3\4" // internal justfication, hex format, grouping TEST (T, LL (0), OPTS, " 0"); TEST (T, LL (0x1), OPTS, "0x 1"); TEST (T, LL (0x12), OPTS, "0x 1,2"); TEST (T, LL (0x123), OPTS, "0x 12,3"); TEST (T, LL (0x1234), OPTS, "0x 1,23,4"); TEST (T, LL (0x12345), OPTS, "0x 12,34,5"); TEST (T, LL (0x123456), OPTS, "0x 123,45,6"); TEST (T, LL (0x1234567), OPTS, "0x 1,234,56,7"); TEST (T, LL (0x12345678), OPTS, "0x 12,345,67,8"); TEST (T, LL (0x123456789), OPTS, "0x 123,456,78,9"); TEST (T, LL (0x123456789a), OPTS, "0x 1234,567,89,a"); TEST (T, LL (0x123456789ab), OPTS, "0x 1,2345,678,9a,b"); TEST (T, LL (0x123456789abc), OPTS, "0x 1,2,3456,789,ab,c"); TEST (T, LL (0x123456789abcd), OPTS, "0x12,3,4567,89a,bc,d"); TEST (T, LL (0x123456789abcde), OPTS, "0x1,23,4,5678,9ab,cd,e"); TEST (T, LL (0x123456789abcdef), OPTS, "0x12,34,5,6789,abc,de,f"); TEST (T, LL (0x123456789abcdef0), OPTS, "0x123,45,6,789a,bcd,ef,0"); #else // if defined (_RWSTD_NO_LONG_LONG) rw_note (0, 0, __LINE__, "num_put<%s>::put (..., %s) not exercised, " "macro _RWSTD_NO_LONG_LONG #defined", cname, tname); #endif // _RWSTD_LONG_LONG } /**************************************************************************/ template <class charT> void ullong_test (charT, const char *cname) { const char* const tname = "unsigned long long"; rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s)", cname, tname); #ifndef _RWSTD_NO_LONG_LONG rw_warn (0, 0, __LINE__, "num_put<%s>::put (..., %s) not exercised", cname, tname); #else // if defined (_RWSTD_NO_LONG_LONG) rw_note (0, 0, __LINE__, "num_put<%s>::put (..., %s) not exercised, " "macro _RWSTD_NO_LONG_LONG #defined", cname, tname); #endif // _RWSTD_NO_LONG_LONG } /**************************************************************************/ // use a volatile variable to fool optimizers into not issuing // warnings about division by zero volatile double zero; template <class charT, class floatT> void inf_nan_test (charT, floatT, const char *cname, const char *tname) { rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s) formatting " "infinities", cname, tname); // compute infinity const floatT inf = 1 / zero; ////////////////////////////////////////////////////////////////// // exercise the formatting of positive and negative infinities // +-- value to format // | +-- fmtflags // | | +-- precision // | | | +-- field width // | | | | +-- fill character // | | | | | +-- grouping // | | | | | | +-- expected output // | | | | | | | // V V V V V V V TEST (T, inf, 0, 0, 0, ' ', "", "inf"); TEST (T, inf, showpos, 0, 0, ' ', "", "+inf"); TEST (T, inf, uppercase, 0, 0, ' ', "", "INF"); TEST (T, inf, showpos | uppercase, 0, 0, ' ', "", "+INF"); TEST (T, -inf, 0, 0, 0, ' ', "", "-inf"); TEST (T, -inf, showpos, 0, 0, ' ', "", "-inf"); TEST (T, -inf, uppercase, 0, 0, ' ', "", "-INF"); TEST (T, -inf, showpos | uppercase, 0, 0, ' ', "", "-INF"); TEST (T, inf, 0, 1, 0, ' ', "", "inf"); TEST (T, inf, showpos, 1, 0, ' ', "", "+inf"); TEST (T, inf, uppercase, 1, 0, ' ', "", "INF"); TEST (T, inf, showpos | uppercase, 1, 0, ' ', "", "+INF"); TEST (T, -inf, 0, 1, 0, ' ', "", "-inf"); TEST (T, -inf, showpos, 1, 0, ' ', "", "-inf"); TEST (T, -inf, uppercase, 1, 0, ' ', "", "-INF"); TEST (T, -inf, showpos | uppercase, 1, 0, ' ', "", "-INF"); TEST (T, inf, 0, 3, 0, ' ', "", "inf"); TEST (T, inf, showpos, 3, 0, ' ', "", "+inf"); TEST (T, inf, uppercase, 3, 0, ' ', "", "INF"); TEST (T, inf, showpos | uppercase, 3, 0, ' ', "", "+INF"); TEST (T, -inf, 0, 3, 0, ' ', "", "-inf"); TEST (T, -inf, showpos, 3, 0, ' ', "", "-inf"); TEST (T, -inf, uppercase, 3, 0, ' ', "", "-INF"); TEST (T, -inf, showpos | uppercase, 3, 0, ' ', "", "-INF"); TEST (T, inf, 0, 4, 0, ' ', "", "inf"); TEST (T, inf, showpos, 4, 0, ' ', "", "+inf"); TEST (T, inf, uppercase, 4, 0, ' ', "", "INF"); TEST (T, inf, showpos | uppercase, 4, 0, ' ', "", "+INF"); TEST (T, -inf, 0, 4, 0, ' ', "", "-inf"); TEST (T, -inf, showpos, 4, 0, ' ', "", "-inf"); TEST (T, -inf, uppercase, 4, 0, ' ', "", "-INF"); TEST (T, -inf, showpos | uppercase, 4, 0, ' ', "", "-INF"); TEST (T, inf, 0, 9, 0, ' ', "", "inf"); TEST (T, inf, showpos, 9, 0, ' ', "", "+inf"); TEST (T, inf, uppercase, 9, 0, ' ', "", "INF"); TEST (T, inf, showpos | uppercase, 9, 0, ' ', "", "+INF"); TEST (T, -inf, 0, 9, 0, ' ', "", "-inf"); TEST (T, -inf, showpos, 9, 0, ' ', "", "-inf"); TEST (T, -inf, uppercase, 9, 0, ' ', "", "-INF"); TEST (T, -inf, showpos | uppercase, 9, 0, ' ', "", "-INF"); TEST (T, inf, 0, 0, 1, ' ', "", "inf"); TEST (T, inf, showpos, 0, 1, ' ', "", "+inf"); TEST (T, inf, uppercase, 0, 1, ' ', "", "INF"); TEST (T, inf, showpos | uppercase, 0, 1, ' ', "", "+INF"); TEST (T, -inf, 0, 0, 1, ' ', "", "-inf"); TEST (T, -inf, showpos, 0, 1, ' ', "", "-inf"); TEST (T, -inf, uppercase, 0, 1, ' ', "", "-INF"); TEST (T, -inf, showpos | uppercase, 0, 1, ' ', "", "-INF"); TEST (T, inf, 0, 0, 3, ' ', "", "inf"); TEST (T, inf, showpos, 0, 3, ' ', "", "+inf"); TEST (T, inf, uppercase, 0, 3, ' ', "", "INF"); TEST (T, inf, showpos | uppercase, 0, 3, ' ', "", "+INF"); TEST (T, -inf, 0, 0, 3, ' ', "", "-inf"); TEST (T, -inf, showpos, 0, 3, ' ', "", "-inf"); TEST (T, -inf, uppercase, 0, 3, ' ', "", "-INF"); TEST (T, -inf, showpos | uppercase, 0, 3, ' ', "", "-INF"); TEST (T, inf, 0, 0, 4, ' ', "", " inf"); TEST (T, inf, showpos, 0, 4, ' ', "", "+inf"); TEST (T, inf, uppercase, 0, 4, ' ', "", " INF"); TEST (T, inf, showpos | uppercase, 0, 4, ' ', "", "+INF"); TEST (T, -inf, 0, 0, 4, ' ', "", "-inf"); TEST (T, -inf, showpos, 0, 4, ' ', "", "-inf"); TEST (T, -inf, uppercase, 0, 4, ' ', "", "-INF"); TEST (T, -inf, showpos | uppercase, 0, 4, ' ', "", "-INF"); TEST (T, inf, 0, 0, 8, ' ', "", " inf"); TEST (T, inf, showpos, 0, 8, ' ', "", " +inf"); TEST (T, inf, uppercase, 0, 8, ' ', "", " INF"); TEST (T, inf, showpos | uppercase, 0, 8, ' ', "", " +INF"); TEST (T, -inf, 0, 0, 8, ' ', "", " -inf"); TEST (T, -inf, showpos, 0, 8, ' ', "", " -inf"); TEST (T, -inf, uppercase, 0, 8, ' ', "", " -INF"); TEST (T, -inf, showpos | uppercase, 0, 8, ' ', "", " -INF"); TEST (T, inf, left, 0, 9, ' ', "", "inf "); TEST (T, inf, left | showpos, 0, 9, ' ', "", "+inf "); TEST (T, inf, left | uppercase, 0, 9, ' ', "", "INF "); TEST (T, inf, left | showpos | uppercase, 0, 9, ' ', "", "+INF "); TEST (T, -inf, left, 0, 9, ' ', "", "-inf "); TEST (T, -inf, left | showpos, 0, 9, ' ', "", "-inf "); TEST (T, -inf, left | uppercase, 0, 9, ' ', "", "-INF "); TEST (T, -inf, left | showpos | uppercase, 0, 9, ' ', "", "-INF "); TEST (T, inf, right, 0, 9, ' ', "", " inf"); TEST (T, inf, right | showpos, 0, 9, ' ', "", " +inf"); TEST (T, inf, right | uppercase, 0, 9, ' ', "", " INF"); TEST (T, inf, right | showpos | uppercase, 0, 9, ' ', "", " +INF"); TEST (T, -inf, right, 0, 9, ' ', "", " -inf"); TEST (T, -inf, right | showpos, 0, 9, ' ', "", " -inf"); TEST (T, -inf, right | uppercase, 0, 9, ' ', "", " -INF"); TEST (T, -inf, right | showpos | uppercase, 0, 9, ' ', "", " -INF"); ////////////////////////////////////////////////////////////////// // exercise the formatting of positive and negative (quiet) NaNs rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s) formatting " "NaN's", cname, tname); // compute a quiet NaN #if 0 // temporarily disabled (NAN format is platform specific // and subject to bugs -- see for example STDCXX-464) const floatT nan = 0 / zero; TEST (T, nan, 0, 0, 0, ' ', "", "nan"); TEST (T, nan, showpos, 0, 0, ' ', "", "+nan"); TEST (T, nan, uppercase, 0, 0, ' ', "", "NAN"); TEST (T, nan, showpos | uppercase, 0, 0, ' ', "", "+NAN"); TEST (T, -nan, 0, 0, 0, ' ', "", "-nan"); TEST (T, -nan, showpos, 0, 0, ' ', "", "-nan"); TEST (T, -nan, uppercase, 0, 0, ' ', "", "-NAN"); TEST (T, -nan, showpos | uppercase, 0, 0, ' ', "", "-NAN"); TEST (T, nan, 0, 1, 0, ' ', "", "nan"); TEST (T, nan, showpos, 1, 0, ' ', "", "+nan"); TEST (T, nan, uppercase, 1, 0, ' ', "", "NAN"); TEST (T, nan, showpos | uppercase, 1, 0, ' ', "", "+NAN"); TEST (T, -nan, 0, 1, 0, ' ', "", "-nan"); TEST (T, -nan, showpos, 1, 0, ' ', "", "-nan"); TEST (T, -nan, uppercase, 1, 0, ' ', "", "-NAN"); TEST (T, -nan, showpos | uppercase, 1, 0, ' ', "", "-NAN"); TEST (T, nan, 0, 3, 0, ' ', "", "nan"); TEST (T, nan, showpos, 3, 0, ' ', "", "+nan"); TEST (T, nan, uppercase, 3, 0, ' ', "", "NAN"); TEST (T, nan, showpos | uppercase, 3, 0, ' ', "", "+NAN"); TEST (T, -nan, 0, 3, 0, ' ', "", "-nan"); TEST (T, -nan, showpos, 3, 0, ' ', "", "-nan"); TEST (T, -nan, uppercase, 3, 0, ' ', "", "-NAN"); TEST (T, -nan, showpos | uppercase, 3, 0, ' ', "", "-NAN"); TEST (T, nan, 0, 4, 0, ' ', "", "nan"); TEST (T, nan, showpos, 4, 0, ' ', "", "+nan"); TEST (T, nan, uppercase, 4, 0, ' ', "", "NAN"); TEST (T, nan, showpos | uppercase, 4, 0, ' ', "", "+NAN"); TEST (T, -nan, 0, 4, 0, ' ', "", "-nan"); TEST (T, -nan, showpos, 4, 0, ' ', "", "-nan"); TEST (T, -nan, uppercase, 4, 0, ' ', "", "-NAN"); TEST (T, -nan, showpos | uppercase, 4, 0, ' ', "", "-NAN"); TEST (T, nan, 0, 9, 0, ' ', "", "nan"); TEST (T, nan, showpos, 9, 0, ' ', "", "+nan"); TEST (T, nan, uppercase, 9, 0, ' ', "", "NAN"); TEST (T, nan, showpos | uppercase, 9, 0, ' ', "", "+NAN"); TEST (T, -nan, 0, 9, 0, ' ', "", "-nan"); TEST (T, -nan, showpos, 9, 0, ' ', "", "-nan"); TEST (T, -nan, uppercase, 9, 0, ' ', "", "-NAN"); TEST (T, -nan, showpos | uppercase, 9, 0, ' ', "", "-NAN"); TEST (T, nan, 0, 0, 1, ' ', "", "nan"); TEST (T, nan, showpos, 0, 1, ' ', "", "+nan"); TEST (T, nan, uppercase, 0, 1, ' ', "", "NAN"); TEST (T, nan, showpos | uppercase, 0, 1, ' ', "", "+NAN"); TEST (T, -nan, 0, 0, 1, ' ', "", "-nan"); TEST (T, -nan, showpos, 0, 1, ' ', "", "-nan"); TEST (T, -nan, uppercase, 0, 1, ' ', "", "-NAN"); TEST (T, -nan, showpos | uppercase, 0, 1, ' ', "", "-NAN"); TEST (T, nan, 0, 0, 3, ' ', "", "nan"); TEST (T, nan, showpos, 0, 3, ' ', "", "+nan"); TEST (T, nan, uppercase, 0, 3, ' ', "", "NAN"); TEST (T, nan, showpos | uppercase, 0, 3, ' ', "", "+NAN"); TEST (T, -nan, 0, 0, 3, ' ', "", "-nan"); TEST (T, -nan, showpos, 0, 3, ' ', "", "-nan"); TEST (T, -nan, uppercase, 0, 3, ' ', "", "-NAN"); TEST (T, -nan, showpos | uppercase, 0, 3, ' ', "", "-NAN"); TEST (T, nan, 0, 0, 4, ' ', "", " nan"); TEST (T, nan, showpos, 0, 4, ' ', "", "+nan"); TEST (T, nan, uppercase, 0, 4, ' ', "", " NAN"); TEST (T, nan, showpos | uppercase, 0, 4, ' ', "", "+NAN"); TEST (T, -nan, 0, 0, 4, ' ', "", "-nan"); TEST (T, -nan, showpos, 0, 4, ' ', "", "-nan"); TEST (T, -nan, uppercase, 0, 4, ' ', "", "-NAN"); TEST (T, -nan, showpos | uppercase, 0, 4, ' ', "", "-NAN"); TEST (T, nan, 0, 0, 5, ' ', "", " nan"); TEST (T, nan, showpos, 0, 5, ' ', "", " +nan"); TEST (T, nan, uppercase, 0, 5, ' ', "", " NAN"); TEST (T, nan, showpos | uppercase, 0, 5, ' ', "", " +NAN"); TEST (T, -nan, 0, 0, 5, ' ', "", " -nan"); TEST (T, -nan, showpos, 0, 5, ' ', "", " -nan"); TEST (T, -nan, uppercase, 0, 5, ' ', "", " -NAN"); TEST (T, -nan, showpos | uppercase, 0, 5, ' ', "", " -NAN"); TEST (T, nan, 0, 0, 8, ' ', "", " nan"); TEST (T, nan, showpos, 0, 8, ' ', "", " +nan"); TEST (T, nan, uppercase, 0, 8, ' ', "", " NAN"); TEST (T, nan, showpos | uppercase, 0, 8, ' ', "", " +NAN"); TEST (T, -nan, 0, 0, 8, ' ', "", " -nan"); TEST (T, -nan, showpos, 0, 8, ' ', "", " -nan"); TEST (T, -nan, uppercase, 0, 8, ' ', "", " -NAN"); TEST (T, -nan, showpos | uppercase, 0, 8, ' ', "", " -NAN"); TEST (T, nan, left, 0, 9, ' ', "", "nan "); TEST (T, nan, left | showpos, 0, 9, ' ', "", "+nan "); TEST (T, nan, left | uppercase, 0, 9, ' ', "", "NAN "); TEST (T, nan, left | showpos | uppercase, 0, 9, ' ', "", "+NAN "); TEST (T, -nan, left, 0, 9, ' ', "", "-nan "); TEST (T, -nan, left | showpos, 0, 9, ' ', "", "-nan "); TEST (T, -nan, left | uppercase, 0, 9, ' ', "", "-NAN "); TEST (T, -nan, left | showpos | uppercase, 0, 9, ' ', "", "-NAN "); TEST (T, nan, right, 0, 9, ' ', "", " nan"); TEST (T, nan, right | showpos, 0, 9, ' ', "", " +nan"); TEST (T, nan, right | uppercase, 0, 9, ' ', "", " NAN"); TEST (T, nan, right | showpos | uppercase, 0, 9, ' ', "", " +NAN"); TEST (T, -nan, right, 0, 9, ' ', "", " -nan"); TEST (T, -nan, right | showpos, 0, 9, ' ', "", " -nan"); TEST (T, -nan, right | uppercase, 0, 9, ' ', "", " -NAN"); TEST (T, -nan, right | showpos | uppercase, 0, 9, ' ', "", " -NAN"); #else rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s) formatting " "NaN's disabled due to platform bugs", cname, tname); #endif // 0/1 } /**************************************************************************/ template <class charT> void dbl_test (charT, const char *cname) { const char* const tname = "double"; rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s)", cname, tname); Punct<charT>::decimal_point_ = '.'; TEST (T, 0.0, 0, 0, 0, ' ', "", "%.0g"); TEST (T, -0.0, 0, 0, 0, ' ', "", "%.0g"); TEST (T, 1.0, 0, 0, 0, ' ', "", "%.0g"); TEST (T, 1.0, 0, 0, 0, ' ', "", "1"); TEST (T, -1.0, 0, 0, 0, ' ', "", "%.0g"); TEST (T, -1.0, 0, 0, 0, ' ', "", "-1"); TEST (T, 1.1, 0, 0, 0, ' ', "", "%.0g"); TEST (T, 1.1, 0, 0, 0, ' ', "", "1"); TEST (T, -1.1, 0, 0, 0, ' ', "", "%.0g"); TEST (T, -1.1, 0, 0, 0, ' ', "", "-1"); // exercise formatting of very large numbers in a fixed notation // using '+' as the fill character to disable num_get tests TEST (T, 1.0e+128, fixed, 0, 0, '+', "", "%.0f", Eof); TEST (T, 1.0e+256, fixed, 0, 0, '+', "", "%.0f", Eof); #undef CAT #undef CONCAT #define CAT(a, b) CONCAT (a, b) #define CONCAT(a, b) a ## b const double d = CAT (1.0e+, _RWSTD_DBL_MAX_10_EXP); TEST (T, d, fixed, 0, 0, '+', "", "%.0f", Eof); { char stdiofmt [8]; const std::streamsize prec = std::streamsize (DBL_DIG + 3); std::sprintf (stdiofmt, "%%.%dg", int (prec)); TEST (T, DBL_MIN, 0, prec, 0, ' ', "", stdiofmt); TEST (T, DBL_MAX, 0, prec, 0, ' ', "", stdiofmt); } if (1) { // verify that the global LC_NUMERIC setting has no impact on the facet for (const char *name = rw_locales (LC_NUMERIC, 0); name && *name; name += std::strlen (name) + 1) { // find the first locale whose decimal_point character // is different than in the classic C locale (i.e., than '.') if (0 == std::setlocale (LC_NUMERIC, name)) continue; const std::lconv* const conv = std::localeconv (); if (!conv) continue; if (conv->decimal_point && '.' != *conv->decimal_point) break; } Punct<charT>::decimal_point_ = '*'; Punct<charT>::thousands_sep_ = '/'; TEST (T, 12345.678900, fixed, 6, 0, ' ', "\000", "12345*678900"); TEST (T, 123456.78900, fixed, 5, 0, ' ', "\002", "12/34/56*78900"); TEST (T, 1234567.8900, fixed, 4, 0, ' ', "\003", "1/234/567*8900"); Punct<charT>::decimal_point_ = '.'; TEST (T, 12345678.900, fixed, 3, 0, ' ', "\004", "1234/5678.900"); // reset the global locale std::setlocale (LC_NUMERIC, "C"); } inf_nan_test (charT (), double (), cname, tname); } /**************************************************************************/ template <class charT> void ldbl_test (charT, const char *cname) { #ifndef _RWSTD_NO_LONG_DOUBLE const char* const tname = "long double"; rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s) " "[sizeof (long double) = %u]", cname, tname, sizeof (long double)); typedef long double LDbl; Punct<charT>::decimal_point_ = '.'; TEST (T, 0.0L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, 1.0L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, 2.1L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, -3.2L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, -4.3L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, 1.0e+10L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, 2.0e+20L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, 4.0e+30L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, 1.0e-10L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, 2.0e-20L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, 4.0e-30L, 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, LDbl (CHAR_MAX), 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, LDbl (UCHAR_MAX), 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, LDbl (SCHAR_MAX), 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, LDbl (SHRT_MAX), 0, 0, 0, ' ', "", "%.0Lg"); TEST (T, LDbl (USHRT_MAX), 0, 0, 0, ' ', "", "%.0Lg"); // specify greater precision than the default 6 for large numbers TEST (T, LDbl (INT_MAX), 0, 32, 0, ' ', "", "%.32Lg"); TEST (T, LDbl (UINT_MAX), 0, 32, 0, ' ', "", "%.32Lg"); TEST (T, LDbl (LONG_MAX), 0, 32, 0, ' ', "", "%.32Lg"); TEST (T, LDbl (ULONG_MAX), 0, 32, 0, ' ', "", "%.32Lg"); TEST (T, LDbl (FLT_MIN), 0, 32, 0, ' ', "", "%.32Lg"); TEST (T, LDbl (FLT_MAX), 0, 32, 0, ' ', "", "%.32Lg"); TEST (T, LDbl (DBL_MIN), 0, 32, 0, ' ', "", "%.32Lg"); TEST (T, LDbl (DBL_MAX), 0, 32, 0, ' ', "", "%.32Lg"); { char stdiofmt [8]; const std::streamsize prec = std::streamsize (LDBL_DIG + 3); std::sprintf (stdiofmt, "%%.%d" _RWSTD_LDBL_PRINTF_PREFIX "g", int (prec)); TEST (T, LDbl (LDBL_MIN), 0, prec, 0, ' ', "", stdiofmt); TEST (T, LDbl (LDBL_MAX), 0, prec, 0, ' ', "", stdiofmt); } const long double Pi = 3.14159265358979323846L; // some test cases below that use precision in conjuction with // scientific in the libc format specifier in order to exercise // the proposed resolution of lwg issue 231 TEST (T, Pi, 0, 32, 0, ' ', "", "%.32Lg"); TEST (T, Pi, fixed, 0, 0, ' ', "", "%.0Lf", Eof, 3.0L); TEST (T, Pi, scientific, 0, 0, ' ', "", "%.0Le", Eof, 3.0L); TEST (T, Pi, fixed, 0, 0, ' ', "", "3", Eof, 3.0L); TEST (T, Pi, scientific, 0, 0, ' ', "", "3e+00", Eof, 3.0L); TEST (T, Pi, uppercase, 32, 0, ' ', "", "%.32LG"); TEST (T, Pi, uppercase | fixed, 0, 0, ' ', "", "%.0Lf", Eof, 3.0L); TEST (T, Pi, uppercase | scientific, 0, 0, ' ', "", "%.0LE", Eof, 3.0L); TEST (T, Pi, uppercase | scientific, 0, 0, ' ', "", "3E+00", Eof, 3.0L); #define Showpos(f) (showpos | f) TEST (T, Pi, Showpos (0), 32, 0, ' ', "", "%+.32Lg"); TEST (T, Pi, Showpos (fixed), 0, 0, ' ', "", "%+.0Lf", Eof, 3.0L); TEST (T, Pi, Showpos (scientific), 0, 0, ' ', "", "%+.0Le", Eof, 3.0L); TEST (T, Pi, Showpos (fixed), 0, 0, ' ', "", "+3", Eof, 3.0L); TEST (T, Pi, Showpos (scientific), 0, 0, ' ', "", "+3e+00", Eof, 3.0L); #define SHOWPOS(f) (showpos | uppercase | f) TEST (T, Pi, SHOWPOS (0), 32, 0, ' ', "", "%+.32LG"); TEST (T, Pi, SHOWPOS (fixed), 0, 0, ' ', "", "%+.0Lf", Eof, 3.0L); TEST (T, Pi, SHOWPOS (scientific), 0, 0, ' ', "", "%+.0LE", Eof, 3.0L); TEST (T, Pi, SHOWPOS (fixed), 0, 0, ' ', "", "+3", Eof, 3.0L); TEST (T, Pi, SHOWPOS (scientific), 0, 0, ' ', "", "+3E+00", Eof, 3.0L); #define Showpoint(f) (showpoint | f) TEST (T, Pi, Showpoint (0), 32, 0, ' ', "", "%#.32Lg"); TEST (T, Pi, Showpoint (fixed), 0, 0, ' ', "", "%#.0Lf", Eof, 3.0L); TEST (T, Pi, Showpoint (scientific), 0, 0, ' ', "", "%#.0Le", Eof, 3.0L); TEST (T, Pi, Showpoint (fixed), 0, 0, ' ', "", "3.", Eof, 3.0L); TEST (T, Pi, Showpoint (scientific), 0, 0, ' ', "", "3.e+00", Eof, 3.0L); #define SHOWPOINT(f) (showpoint | uppercase | f) TEST (T, Pi, SHOWPOINT (0), 32, 0, ' ', "", "%#.32LG"); TEST (T, Pi, SHOWPOINT (fixed), 0, 0, ' ', "", "%#.0Lf", Eof, 3.0L); TEST (T, Pi, SHOWPOINT (scientific), 0, 0, ' ', "", "%#.0LE", Eof, 3.0L); TEST (T, Pi, SHOWPOINT (scientific), 0, 0, ' ', "", "3.E+00", Eof, 3.0L); #define Showall(f) (showpoint | showpos | f) TEST (T, Pi, Showall (0), 32, 0, ' ', "", "%#+.32Lg"); TEST (T, Pi, Showall (fixed), 0, 0, ' ', "", "%#+.0Lf", Eof, 3.0L); TEST (T, Pi, Showall (scientific), 0, 0, ' ', "", "%#+.0Le", Eof, 3.0L); TEST (T, Pi, Showall (fixed), 0, 0, ' ', "", "+3.", Eof, 3.0L); TEST (T, Pi, Showall (scientific), 0, 0, ' ', "", "+3.e+00", Eof, 3.0L); #define SHOWALL(f) (showpoint | showpos | uppercase | f) TEST (T, Pi, SHOWALL (0), 32, 0, ' ', "", "%#+.32LG"); TEST (T, Pi, SHOWALL (fixed), 0, 0, ' ', "", "%#+.0Lf", Eof, 3.0L); TEST (T, Pi, SHOWALL (scientific), 0, 0, ' ', "", "%#+.0LE", Eof, 3.0L); TEST (T, Pi, SHOWALL (scientific), 0, 0, ' ', "", "+3.E+00", Eof, 3.0L); // with {g,G}, precision indicates the number of significant digits // the precision == 0 should have the same effect as precision == 1 TEST (T, Pi, 0, 0, 0, ' ', "", "%.0Lg", Eof, 3.0L); TEST (T, Pi, 0, 1, 0, ' ', "", "%.1Lg", Eof, 3.0L); TEST (T, Pi, 0, 2, 0, ' ', "", "%.2Lg", Eof, 3.1L); TEST (T, Pi, 0, 3, 0, ' ', "", "%.3Lg", Eof, 3.14L); TEST (T, Pi, 0, 10, 0, ' ', "", "%.10Lg", Eof, 3.141592654L); // C89 and C99 both specify that (only if specified using the asterisk) // negative precision is treated the same as no precision at all; verify // that num_put handles negative precision gracefully (i.e., ignores it) TEST (T, Pi, 0, -1, 0, ' ', "", "%Lg"); TEST (T, Pi, 0, -9, 0, ' ', "", "%Lg"); // with {e,E,f,F}, precision indicates the number of fractional digits TEST (T, Pi, fixed, 1, 0, ' ', "", "%.1Lf", Eof, 3.1L); TEST (T, Pi, fixed, 2, 0, ' ', "", "%.2Lf", Eof, 3.14L); TEST (T, Pi, fixed, 3, 0, ' ', "", "%.3Lf", Eof, 3.142L); TEST (T, Pi, fixed, 10, 0, ' ', "", "%.10Lf", Eof, 3.1415926536L); // exercise formatting of very large numbers in a fixed notation // using '-' as the fill character to disable num_get tests TEST (T, 2.0e+128L, fixed, 0, 0, '-', "", "%.0Lf", Eof); TEST (T, 3.0e+256L, fixed, 0, 0, '-', "", "%.0Lf", Eof); TEST (T, 4.0e+300L, fixed, 0, 0, '-', "", "%.0Lf", Eof); // extension: fixed format and negative precision TEST (T, Pi, fixed, -2, 0, ' ', "", "0.03"); TEST (T, Pi, fixed, -8, 0, ' ', "", "0.00000003"); #undef CAT #undef CONCAT #define CAT(a, b) CONCAT (a, b) #define CONCAT(a, b) a ## b const long double ld = CAT (CAT (1.0e+, _RWSTD_LDBL_MAX_10_EXP), L); TEST (T, ld, fixed, 0, 0, '-', "", "%.0Lf", Eof); TEST (T, Pi, scientific, 2, 0, ' ', "", "%.2Le", Eof, 3.14L); TEST (T, Pi, scientific, 4, 0, ' ', "", "%.4Le", Eof, 3.1416L); TEST (T, Pi, scientific, 6, 0, ' ', "", "%.6Le", Eof, 3.141593L); TEST (T, Pi, scientific, 12, 0, ' ', "", "%.12Le", Eof, 3.14159265359L); TEST (T, Pi, scientific, -3, 0, ' ', "", "%Le"); TEST (T, Pi, scientific, -7, 0, ' ', "", "%Le"); inf_nan_test (charT (), (long double)0, cname, tname); #endif // _RWSTD_NO_LONG_DOUBLE } /**************************************************************************/ template <class charT> void pvoid_test (charT, const char *cname) { const char* const tname = "const void*"; rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s)", cname, tname); typedef void* PVoid; int foo = 0; int bar = 0; // use "0" rather than "%p" for null pointers to avoid // having to deal with GNU libc's "(nil)" format TEST (T, PVoid ( 0), 0, 0, 0, ' ', "", "0"); TEST (T, PVoid ( 1), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( &foo), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( &bar), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( ~0L), 0, 0, 0, ' ', "", "%p"); // 22.2.2.2.2, p16 and lwg issue 282: grouping and thousands_sep // is only used in arithmetic types TEST (T, PVoid ( 0), 0, 0, 0, ' ', "\1", "0"); TEST (T, PVoid ( 1), 0, 0, 0, ' ', "\1", "%p"); TEST (T, PVoid ( &foo), 0, 0, 0, ' ', "\1\1", "%p"); TEST (T, PVoid ( &bar), 0, 0, 0, ' ', "\1\2", "%p"); TEST (T, PVoid ( ~0L), 0, 0, 0, ' ', "\1\3", "%p"); TEST (T, PVoid ( SHRT_MAX), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( SHRT_MIN), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid (USHRT_MAX), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( INT_MAX), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( INT_MIN), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( UINT_MAX), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( LONG_MAX), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid ( LONG_MIN), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid (ULONG_MAX), 0, 0, 0, ' ', "", "%p"); #ifdef _RWSTD_LLONG_MAX # if _RWSTD_LLONG_SIZE <= _RWSTD_PTR_SIZE TEST (T, PVoid (_RWSTD_LLONG_MAX), 0, 0, 0, ' ', "", "%p"); TEST (T, PVoid (_RWSTD_ULLONG_MAX), 0, 0, 0, ' ', "", "%p"); # endif // LLONG_MAX #endif // _RWSTD_LLONG_MAX } /**************************************************************************/ template <class charT> void errno_test (charT, const char *cname) { const char* const tname = "long"; rw_info (0, 0, 0, "std::num_put<%s>::put (..., %s) and errno", cname, tname); // verify that errno doesn't change after, or adversely affect // successful insertion; and that the insertion doesn't change // the value of errno errno = -1; TEST (T, 12345L, 0, 0, 0, ' ', "", "12345"); rw_assert (-1 == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", -1); errno = 0; TEST (T, 12346L, 0, 0, 0, ' ', "", "12346"); rw_assert (0 == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", -0); errno = 1; TEST (T, 12347L, 0, 0, 0, ' ', "", "12347"); rw_assert (1 == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", 1); errno = 2; TEST (T, 12348L, 0, 0, 0, ' ', "", "12348"); rw_assert (2 == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", 2); errno = 3; TEST (T, 12349L, 0, 0, 0, ' ', "", "12349"); rw_assert (3 == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", 3); errno = 4; TEST (T, 12350L, 0, 0, 0, ' ', "", "12350"); rw_assert (4 == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", 4); errno = ERANGE; TEST (T, 12351L, 0, 0, 0, ' ', "", "12351"); rw_assert (ERANGE == errno, 0, __LINE__, "errno unexpectedly changed from %{#m} to %{#m} (%m)", ERANGE); errno = Bad; TEST (T, 12352L, 0, 0, 0, ' ', "", "12352"); rw_assert (Bad == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", Bad); errno = Eof; TEST (T, 12353L, 0, 0, 0, ' ', "", "12353"); rw_assert (Eof == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", Eof); errno = Fail; TEST (T, 12354L, 0, 0, 0, ' ', "", "12354"); rw_assert (Fail == errno, 0, __LINE__, "errno unexpectedly changed from %d to %{#m} (%m)", Fail); errno = 0; } /**************************************************************************/ // verify that std::ctype<>::widen() is called at least once // for every distinct narow character (not for fill characters) // note that an implementation is allowed to cache the results // of facet virtual functions() called with the same arguments // (including the implicit this pointer), so the numbers here // are minimum required values but not exact or maximums void widen_test () { rw_info (0, 0, 0, "std::num_put<char>::put (..., long) calls ctype<char>::widen()"); static const struct { long val; std::streamsize width; int flags; int n_widen; const char *str; } data[] = { { 0, 0, 0, 1, "9" }, { 1, 0, 0, 1, "8" }, { 11, 0, 0, 1, "88" }, { 12, 0, 0, 2, "87" }, { 123, 0, 0, 3, "876" }, { 111, 0, 0, 1, "888" }, { -1234, 0, 0, 5, "-8765" }, { 12121, 0, 0, 2, "87878" }, { 12345, 0, showpos, 6, "+87654" }, { 0123456, 0, oct | showbase, 7, "9876543" }, { 0x234567, 0, hex | showbase, 8, "9x765432" }, { 0x2345678, 10, hex | showbase, 9, " 9x7654321" }, { 9, 5, showpos | internal, 2, "+ 0" } }; for (unsigned i = 0; i != sizeof data / sizeof *data; ++i) { const Ctype<char> ctp; // construct and initialize a basic_ios-derived object Ios<char> ios; // construct a num_put-derived facet to exercise const NumPut<char> np; // imbue a stream object with a custom locale // containing the replacement ctype facet ios.imbue (std::locale (ios.getloc (), (const std::ctype<char>*)&ctp)); ios.flags (std::ios_base::fmtflags (data [i].flags)); ios.width (data [i].width); char buf [40]; // reset function call counter Ctype<char>::n_widen_ = 0; *np.put (buf, ios, ' ', data [i].val) = '\0'; rw_assert (data [i].n_widen <= Ctype<char>::n_widen_, 0, __LINE__, "%d. num_put<char>::do_put (..., %d) called " "ctype<char>::do_widen() %d times, %d expected; " "flags = %{If}, width = %d", i, data [i].val, Ctype<char>::n_widen_, data [i].n_widen, data [i].flags, data [i].width); rw_assert (0 == rw_strncmp (buf, data [i].str), 0, __LINE__, "%d. num_put<char>::do_put (..., %d) produced %s, " "expected \"%{#*s}\"; " "flags = %{If}, width = %d", i, data [i].val, buf, int (sizeof data [i].str [0]), data [i].str, data [i].flags, data [i].width); } } /**************************************************************************/ // verify that std::numpunct<>::grouping() is called and used correctly void grouping_test () { // construct a "replacement" numpunct-derived facet const Punct<char> pun (1); // construct and initialize a basic_ios-derived object Ios<char> ios; // construct a num_put-derived facet to exercise const NumPut<char> np; // imbue a stream object with a custom locale // containing the replacement punctuation facet ios.imbue (std::locale (ios.getloc (), (const std::numpunct<char>*)&pun)); rw_assert (1 == Punct<char>::n_objs_, 0, __LINE__, "%d facets exist, 1 expected", Punct<char>::n_objs_); // decimal output, no special formatting ios.setf (std::ios::fmtflags ()); char buf [40]; // group after every digit Punct<char>::grouping_ = "\1"; // reset the do_thousands_sep()-call counter Punct<char>::n_thousands_sep_ = 0; *np.put (buf, ios, '\0', 123456789L) = '\0'; // verify that the number was formatted correctly rw_assert (0 == std::strcmp (buf, "1,2,3,4,5,6,7,8,9"), 0, __LINE__, "num_put<char>::do_put (..., 123456789) produced \"%s\", " "expected \"%s\"", buf, "1,2,3,4,5,6,7,8,9"); // verify that do_thousands_sep() was called at least once rw_assert (0 < Punct<char>::n_thousands_sep_, 0, __LINE__, "num_put<char>::do_put (..., 123456789) failed to call " "numpunct<char>::do_thousands_sep()"); // repeat test to verify that distinct instances // of the same facet do not cache each other's data { // nested scope works around a SunPro bug (PR #27543) ios.imbue (std::locale (ios.getloc (), (const std::numpunct<char>*)new Punct<char>(0))); } rw_assert (2 == Punct<char>::n_objs_, 0, __LINE__, "%d facets exist, 2 expected", Punct<char>::n_objs_); // now group after every other digit Punct<char>::grouping_ = "\2"; // reset the do_thousands_sep()-call counter Punct<char>::n_thousands_sep_ = 0; *np.put (buf, ios, '\0', 123456790L) = '\0'; // again verify that the number was formatted correctly rw_assert (0 == std::strcmp (buf, "1,23,45,67,90"), 0, __LINE__, "num_put<char>::do_put (..., 123456790) produced \"%s\", " "expected \"%s\"", buf, "1,23,45,67,90"); // verify that do_thousands_sep() was called at least once // (i.e., that there is no unwarranted caching going on) rw_assert (0 < Punct<char>::n_thousands_sep_, 0, __LINE__, "num_put<char>::do_put (..., 123456790) failed to call " "numpunct<char>::do_thousands_sep()"); // replace imbued locale with a copy of the classic locale // and remove the previously installed locale containing // the user-defined facet; this must destroy the dynamically // created facet leaving only the local facet on the stack { // nested scope works around a SunPro bug (PR #27543) ios.imbue (std::locale::classic ()); } rw_assert (1 == Punct<char>::n_objs_, 0, __LINE__, "%d facets exist, 1 expected", Punct<char>::n_objs_); } /**************************************************************************/ template <class charT> void numput_virtuals_test (charT, const char *cname) { const NumPut<charT> put (1); const std::num_put<charT, charT*> &np = put; Ios<charT> ios; ios.flags (std::ios_base::fmtflags ()); #define Abs(i) ((i) < 0 ? (-i) : (i)) #define ASSERT(T, N, T2, tname, t2name) \ do { \ /* number of expected calls to the do_put() member */ \ const int expect = N + put.ncalls_ [put.test_ ## T]; \ const int expect_2 = !N + put.ncalls_ [put.test_ ## T2]; \ charT buf [80]; \ const charT* const end = np.put (buf, ios, charT (), (T)0); \ rw_assert (end == buf + 1, 0, __LINE__, \ "line %d: num_put<%s>::put (..., %s = 0) " \ "return value", __LINE__, cname, tname); \ const int ncalls = put.ncalls_ [put.test_ ## T]; \ const int ncalls_2 = put.ncalls_ [put.test_ ## T2]; \ rw_assert (expect == ncalls, 0, __LINE__, \ "line %d: num_put<%s>::put (..., %s) called " \ "do_put(..., %s) %d times, expected %d", \ __LINE__, cname, tname, \ tname, Abs (ncalls - expect - N), N); \ /* make sure extensions, if any, are implemented in */ \ /* terms of and call the standard virtual functions */ \ /* bogus addressof operator prevents warnings about */ \ /* unreachable code when T is the same as T2 */ \ if (put.test_ ## T != put.test_ ## T2) \ rw_assert (expect_2 == ncalls_2, 0, __LINE__, \ "line %d: num_put<%s>::put (..., %s) called " \ "do_put(..., %s) %d times, expected %d", \ __LINE__, cname, tname, \ t2name, Abs (expect_2 - ncalls_2 - !N), !N); \ } while (0) typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; // verify that each public member function calls each corresponding // implementation do_xxx() member functions exactly once // in the case of extensions, verify that each extended public member // function calls the appropriate implementation standard do_xxx() // member function #ifndef _RWSTD_NO_BOOL ASSERT (bool, 1, bool, "bool", "bool"); #endif // _RWSTD_NO_BOOL ASSERT (long, 1, long, "long", "long"); ASSERT (ulong, 1, ulong, "unsigned long", "unsigned long"); #if defined (_RWSTD_LONG_LONG) && !defined (_RWSTD_NO_EXT_NUM_PUT) typedef _RWSTD_LONG_LONG llong; typedef unsigned _RWSTD_LONG_LONG ullong; ASSERT (llong, 1, llong, "long long", "long long"); ASSERT (ullong, 1, ullong, "unsigned long long", "unsigned long long"); #endif // _RWSTD_LONG_LONG && !_RWSTD_NO_EXT_NUM_PUT ASSERT (double, 1, double, "double", "double"); #ifndef _RWSTD_NO_LONG_DOUBLE typedef long double ldouble; ASSERT (ldouble, 1, ldouble, "long double", "long double"); #endif // _RWSTD_NO_LONG_DOUBLE typedef const void* pvoid; ASSERT (pvoid, 1, pvoid, "const void*", "const void*"); } /**************************************************************************/ template <class charT> void run_tests (charT, const char *cname) { numput_virtuals_test (charT (), cname); direct_use_test (charT (), cname); #undef TEST #define TEST(T, tname) \ if (rw_enabled (#T)) \ T ## _test (charT (), cname); \ else \ rw_note (0, __FILE__, __LINE__, "%s test disabled", \ tname && *tname ? tname : #T) #ifndef _RWSTD_NO_BOOL TEST (bool, ""); #endif // _RWSTD_NO_BOOL // NOTE: there is no num_put::put(..., short) // TEST (shrt, "short"); // TEST (ushrt, "unsigned short"); // NOTE: there is no num_put::put(..., int) // TEST (int, ""); // TEST (uint, "unsigned int"); TEST (long, ""); TEST (ulong, "unsigned long"); #ifndef _RWSTD_NO_LONG_LONG TEST (llong, "long long"); TEST (ullong, "unsigned long long"); #endif // _RWSTD_NO_LONG_LONG // NOTE: there is no num_put::put(..., float) // TEST (flt, "float"); TEST (dbl, "dbouble"); #ifndef _RWSTD_NO_LONG_DOUBLE TEST (ldbl, "long double"); #endif // _RWSTD_NO_LONG_DOUBLE TEST (pvoid, "void*"); if (rw_opt_no_errno) rw_note (0, __FILE__, __LINE__, "errno test disabled"); else errno_test (charT (), cname); } /**************************************************************************/ static int run_test (int, char*[]) { if (rw_opt_no_widen) { rw_note (0, 0, 0, "widen test disabled"); } else { widen_test (); } if (rw_opt_no_grouping) { rw_note (0, 0, 0, "grouping test disabled"); } else { grouping_test (); } if (rw_enabled ("char")) run_tests (char (), "char"); else rw_note (0, __FILE__, __LINE__, "char test disabled"); #ifndef _RWSTD_NO_WCHAR_T if (rw_enabled ("wchar_t")) run_tests (wchar_t (), "wchar_t"); else rw_note (0, __FILE__, __LINE__, "wchar_t test disabled"); #endif // _RWSTD_NO_WCHAR_T return 0; } /**************************************************************************/ int main (int argc, char *argv[]) { return rw_test (argc, argv, __FILE__, "lib.locale.num.put", 0 /* no comment */, run_test, "|-enable-num_get# " "|-no-errno# " "|-no-grouping# " "|-no-widen# ", &rw_opt_enable_num_get, &rw_opt_no_errno, &rw_opt_no_grouping, &rw_opt_no_widen); }
39.915041
80
0.450775
[ "object" ]
fa77a7456f1ca8ce8171ad8ec2f6be182b7110c4
12,204
hpp
C++
include/ssci/bio/vioalt.hpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
include/ssci/bio/vioalt.hpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
include/ssci/bio/vioalt.hpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
/* * ::718604! * * Copyright(C) November 20, 2014 U.S. Food and Drug Administration * Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al * Affiliation: Food and Drug Administration (1), George Washington University (2) * * All rights Reserved. * * The MIT License (MIT) * * 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. */ #pragma once #ifndef sLib_vioalt_hpp #define sLib_vioalt_hpp #include <slib/core.hpp> #include <slib/std.hpp> #include <slib/utils.hpp> #include <ssci/bio/bioseqalign.hpp> #include <ssci/bio/bioal.hpp> #include <ssci/math/rand/rand.hpp> #include <regex.h> class sVioal : public sBioal { public: struct digestParams { idx flags, minFragmentLength, maxFragmentLength, countHiveAlPieces, seed; bool combineFiles; inline bool isKeepAll() { return (flags&sBioseqAlignment::fAlignIsPairedEndMode) || sBioseqAlignment::doSelectMatches(flags); } digestParams() { sSet(this,0); } }; private: sVioDB vioDB; enum eVioaltTypes { eTypeAlignment=1, eTypeMatch, eTypeSubject, eTypeQry, eTypeStat, eTypeRpt }; struct ALFact { int pos; short int iFile; int sub; int rpt; idx ofsFile; idx idQry; }; sVec < ALFact > AlFactors, * alFactors; idx DigestPairedEnds( sVec<ALFact> &als, sVec<sFil> & fileList, digestParams &params, sDic < sBioal::LenHistogram > * lenHistogram = 0, sVec< idx > * totSubjectCoverage = 0); inline bool filterPair(sVioal::ALFact * _i1, sVioal::ALFact * _i2, sBioseqAlignment::Al *_hdr1, sBioseqAlignment::Al *_hdr2, digestParams &params); public: /*! * This is the constructor function for the sVioalt class. * \param InputFilename The vioalt file used to initiate a vioDB object. * \param sub A sBioseq object containing the reference sequence. * \param qry A sBioseq object containing the query sequence. * \param mode An optional tag specifying the mode that the sVioalt container should be opened in, values allowed: * <i>fReadonly </i>(the default)<i>, ...</i> * \param biomode Needed to create the sVioDB wrapper; the file open flags such as <i>sMex::fSetZero|sMex::fBlockDoubling</i> */ sVioal (const char * InputFilename=0, sBioseq * sub=0, sBioseq * qry=0, idx mode=sMex::fReadonly, idx bioMode=0): sBioal() { myCallbackFunction=0; myCallbackParam=0; alFactors=&AlFactors; init(InputFilename, sub, qry, mode , bioMode); } virtual ~sVioal () { } /*! * Initiation function called from the constructor to set up an sVioalt wrapper by setting the vioDB, Sub, and Qry * attributes. * \param InputFilename The vioalt file used to initiate a vioDB object. * \param sub A sBioseq object containing the reference sequence. * \param qry A sBioseq object containing the query sequence. * \param mode An optional tag specifying the mode that the sVioalt container should be opened in, values allowed: * <i>fReadonly </i>(the default)<i>, ...</i> * \param biomode Needed to create the sVioDB wrapper; the file open flags such as <i>sMex::fSetZero|sMex::fBlockDoubling</i> * \returns sVioalt object. */ sVioal* init (const char * InputFilename=0, sBioseq * sub=0, sBioseq * qry=0, idx mode=sMex::fReadonly, idx bioMode=0) { if(InputFilename) vioDB.init(InputFilename,"vioalt",0,0,mode); Sub=sub; Qry=qry; if(!(mode&sMex::fReadonly)){ setMode(Qry->getmode(), Sub->getmode()); } return this; } typedef idx (*callbackType)(void * param, idx countDone, idx progressCur, idx percentMax); callbackType myCallbackFunction; void * myCallbackParam; /*! * Checks on the internal sVioDB object to see if it is valid. * \returns True/False */ virtual bool isok(void) { return vioDB.isok("vioalt")? true : false; } /*! * Returns the number of alignment records in the sVioalt object. * \returns idx of the number of records. */ virtual idx dimAl(void){ return vioDB.GetRecordCnt(eTypeAlignment); } /*! * Returns an alignment in the sVioalt object. * \param iAlIndex The Alignment index of interest. * \returns sBioseqAlignment::Al type alignment. */ virtual sBioseqAlignment::Al * getAl(idx iAlIndex){ return (sBioseqAlignment::Al * )vioDB.Getbody (eTypeAlignment, iAlIndex+1, 0); } virtual idx * getMatch (idx iAlIndex) { idx * pMatch=(idx*)vioDB.GetRelationPtr(eTypeAlignment, (idx)iAlIndex+1, 1, 0,0 ); return (idx*)vioDB.Getbody (eTypeMatch, *pMatch, 0); } virtual idx getRpt (idx iAlIndex) { idx * pMatch=(idx*)vioDB.GetRelationPtr(eTypeAlignment, (idx)iAlIndex+1, 2, 0,0 ); return pMatch?*(idx*)vioDB.Getbody (eTypeRpt, *pMatch, 0):0; } /*! * Returns the number of reference sequence records in the sVioalt object. * \returns idx type number of records. */ virtual idx dimSub(){ return vioDB.GetRecordCnt(eTypeSubject); } virtual idx listSubAlIndex(idx idSub, idx * relCount){ // ,sVec < idx > * alIndexes idx iRec=vioDB.GetRecordIndexByBody((const void *)&(idSub), eTypeSubject); idx * res=vioDB.GetRelationPtr(eTypeSubject, iRec, 1, (idx*)relCount,0 ); /* if(relCount && *relCount && alIndexes ) { idx * cpy=alIndexes->add(*relCount); memcpy(cpy,res,sizeof(idx)*(*relCount)); return cpy; } */ return res ? *res : 0 ; } /*! * Returns the number of query sequence records in the sVioalt object. * \returns idx type number of records. */ /* idx dimQry() { return vioDB.GetRecordCnt(eTypeQry); } idx * listQryAl(idx idQry, idx * relCount){ idx iRec=vioDB.GetRecordIndexByBody((const void *)&(idQry), eTypeQry); return (idx*)vioDB.GetRelationPtr(eTypeQry, iRec, 1, (idx*)relCount,0 ); } */ virtual idx dimStat() { return vioDB.GetRecordCnt(eTypeStat); } virtual Stat * getStat(idx iStat=0, idx iSub=0, idx * size=0) { Stat * pI=(Stat *)vioDB.Getbody (eTypeStat, iStat+1, size); if(size)*size/=sizeof(Stat); return pI+iSub; } static void setMode(sVioDB &db, sBioseq::EBioMode qrymode, sBioseq::EBioMode submode){ idx resmode = eBioModeShortBoth; if(qrymode==sBioseq::eBioModeLong && submode==sBioseq::eBioModeLong) resmode = eBioModeLongBoth; else if(qrymode==sBioseq::eBioModeLong && submode==sBioseq::eBioModeShort) resmode = eBioModeLongQry; else if(qrymode==sBioseq::eBioModeShort && submode==sBioseq::eBioModeLong) resmode = eBioModeLongSub; char userspace = *(db.userSpace8()); userspace &= ~(0x3); userspace |= (char)resmode; *(db.userSpace8()) = userspace; } virtual void setMode(sBioseq::EBioMode qrymode,sBioseq:: EBioMode submode){ sVioal::setMode(vioDB, qrymode, submode); } virtual sBioseq::EBioMode getSubMode(void) { char userspace = *(vioDB.userSpace8()); userspace &= 0x03; return ((userspace == eBioModeLongBoth) || (userspace == eBioModeLongSub)) ? sBioseq::eBioModeLong : sBioseq::eBioModeShort; } virtual sBioseq::EBioMode getQryMode(void) { char userspace = *(vioDB.userSpace8()); userspace &= 0x03; return ((userspace ==eBioModeLongBoth) || (userspace == eBioModeLongQry)) ? sBioseq::eBioModeLong : sBioseq::eBioModeShort; } virtual bool isPairedEnd(void) { idx size; getStat(0,0,&size); return size == 2*Sub->dim()+1; } /* idx dimFailed( idx isdetail=0) { if(!isdetail){ idx * pCount=(idx*)vioDB.Getbody (eTypeFailed, 1, 0); return (pCount) ? *pCount : 0 ; } return vioDB.GetRecordCnt(eTypeFailed); } */ /* idx * listFailed(idx iFailedIndex) { return (idx*)vioDB.Getbody (eTypeFailed, iFailedIndex+1, 0); } */ //typedef idx (callbackType)(void * data, real percentDone); static idx DigestInit(sVioDB * db , const char * outputfilename); static idx DigestFirstStage(sVioDB * db, sBioseqAlignment::Al * hdr, sBioseqAlignment::Al * hdre, sBioseq * qry, sBioal::Stat * stat, bool selectedOnly , bool doQueries, idx biomode, idx oneRepeatForall=0); static idx DigestFragmentStage(ALFact * hdr, ALFact * hdre, sBioal::Stat * stat, sBioseq * qry, idx biomode, idx oneRepeatForall=0); static idx DigestSecondStage(sVioDB * db, sBioseq * qry, idx * pAl, sBioseqAlignment::Al * hdr,sBioseqAlignment::Al * hdre , bool selectedOnly , bool doQueries, idx oneRepeatForall=0); idx Digest(const char* outputfilename, bool combineFile, sBioseqAlignment::Al * rawAlignment, idx size , Stat * statFailed, bool selectedOnly=false , bool doQueries=false, idx biomode=0); idx concatAlignmentFiles( const char * dstfile, const char * filenames , bool ifGlueTheFile=false, bool removeOriginals=false, callbackType * func = 0 ){ return vioDB.concatFiles( dstfile, filenames ,"vioalt", ifGlueTheFile,removeOriginals); } public: void SortOnSubject(){ ParamsAlignmentSorter Param; Param.flags=alSortByPosStart; Param.bioal=this; vioDB.viodDBSorter( eTypeSubject, 1, BioseqAlignmentComparator , &Param ); } void SortAll(idx * ind,ParamsAlignmentSorter &param){ vioDB.viodDBSorter( eTypeAlignment, ind, BioseqAlignmentComparator, &param ); } static idx __sort_totalAlignmentSorter_onSubject(void * param, void * arr , idx i1, idx i2); static idx __sort_totalAlignmentSorter_onQuery(void * param, void * arr , idx i1, idx i2); static idx __sort_totalAlignmentSorter_onPosition(void * param, void * arr , idx i1, idx i2); idx DigestCombineAlignmentsRaw(const char* outputfilename, const char * filenames00, digestParams &params, sDic < sBioal::LenHistogram > * lenHistogram=0, sVec < idx > * totSubjectCoverage=0, idx sortFlags = 0 ) ; }; #endif
40.95302
221
0.611275
[ "object" ]
fa858726b6f856ee899c674c19a5016a7a9bd42d
5,092
cpp
C++
Game/Source/Player.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
Game/Source/Player.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
Game/Source/Player.cpp
Paideieitor/PlatformerGame
e00602171807c694b0c5f4afac50157ce9cd23b1
[ "MIT" ]
null
null
null
#include "EntityManager.h" #include "Animation.h" #include "Audio.h" #include "Collisions.h" #include "DungeonScene.h" #include "Input.h" #include "Player.h" #define MAX_JUMPS 1 Player::Player(fPoint position, bool flip) : Entity(EntityType::PLAYER, position, flip, nullptr) { wall = WallCollision::NONE; grounded = false; jumps = 0; velocity = { 0,0 }; timeOnAir = 0; shurikenColdown = 0.5f; shurikenTimer = 0.0f; size.x = 16; size.y = 16; texture = app->tex->Load("Assets/textures/ninja.png"); idle = new Animation(2, true, 0.25f); idle->PushBack(0, 0, 16, 16); idle->PushBack(16, 0, 16, 16); run = new Animation(4, true, 0.1f); run->PushBack(16, 16, 16, 16); run->PushBack(0, 16, 16, 16); run->PushBack(32, 16, 16, 16); run->PushBack(0, 16, 16, 16); jump = new Animation(1, false); jump->PushBack(48, 16, 16, 16); currentAnimation = idle; feet = app->collisions->CreateCollider(ColliderType::PLAYER, { (int)position.x,(int)position.y,1,13 }, true, this); body = app->collisions->CreateCollider(ColliderType::PLAYER, { (int)position.x,(int)position.y,16,13 }, true, this); } Player::~Player() { for(uint i = 0; i < shurikens.size(); i++) shurikens[i]->toDelete = true; app->tex->UnLoad(texture); delete idle; delete run; delete jump; app->collisions->DeleteCollider(body); app->collisions->DeleteCollider(feet); } bool Player::Update(float dt) { currentAnimation = idle; if(shurikenTimer != 0.0f) { shurikenTimer += dt; if(shurikenTimer >= shurikenColdown) shurikenTimer = 0.0f; } if(shurikenTimer == 0.0f && app->input->GetKey(SDL_SCANCODE_LSHIFT) == KEY_DOWN) { shurikens.push_back(app->entitymanager->CreateEntity(EntityType::SHURIKEN, position, flip, this)); shurikenTimer += dt; } velocity.x = 0; if(wall != WallCollision::RIGHT && app->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) { velocity.x = -dt * 100; currentAnimation = run; flip = true; } if(wall != WallCollision::LEFT && app->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) { velocity.x = dt * 100; currentAnimation = run; flip = false; } wall = WallCollision::NONE; if(app->godMode) { velocity.y = 0; if(app->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) velocity.y = -dt * 100; if(app->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) velocity.y = dt * 100; } else { bool onGround = grounded; grounded = false; if(onGround) { if (velocity.y >= 0) { velocity.y = 0; timeOnAir = 0; } jumps = 0; } else { velocity.y += timeOnAir * dt; timeOnAir += 5000.0f * dt; currentAnimation = jump; } if(jumps < MAX_JUMPS && app->input->GetKey(SDL_SCANCODE_W) == KEY_DOWN) { velocity.y = -200; jumps++; timeOnAir = 0; app->audio->PlayFx(app->dungeonscene->jumpSound); position.y -= 3.0f; } } fPoint dPosition = GetDrawPosition(size); app->render->SetTextureEvent(5, texture, dPosition, currentAnimation->GetFrame(dt), flip); iPoint cameraOnPlayer = { (int)position.x - app->render->resolution.x / 2 , (int)position.y - app->render->resolution.y / 2 }; if (cameraOnPlayer.y < 0) cameraOnPlayer.y = 0; app->render->camera.x = -cameraOnPlayer.x; app->render->camera.y = -cameraOnPlayer.y; position.x += velocity.x; if(!app->godMode) position.y += velocity.y * dt; else position.y += velocity.y; dPosition = GetDrawPosition(size); body->SetPosition((int)dPosition.x, (int)dPosition.y + 3); feet->SetPosition((int)dPosition.x + 8, (int)dPosition.y + 3); return true; } bool WalkableCollider(ColliderType type) { if (type == ColliderType::GROUND || type == ColliderType::STATIC_SHURIKEN) return true; return false; } bool DangerousCollider(ColliderType type) { if(type == ColliderType::ATTACK || type == ColliderType::ENEMY) return true; return false; } void Player::Collision(Collider* c1, Collider* c2) { if(c1 == body && WalkableCollider(c2->type)) { if (feet->rect.y + feet->rect.h * 0.8 < c2->rect.y) //for the body to collide with a ground collider it must a certain height { //respect to the feet to avoid colliding with the floor as a wall } else if(c2->rect.x > body->rect.x) { wall = WallCollision::LEFT; } else if(c2->rect.x < body->rect.x) { wall = WallCollision::RIGHT; } return; } if(c1 == feet && WalkableCollider(c2->type)) { if(feet->rect.y < c2->rect.y /*head over the ground*/ || (feet->rect.y > c2->rect.y && feet->rect.y + feet->rect.h < c2->rect.y + c2->rect.h)/*body inside a collider*/) { grounded = true; position.y = c2->rect.y - feet->rect.h / 2; return; } else if(feet->rect.y + feet->rect.h > c2->rect.y + c2->rect.h /*head under the entire collider, hitting the celing*/) { position.y = c2->rect.y + c2->rect.h + size.y / 2; velocity.y = 0; } } if(c1 == body && c2->type == ColliderType::CHECKPOINT) { app->dungeonscene->iterate = true; } if(!app->godMode && c1 == body && DangerousCollider(c2->type)) { app->audio->PlayFx(app->dungeonscene->deathSound); app->dungeonscene->RespawnPlayer(); } }
24.247619
170
0.646504
[ "render" ]
fa953d8ca556e806449758371e4b2de74fc34d1d
4,969
cpp
C++
clang/ExtentCollection.cpp
djp952/tools-llvm
01503ab630354dc7196a8dfe15f4525bf9a0e1ec
[ "MIT" ]
1
2016-09-11T11:32:08.000Z
2016-09-11T11:32:08.000Z
clang/ExtentCollection.cpp
djp952/tools-llvm
01503ab630354dc7196a8dfe15f4525bf9a0e1ec
[ "MIT" ]
3
2016-06-04T03:55:58.000Z
2016-06-09T03:13:15.000Z
clang/ExtentCollection.cpp
djp952/tools-llvm
01503ab630354dc7196a8dfe15f4525bf9a0e1ec
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // Copyright (c) 2016 Michael G. Brehm // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //--------------------------------------------------------------------------- #include "stdafx.h" #include "ExtentCollection.h" #include "Extent.h" #include "ReadOnlyListEnumerator.h" #pragma warning(push, 4) // Enable maximum compiler warnings namespace zuki::tools::llvm::clang { //--------------------------------------------------------------------------- // ExtentCollection Constructor // // Arguments: // // extents - List<> containing the extents ExtentCollection::ExtentCollection(List<Extent^>^ extents) : m_extents(extents) { if(Object::ReferenceEquals(extents, nullptr)) throw gcnew ArgumentNullException("extents"); } //--------------------------------------------------------------------------- // ExtentCollection::default[int]::get // // Gets the element at the specified index in the read-only list Extent^ ExtentCollection::default::get(int index) { return m_extents[index]; } //--------------------------------------------------------------------------- // ExtentCollection::Count::get // // Gets the number of elements in the collection int ExtentCollection::Count::get(void) { return m_extents->Count; } //--------------------------------------------------------------------------- // ExtentCollection::Create (static, internal) // // Creates a new ExtentCollection instance // // Arguments: // // owner - Owning safe handle instance // transunit - TranslationUnitHandle instance // extents - Unmanaged CXSourceRangeList instance (rvalue reference) ExtentCollection^ ExtentCollection::Create(SafeHandle^ owner, TranslationUnitHandle^ transunit, CXSourceRangeList*&& extents) { // If the provided CXSourceRangeList is null, use the empty collection if(extents == __nullptr) return ExtentCollection::Empty; try { // Create a new List<> to hold all of the generated Extent instances List<Extent^>^ extentlist = gcnew List<Extent^>(extents->count); // Load the List<> with new Extent objects for each item provided in the CXSourceRangeList for(unsigned int index = 0; index < extents->count; index++) extentlist->Add(Extent::Create(owner, transunit, extents->ranges[index])); return gcnew ExtentCollection(extentlist); } // This function takes ownership of the CXSourceRangeList, always release it finally { clang_disposeSourceRangeList(extents); extents = __nullptr; } } //--------------------------------------------------------------------------- // ExtentCollection::Create (static, internal) // // Creates a new ExtentCollection instance // // Arguments: // // extents - Existing List<Extent^>^ instance ExtentCollection^ ExtentCollection::Create(List<Extent^>^ extents) { // This overload was added to support operations where a list of extents // has to be manually generated, just pass the existing List<> to the constructor return gcnew ExtentCollection(extents); } //--------------------------------------------------------------------------- // ExtentCollection::GetEnumerator // // Returns a generic IEnumerator<T> for the member collection // // Arguments: // // NONE IEnumerator<Extent^>^ ExtentCollection::GetEnumerator(void) { return gcnew ReadOnlyListEnumerator<Extent^>(this); } //--------------------------------------------------------------------------- // ExtentCollection::IEnumerable_GetEnumerator // // Returns a non-generic IEnumerator for the member collection // // Arguments: // // NONE System::Collections::IEnumerator^ ExtentCollection::IEnumerable_GetEnumerator(void) { return GetEnumerator(); } //--------------------------------------------------------------------------- } // zuki::tools::llvm::clang #pragma warning(pop)
34.506944
138
0.613604
[ "object" ]
fa9549eb5c887b811e405bc015c955f754fdd8c2
6,842
hpp
C++
src/clcontext.hpp
tigrazone/fluctus
7f5721d725f2787e5fb705107c83611200fc5ebb
[ "MIT" ]
null
null
null
src/clcontext.hpp
tigrazone/fluctus
7f5721d725f2787e5fb705107c83611200fc5ebb
[ "MIT" ]
null
null
null
src/clcontext.hpp
tigrazone/fluctus
7f5721d725f2787e5fb705107c83611200fc5ebb
[ "MIT" ]
3
2021-05-06T12:43:07.000Z
2021-05-27T15:32:18.000Z
#pragma once #ifdef _DEBUG #define CPU_DEBUGGING #endif #include "cl2.hpp" #include "geom.h" #include <clt.hpp> #include <string> typedef struct { float primary = 0.0f; float extension = 0.0f; float shadow = 0.0f; float samples = 0.0f; float total = 0.0f; } PerfNumbers; class EnvironmentMap; class BVH; class Scene; class PTWindow; class CLContext { friend class Tracer; public: CLContext(); ~CLContext() = default; void enqueueResetKernel(const RenderParams &params); void enqueueRayGenKernel(const RenderParams &params); void enqueueNextVertexKernel(const RenderParams &params); void enqueueBsdfSampleKernel(const RenderParams &params); void enqueueSplatKernel(const RenderParams &params); void enqueueSplatPreviewKernel(const RenderParams &params); void enqueuePostprocessKernel(const RenderParams &params); void enqueueWfResetKernel(const RenderParams &params); void enqueueWfRaygenKernel(const RenderParams &params); void enqueueWfExtRayKernel(const RenderParams &params); void enqueueWfShadowRayKernel(const RenderParams &params); void enqueueWfLogicKernel(const RenderParams &params, const bool firstIteration); void enqueueWfMaterialKernels(const RenderParams &params); // Done conservatively void recompileKernels(bool setArgs); void enqueueClearWfQueues(); void finishQueue(); void updatePixelIndex(cl_uint numPixels, cl_uint numNewPaths); void resetPixelIndex(); cl_uint getNumTasks() const; Hit pickSingle(float NDCx, float NDCy); void setup(PTWindow *window); void setupParams(); void setupPickResult(); void setupStats(); void resetStats(); void fetchStatsAsync(); void updateRenderPerf(float deltaT); const PerfNumbers getRenderPerf(); const RenderStats getStats(); void enqueueGetCounters(QueueCounters *cnt); void checkTracingPerf(); void updateParams(const RenderParams &params); void uploadSceneData(BVH *bvh, Scene *scene); void setupPixelStorage(PTWindow *window); void saveImage(std::string filename, const RenderParams &params); void createEnvMap(EnvironmentMap *map); private: void setupScene(); void verify(std::string msg, int pred = -1); void packTextures(Scene *scene); void enqueueWfDiffuseKernel(const RenderParams &params); void enqueueWfGlossyKernel(const RenderParams &params); void enqueueWfGGXReflKernel(const RenderParams &params); void enqueueWfGGXRefrKernel(const RenderParams &params); void enqueueWfDeltaKernel(const RenderParams &params); void enqueueWfEmissiveKernel(const RenderParams &params); void enqueueWfAllMaterialsKernel(const RenderParams &params); void setupKernels(); void setupResetKernel(); void setupRayGenKernel(); void setupNextVertexKernel(); void setupBsdfSampleKernel(); void setupSplatKernel(); void setupSplatPreviewKernel(); void setupPostprocessKernel(); void setupPickKernel(); void setupWfExtKernel(); void setupWfResetKernel(); void setupWfLogicKernel(); void setupWfShadowKernel(); void setupWfRaygenKernel(); void setupWfDiffuseKernel(); void setupWfGlossyKernel(); void setupWfGGXReflKernel(); void setupWfGGXRefrKernel(); void setupWfDeltaKernel(); void setupWfEmissiveKernel(); void setupWfAllMaterialsKernel(); void initMCBuffers(); void setKernelBuildSettings(); int err; // error code returned from api calls cl_uint NUM_TASKS = 0; // the amount of paths in flight simultaneously, limited by VRAM, defined in settings // For showing progress PTWindow *window; cl::Device device; cl::Platform platform; cl::Context context; cl::CommandQueue cmdQueue; // General kernels clt::Kernel* kernel_pick = nullptr; clt::Kernel* mk_postprocess = nullptr; // Luxrender-style microkernels clt::Kernel* mk_reset = nullptr; clt::Kernel* mk_raygen = nullptr; clt::Kernel* mk_next_vertex = nullptr; clt::Kernel* mk_sample_bsdf = nullptr; clt::Kernel* mk_splat = nullptr; clt::Kernel* mk_splat_preview = nullptr; // Aila-style wavefront kernels clt::Kernel* wf_reset = nullptr; clt::Kernel* wf_extension = nullptr; clt::Kernel* wf_raygen = nullptr; clt::Kernel* wf_logic = nullptr; clt::Kernel* wf_shadow = nullptr; clt::Kernel* wf_diffuse = nullptr; clt::Kernel* wf_glossy = nullptr; clt::Kernel* wf_ggx_refl = nullptr; clt::Kernel* wf_ggx_refr = nullptr; clt::Kernel* wf_delta = nullptr; clt::Kernel* wf_emissive = nullptr; clt::Kernel* wf_mat_all = nullptr; // Device memory shared with GL std::vector<cl::Memory> sharedMemory; // Performance statistics RenderStats statsAsync; // fetched asynchronously from device after each iteration PerfNumbers renderPerf; cl::Event extRayEvent; cl::Event shdwRayEvent; QueueCounters hostCounters = {}; // synced from queueCounters cl_uint pixelIdx = 0; public: // Device buffers need to be accessible to kernel implementations struct { // Microkernel buffers cl::Buffer tasksBuffer; cl::Buffer raygenQueue; // indices of paths to regenerate cl::Buffer extensionQueue; // indices of paths to extend cl::Buffer shadowQueue; // indices of shadow ray casts cl::Buffer diffuseMatQueue; cl::Buffer glossyMatQueue; cl::Buffer ggxReflMatQueue; cl::Buffer ggxRefrMatQueue; cl::Buffer deltaMatQueue; cl::Buffer emissiveMatQueue; cl::Buffer currentPixelIdx; // points to next pixel, since NUM_TASKS != #pixels cl::Buffer queueCounters; // atomic counters keeping track of queue lengths cl::Buffer samplesPerPixel; // Variables from BVH cl::Buffer triangleBuffer; cl::Buffer nodeBuffer; cl::Buffer indexBuffer; cl::Buffer materialBuffer; cl::Buffer texDescriptorBuffer; cl::Buffer texDataBuffer; // Environment map data cl::Image2D environmentMap; cl::Buffer probTable; cl::Buffer aliasTable; cl::Buffer pdfTable; // Statistics cl::Buffer renderStats; // ray + sample counts // Pixel storage cl::Buffer pixelBuffer; // raw (linear) pixel data, not used by OpenGL cl::Buffer denoiserAlbedoBuffer; cl::Buffer denoiserNormalBuffer; cl::BufferGL previewBuffer; // post-processed buffer, shown on screen cl::BufferGL denoiserAlbedoBufferGL; cl::BufferGL denoiserNormalBufferGL; // Single element buffers cl::Buffer pickResult; cl::Buffer renderParams; } deviceBuffers; };
31.675926
113
0.694241
[ "vector" ]
fa971bd4b45eb42cc78f5365cbcd5e81e622c9a0
5,880
cxx
C++
MITK/Plugins/uk.ac.ucl.cmic.igitrackedimage/src/internal/TrackedImageViewPreferencePage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Plugins/uk.ac.ucl.cmic.igitrackedimage/src/internal/TrackedImageViewPreferencePage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Plugins/uk.ac.ucl.cmic.igitrackedimage/src/internal/TrackedImageViewPreferencePage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "TrackedImageViewPreferencePage.h" #include "TrackedImageView.h" #include <QFormLayout> #include <QVBoxLayout> #include <QLabel> #include <QCheckBox> #include <QDoubleSpinBox> #include <QMessageBox> #include <QPushButton> #include <ctkPathLineEdit.h> #include <QCheckBox> #include <berryIPreferencesService.h> #include <berryPlatform.h> const QString TrackedImageViewPreferencePage::CALIBRATION_FILE_NAME("calibration file name"); const QString TrackedImageViewPreferencePage::SCALE_FILE_NAME("scale file name"); const QString TrackedImageViewPreferencePage::EMTOWORLDCALIBRATION_FILE_NAME("Em to optical calibration file name"); const QString TrackedImageViewPreferencePage::FLIP_X_SCALING("flip x scaling"); const QString TrackedImageViewPreferencePage::FLIP_Y_SCALING("flip y scaling"); const QString TrackedImageViewPreferencePage::CLONE_IMAGE("Clone image"); const QString TrackedImageViewPreferencePage::SHOW_2D_WINDOW("show 2D window"); //----------------------------------------------------------------------------- TrackedImageViewPreferencePage::TrackedImageViewPreferencePage() : m_MainControl(0) , m_CalibrationFileName(0) , m_ScaleFileName(0) , m_EmToWorldCalibrationFileName(0) , m_Initializing(false) , m_CloneImage(0) , m_Show2DWindow(0) , m_TrackedImageViewPreferencesNode(0) { } //----------------------------------------------------------------------------- TrackedImageViewPreferencePage::TrackedImageViewPreferencePage(const TrackedImageViewPreferencePage& other) : berry::Object(), QObject() { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } //----------------------------------------------------------------------------- TrackedImageViewPreferencePage::~TrackedImageViewPreferencePage() { } //----------------------------------------------------------------------------- void TrackedImageViewPreferencePage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void TrackedImageViewPreferencePage::CreateQtControl(QWidget* parent) { m_Initializing = true; berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); m_TrackedImageViewPreferencesNode = prefService->GetSystemPreferences()->Node(TrackedImageView::VIEW_ID); m_MainControl = new QWidget(parent); QFormLayout *formLayout = new QFormLayout; m_CalibrationFileName = new ctkPathLineEdit(); formLayout->addRow("calibration matrix file name", m_CalibrationFileName); m_ScaleFileName = new ctkPathLineEdit(); formLayout->addRow("scale matrix file name", m_ScaleFileName); m_EmToWorldCalibrationFileName = new ctkPathLineEdit(); formLayout->addRow("EM to optical calibration matrix file name", m_EmToWorldCalibrationFileName); m_FlipXScaling = new QCheckBox(); m_FlipXScaling->setChecked(false); formLayout->addRow("flip x scale factor", m_FlipXScaling); m_FlipYScaling = new QCheckBox(); m_FlipYScaling->setChecked(false); formLayout->addRow("flip y scale factor", m_FlipYScaling); m_CloneImage = new QCheckBox(); m_CloneImage->setChecked(false); formLayout->addRow("show clone image button", m_CloneImage); m_Show2DWindow = new QCheckBox(); m_Show2DWindow->setChecked(false); formLayout->addRow("show 2D window", m_Show2DWindow); m_MainControl->setLayout(formLayout); this->Update(); m_Initializing = false; } //----------------------------------------------------------------------------- QWidget* TrackedImageViewPreferencePage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- bool TrackedImageViewPreferencePage::PerformOk() { m_TrackedImageViewPreferencesNode->Put(CALIBRATION_FILE_NAME, m_CalibrationFileName->currentPath()); m_TrackedImageViewPreferencesNode->Put(SCALE_FILE_NAME, m_ScaleFileName->currentPath()); m_TrackedImageViewPreferencesNode->Put(EMTOWORLDCALIBRATION_FILE_NAME, m_EmToWorldCalibrationFileName->currentPath()); m_TrackedImageViewPreferencesNode->PutBool(FLIP_X_SCALING, m_FlipXScaling->isChecked()); m_TrackedImageViewPreferencesNode->PutBool(FLIP_Y_SCALING, m_FlipYScaling->isChecked()); m_TrackedImageViewPreferencesNode->PutBool(CLONE_IMAGE, m_CloneImage->isChecked()); m_TrackedImageViewPreferencesNode->PutBool(SHOW_2D_WINDOW, m_Show2DWindow->isChecked()); return true; } //----------------------------------------------------------------------------- void TrackedImageViewPreferencePage::PerformCancel() { } //----------------------------------------------------------------------------- void TrackedImageViewPreferencePage::Update() { m_CalibrationFileName->setCurrentPath(m_TrackedImageViewPreferencesNode->Get(CALIBRATION_FILE_NAME, "")); m_ScaleFileName->setCurrentPath(m_TrackedImageViewPreferencesNode->Get(SCALE_FILE_NAME, "")); m_EmToWorldCalibrationFileName->setCurrentPath(m_TrackedImageViewPreferencesNode->Get(EMTOWORLDCALIBRATION_FILE_NAME, "")); m_FlipXScaling->setChecked(m_TrackedImageViewPreferencesNode->GetBool(FLIP_X_SCALING, false)); m_FlipYScaling->setChecked(m_TrackedImageViewPreferencesNode->GetBool(FLIP_Y_SCALING, false)); m_CloneImage->setChecked(m_TrackedImageViewPreferencesNode->GetBool(CLONE_IMAGE, false)); m_Show2DWindow->setChecked(m_TrackedImageViewPreferencesNode->GetBool(SHOW_2D_WINDOW, false)); }
37.452229
125
0.690476
[ "object" ]
b702d4671b66eda4aa0dbb2c06382c10b49bc72a
20,851
cpp
C++
Source/Urho3D/EffekseerUrho3D/RendererUrho3D/EffekseerUrho3D.ModelRenderer.cpp
aimoonchen/rbfx
de4f1fd795f4f42009693a71b6f887a221aa19db
[ "MIT" ]
null
null
null
Source/Urho3D/EffekseerUrho3D/RendererUrho3D/EffekseerUrho3D.ModelRenderer.cpp
aimoonchen/rbfx
de4f1fd795f4f42009693a71b6f887a221aa19db
[ "MIT" ]
null
null
null
Source/Urho3D/EffekseerUrho3D/RendererUrho3D/EffekseerUrho3D.ModelRenderer.cpp
aimoonchen/rbfx
de4f1fd795f4f42009693a71b6f887a221aa19db
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------------- // Include //---------------------------------------------------------------------------------- #include "EffekseerUrho3D.RenderState.h" #include "EffekseerUrho3D.RendererImplemented.h" #include "EffekseerUrho3D.IndexBuffer.h" #include "EffekseerUrho3D.ModelRenderer.h" #include "EffekseerUrho3D.Shader.h" #include "EffekseerUrho3D.VertexBuffer.h" #include "../../Cocos2D/Urho3DContext.h" #include "../../Graphics/Graphics.h" namespace EffekseerUrho3D { namespace ModelShaders { namespace Unlit { #define DISTORTION 0 #define LIGHTING 0 namespace Lightweight { #define SOFT_PARTICLE 0 #include "Shaders/Model.inl" #undef SOFT_PARTICLE } namespace SoftParticle { #define SOFT_PARTICLE 1 #include "Shaders/Model.inl" #undef SOFT_PARTICLE } namespace CanvasItem { #include "Shaders/Model2D.inl" } #undef LIGHTING #undef DISTORTION } namespace Lighting { #define DISTORTION 0 #define LIGHTING 1 namespace Lightweight { #define SOFT_PARTICLE 0 #include "Shaders/Model.inl" #undef SOFT_PARTICLE } namespace SoftParticle { #define SOFT_PARTICLE 1 #include "Shaders/Model.inl" #undef SOFT_PARTICLE } namespace CanvasItem { #include "Shaders/Model2D.inl" } #undef LIGHTING #undef DISTORTION } namespace Distortion { #define DISTORTION 1 #define LIGHTING 0 namespace Lightweight { #define SOFT_PARTICLE 0 #include "Shaders/Model.inl" #undef SOFT_PARTICLE } namespace SoftParticle { #define SOFT_PARTICLE 1 #include "Shaders/Model.inl" #undef SOFT_PARTICLE } namespace CanvasItem { #include "Shaders/Model2D.inl" } #undef LIGHTING #undef DISTORTION } } template <int N> void ModelRenderer::InitRenderer() { auto applyPSAdvancedRendererParameterTexture = [](Shader* shader, int32_t offset) -> void { shader->SetTextureSlot(0 + offset, shader->GetUniformId("Sampler_sampler_alphaTex")); shader->SetTextureSlot(1 + offset, shader->GetUniformId("Sampler_sampler_uvDistortionTex")); shader->SetTextureSlot(2 + offset, shader->GetUniformId("Sampler_sampler_blendTex")); shader->SetTextureSlot(3 + offset, shader->GetUniformId("Sampler_sampler_blendAlphaTex")); shader->SetTextureSlot(4 + offset, shader->GetUniformId("Sampler_sampler_blendUVDistortionTex")); }; auto shader_ad_unlit_ = m_shaders[(size_t)EffekseerRenderer::RendererShaderType::AdvancedUnlit].get(); // auto shader_ad_lit_ = m_shaders[(size_t)RendererShaderType::AdvancedLit].get(); // auto shader_ad_distortion_ = m_shaders[(size_t)RendererShaderType::AdvancedBackDistortion].get(); auto shader_unlit_ = m_shaders[(size_t)EffekseerRenderer::RendererShaderType::Unlit].get(); auto shader_lit_ = m_shaders[(size_t)EffekseerRenderer::RendererShaderType::Lit].get(); auto shader_distortion_ = m_shaders[(size_t)EffekseerRenderer::RendererShaderType::BackDistortion].get(); // shader_ad_lit_->SetVertexConstantBufferSize( // sizeof(::EffekseerRenderer::ModelRendererAdvancedVertexConstantBuffer<N>)); shader_ad_unlit_->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererAdvancedVertexConstantBuffer<N>)); // shader_ad_distortion_->SetVertexConstantBufferSize( // sizeof(::EffekseerRenderer::ModelRendererAdvancedVertexConstantBuffer<N>)); // shader_ad_lit_->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBuffer)); shader_ad_unlit_->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBuffer)); // shader_ad_distortion_->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBufferDistortion)); shader_lit_->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<N>)); shader_unlit_->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<N>)); // shader_distortion_->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<N>)); shader_lit_->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBuffer)); shader_unlit_->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBuffer)); // shader_distortion_->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBufferDistortion)); // for (auto& shader : {/*shader_ad_lit_, */shader_lit_}) { // shader->SetTextureSlot(0, shader->GetUniformId("sDiffMap")); // shader->SetTextureSlot(1, shader->GetUniformId("sNormalMap")); // } // applyPSAdvancedRendererParameterTexture(shader_ad_lit_, 2); // shader_lit_->SetTextureSlot(2, shader_lit_->GetUniformId("Sampler_sampler_depthTex")); // shader_ad_lit_->SetTextureSlot(7, shader_ad_lit_->GetUniformId("Sampler_sampler_depthTex")); for (auto& shader : {shader_ad_unlit_, shader_unlit_}) { shader->SetTextureSlot(0, shader->GetUniformId("sDiffMap")); } applyPSAdvancedRendererParameterTexture(shader_ad_unlit_, 1); shader_unlit_->SetTextureSlot(1, shader_unlit_->GetUniformId("sNormalMap")); shader_ad_unlit_->SetTextureSlot(0, shader_ad_unlit_->GetUniformId("Sampler_sampler_colorTex")); shader_ad_unlit_->SetTextureSlot(6, shader_ad_unlit_->GetUniformId("Sampler_sampler_depthTex")); // for (auto& shader : {/*shader_ad_distortion_, */shader_distortion_}) // { // shader->SetTextureSlot(0, shader->GetUniformId("sDiffMap")); // shader->SetTextureSlot(2, shader->GetUniformId("sSpecMap")); // } // // applyPSAdvancedRendererParameterTexture(shader_ad_distortion_, 2); // shader_distortion_->SetTextureSlot(1, shader_distortion_->GetUniformId("sNormalMap")); // // shader_ad_distortion_->SetTextureSlot(7, shader_ad_distortion_->GetUniformId("Sampler_sampler_depthTex")); Shader* shaders[4]; shaders[0] = nullptr;// shader_ad_lit_; shaders[1] = shader_ad_unlit_; shaders[2] = shader_lit_; shaders[3] = shader_unlit_; for (int32_t i = 0; i < 4; i++) { if (i == 0 || i == 2) continue; auto isAd = i < 2; int vsOffset = 0; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_MATRIX44, shaders[i]->GetUniformId("mCameraProj"), vsOffset); vsOffset += sizeof(Effekseer::Matrix44); if (VertexType == EffekseerRenderer::ModelRendererVertexType::Instancing) { shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_MATRIX44, shaders[i]->GetUniformId("mModel_Inst"), vsOffset, N); } else { shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_MATRIX44, shaders[i]->GetUniformId("mModel"), vsOffset, N); } vsOffset += sizeof(Effekseer::Matrix44) * N; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fUV"), vsOffset, N); vsOffset += sizeof(float[4]) * N; if (isAd) { shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fAlphaUV"), vsOffset, N); vsOffset += sizeof(float[4]) * N; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fUVDistortionUV"), vsOffset, N); vsOffset += sizeof(float[4]) * N; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fBlendUV"), vsOffset, N); vsOffset += sizeof(float[4]) * N; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fBlendAlphaUV"), vsOffset, N); vsOffset += sizeof(float[4]) * N; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fBlendUVDistortionUV"), vsOffset, N); vsOffset += sizeof(float[4]) * N; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("vsFlipbookParameter"), vsOffset); vsOffset += sizeof(float[4]) * 1; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fFlipbookIndexAndNextRate"), vsOffset, N); vsOffset += sizeof(float[4]) * N; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fModelAlphaThreshold"), vsOffset, N); vsOffset += sizeof(float[4]) * N; } shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("fModelColor"), vsOffset, N); vsOffset += sizeof(float[4]) * N; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("vsLightDirection"), vsOffset); vsOffset += sizeof(float[4]) * 1; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("vsLightColor"), vsOffset); vsOffset += sizeof(float[4]) * 1; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("vsLightAmbient"), vsOffset); vsOffset += sizeof(float[4]) * 1; shaders[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders[i]->GetUniformId("mUVInversed"), vsOffset); vsOffset += sizeof(float[4]) * 1; AssignPixelConstantBuffer(shaders[i]); } // Shader* shaders_d[2]; // shaders_d[0] = nullptr;// shader_ad_distortion_; // shaders_d[1] = shader_distortion_; // // for (int32_t i = 0; i < 2; i++) { // auto isAd = i < 1; // if (isAd) { // continue; // } // int vsOffset = 0; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_MATRIX44, shaders_d[i]->GetUniformId("mCameraProj"), vsOffset); // vsOffset += sizeof(Effekseer::Matrix44); // if (VertexType == EffekseerRenderer::ModelRendererVertexType::Instancing) { // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_MATRIX44, shaders_d[i]->GetUniformId("mModel_Inst"), vsOffset, N); // } else { // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_MATRIX44, shaders_d[i]->GetUniformId("mModel"), vsOffset, N); // } // vsOffset += sizeof(Effekseer::Matrix44) * N; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fUV"), vsOffset, // N); // vsOffset += sizeof(float[4]) * N; // if (isAd) { // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fAlphaUV"), vsOffset, N); // vsOffset += sizeof(float[4]) * N; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fUVDistortionUV"), vsOffset, N); // vsOffset += sizeof(float[4]) * N; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fBlendUV"), vsOffset, N); // vsOffset += sizeof(float[4]) * N; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fBlendAlphaUV"), vsOffset, N); // vsOffset += sizeof(float[4]) * N; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fBlendUVDistortionUV"), vsOffset, N); // vsOffset += sizeof(float[4]) * N; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("vsFlipbookParameter"), vsOffset); // vsOffset += sizeof(float[4]) * 1; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fFlipbookIndexAndNextRate"), vsOffset, N); // vsOffset += sizeof(float[4]) * N; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fModelAlphaThreshold"), vsOffset, N); // vsOffset += sizeof(float[4]) * N; // } // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("fModelColor"), vsOffset, N); // vsOffset += sizeof(float[4]) * N; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("vsLightDirection"), vsOffset); // vsOffset += sizeof(float[4]) * 1; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("vsLightColor"), vsOffset); // vsOffset += sizeof(float[4]) * 1; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("vsLightAmbient"), vsOffset); // vsOffset += sizeof(float[4]) * 1; // shaders_d[i]->AddVertexConstantLayout(CONSTANT_TYPE_VECTOR4, shaders_d[i]->GetUniformId("mUVInversed"), vsOffset); // vsOffset += sizeof(float[4]) * 1; // AssignDistortionPixelConstantBuffer(shaders_d[i]); // } } static const int InstanceCount = 10; ModelRenderer::ModelRenderer(RendererImplemented* renderer) : m_renderer(renderer) { using namespace EffekseerRenderer; using namespace EffekseerUrho3D::ModelShaders; m_shaders[(size_t)RendererShaderType::Unlit] = Shader::Create(renderer->GetUrho3DGraphics(), "Effekseer/UnlitModel", RendererShaderType::Unlit); m_shaders[(size_t)RendererShaderType::Unlit]->SetVertexConstantBufferSize(sizeof(ModelRendererVertexConstantBuffer<40>)); m_shaders[(size_t)RendererShaderType::Unlit]->SetPixelConstantBufferSize(sizeof(PixelConstantBuffer)); m_shaders[(size_t)RendererShaderType::Unlit]->Compile(Shader::RenderType::SpatialLightweight, Unlit::Lightweight::code, Unlit::Lightweight::decl); m_shaders[(size_t)RendererShaderType::Unlit]->Compile(Shader::RenderType::SpatialDepthFade, Unlit::SoftParticle::code, Unlit::SoftParticle::decl); m_shaders[(size_t)RendererShaderType::Unlit]->Compile(Shader::RenderType::CanvasItem, Unlit::CanvasItem::code, Unlit::CanvasItem::decl); m_shaders[(size_t)RendererShaderType::Lit] = Shader::Create(renderer->GetUrho3DGraphics(), "Effekseer/UnlitModel"/*"Model_Basic_Lighting"*/, RendererShaderType::Lit); m_shaders[(size_t)RendererShaderType::Lit]->SetVertexConstantBufferSize(sizeof(ModelRendererVertexConstantBuffer<40>)); m_shaders[(size_t)RendererShaderType::Lit]->SetPixelConstantBufferSize(sizeof(PixelConstantBuffer)); m_shaders[(size_t)RendererShaderType::Lit]->Compile(Shader::RenderType::SpatialLightweight, Lighting::Lightweight::code, Lighting::Lightweight::decl); m_shaders[(size_t)RendererShaderType::Lit]->Compile(Shader::RenderType::SpatialDepthFade, Lighting::SoftParticle::code, Lighting::SoftParticle::decl); m_shaders[(size_t)RendererShaderType::Lit]->Compile(Shader::RenderType::CanvasItem, Lighting::CanvasItem::code, Lighting::CanvasItem::decl); // m_shaders[(size_t)RendererShaderType::BackDistortion] = Shader::Create(renderer->GetUrho3DGraphics(), "Effekseer/BackDistortionModel", RendererShaderType::BackDistortion); // m_shaders[(size_t)RendererShaderType::BackDistortion]->SetVertexConstantBufferSize(sizeof(ModelRendererVertexConstantBuffer<40>)); // m_shaders[(size_t)RendererShaderType::BackDistortion]->SetPixelConstantBufferSize(sizeof(PixelConstantBuffer)); // m_shaders[(size_t)RendererShaderType::BackDistortion]->Compile(Shader::RenderType::SpatialLightweight, Distortion::Lightweight::code, Distortion::Lightweight::decl); // m_shaders[(size_t)RendererShaderType::BackDistortion]->Compile(Shader::RenderType::SpatialDepthFade, Distortion::SoftParticle::code, Distortion::SoftParticle::decl); // m_shaders[(size_t)RendererShaderType::BackDistortion]->Compile(Shader::RenderType::CanvasItem, Distortion::CanvasItem::code, Distortion::CanvasItem::decl); m_shaders[(size_t)RendererShaderType::AdvancedUnlit] = Shader::Create(renderer->GetUrho3DGraphics(), "Effekseer/AdvancedUnlitModel", RendererShaderType::AdvancedUnlit); if (false/*renderer->GetDeviceType() == OpenGLDeviceType::OpenGL3 || renderer->GetDeviceType() == OpenGLDeviceType::OpenGLES3*/) { VertexType = EffekseerRenderer::ModelRendererVertexType::Instancing; InitRenderer<InstanceCount>(); } else { InitRenderer<1>(); } } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- ModelRenderer::~ModelRenderer() { } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- ModelRendererRef ModelRenderer::Create(RendererImplemented* renderer) { assert(renderer != NULL); return ModelRendererRef(new ModelRenderer(renderer)); } void ModelRenderer::BeginRendering(const efkModelNodeParam& parameter, int32_t count, void* userData) { BeginRendering_(m_renderer, parameter, count, userData); } void ModelRenderer::Rendering(const efkModelNodeParam& parameter, const InstanceParameter& instanceParameter, void* userData) { Rendering_<RendererImplemented>(m_renderer, parameter, instanceParameter, userData); } static void StoreBufferToGPU(Effekseer::Model* model) { if (model->isBufferStoredOnGPU_ || model->models_[0].vertexBuffer.Get()) { return; } static ea::vector<Urho3D::VertexElement> layout; if (layout.empty()) { layout.push_back(Urho3D::VertexElement(Urho3D::TYPE_VECTOR3, Urho3D::SEM_POSITION, 0, false)); layout.push_back(Urho3D::VertexElement(Urho3D::TYPE_VECTOR3, Urho3D::SEM_NORMAL, 0, false)); layout.push_back(Urho3D::VertexElement(Urho3D::TYPE_VECTOR3, Urho3D::SEM_BINORMAL, 0, false)); layout.push_back(Urho3D::VertexElement(Urho3D::TYPE_VECTOR3, Urho3D::SEM_TANGENT, 0, false)); layout.push_back(Urho3D::VertexElement(Urho3D::TYPE_VECTOR2, Urho3D::SEM_TEXCOORD, 0, false)); layout.push_back(Urho3D::VertexElement(Urho3D::TYPE_UBYTE4_NORM, Urho3D::SEM_COLOR, 0, false)); } auto context = GetUrho3DContext(); for (int32_t f = 0; f < model->GetFrameCount(); f++) { auto& md = model->models_[f]; md.vertexBuffer = Backend::VertexBuffer::Create(context, model->GetVertexCount(f), layout, md.vertexes.data()); if (md.vertexBuffer == nullptr) { return; } md.indexBuffer = Backend::IndexBuffer::Create(context, 3 * model->GetFaceCount(f), Effekseer::Backend::IndexBufferStrideType::Stride4, md.faces.data()); if (md.indexBuffer == nullptr) { return; } } model->isBufferStoredOnGPU_ = true; } void ModelRenderer::EndRendering(const efkModelNodeParam& parameter, void* userData) { if (parameter.ModelIndex < 0) { return; } Effekseer::ModelRef model{ nullptr }; if (parameter.IsProceduralMode) { model = parameter.EffectPointer->GetProceduralModel(parameter.ModelIndex); } else { model = parameter.EffectPointer->GetModel(parameter.ModelIndex); } if (model == nullptr) { return; } StoreBufferToGPU(model.Get()); //model->StoreBufferToGPU(graphicsDevice_.Get()); if (!model->GetIsBufferStoredOnGPU()) { return; } // if (m_renderer->GetRenderMode() == Effekseer::RenderMode::Wireframe) // { // model->GenerateWireIndexBuffer(graphicsDevice_.Get()); // if (!model->GetIsWireIndexBufferGenerated()) // { // return; // } // } // m_renderer->SetModel(model); using namespace EffekseerRenderer; if (VertexType == EffekseerRenderer::ModelRendererVertexType::Instancing) { EndRendering_<RendererImplemented, Shader, Effekseer::Model, true, InstanceCount>( m_renderer, m_shaders[(size_t)RendererShaderType::AdvancedLit].get(), m_shaders[(size_t)RendererShaderType::AdvancedUnlit].get(), m_shaders[(size_t)RendererShaderType::AdvancedBackDistortion].get(), m_shaders[(size_t)RendererShaderType::Lit].get(), m_shaders[(size_t)RendererShaderType::Unlit].get(), m_shaders[(size_t)RendererShaderType::BackDistortion].get(), parameter, userData); } else { EndRendering_<RendererImplemented, Shader, Effekseer::Model, false, 1>( m_renderer, m_shaders[(size_t)RendererShaderType::AdvancedLit].get(), m_shaders[(size_t)RendererShaderType::AdvancedUnlit].get(), m_shaders[(size_t)RendererShaderType::AdvancedBackDistortion].get(), m_shaders[(size_t)RendererShaderType::Lit].get(), m_shaders[(size_t)RendererShaderType::Unlit].get(), m_shaders[(size_t)RendererShaderType::BackDistortion].get(), parameter, userData); } // m_renderer->SetModel(nullptr); } //---------------------------------------------------------------------------------- // //---------------------------------------------------------------------------------- } // namespace EffekseerUrho3D //---------------------------------------------------------------------------------- // //----------------------------------------------------------------------------------
49.176887
175
0.687785
[ "vector", "model" ]
b70b3878d7996a4b5eb51ca646219fe4b7f807e3
19,415
cpp
C++
SymmetricalBroccoli.cpp
tml1024/SymmetricalBroccoli
de5cb80093513476a417fb33b60f711fee55120a
[ "MIT" ]
3
2021-02-11T15:34:12.000Z
2022-03-24T04:52:40.000Z
SymmetricalBroccoli.cpp
tml1024/SymmetricalBroccoli
de5cb80093513476a417fb33b60f711fee55120a
[ "MIT" ]
null
null
null
SymmetricalBroccoli.cpp
tml1024/SymmetricalBroccoli
de5cb80093513476a417fb33b60f711fee55120a
[ "MIT" ]
1
2020-11-04T04:09:57.000Z
2020-11-04T04:09:57.000Z
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ /* MIT License Copyright (c) 2020 Tor Lillqvist 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. */ #if !defined APL || !defined IBM || !defined LIN #error APL, IBM and LIN must be defined in the Makefile or project #endif #if APL + IBM + LIN != 1 #error One and only one of APL, IBM or LIN must be defined as 1, the others as 0 #endif #ifndef XPLM300 #error This must to be compiled against the XPLM300 SDK #endif #include <stdarg.h> // Not <cstdarg> because then Visual C++ doesn't like va_copy() #include <sys/types.h> #if APL || LIN #include <fcntl.h> #include <sys/time.h> #include <unistd.h> #endif #if IBM #include <winsock2.h> #define CLOSESOCKET(s) closesocket(s) #else #include <netinet/in.h> #include <sys/socket.h> typedef int SOCKET; #define CLOSESOCKET(s) close(s) #endif #include <cerrno> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iostream> #include <string> #include <vector> #include "XPLMDataAccess.h" #include "XPLMDisplay.h" #include "XPLMGraphics.h" #include "XPLMMenus.h" #include "XPLMPlugin.h" #include "XPLMProcessing.h" #include "XPLMUtilities.h" #ifndef DEBUGWINDOW #define DEBUGWINDOW 0 #endif #ifndef DEBUGLOGDATA #define DEBUGLOGDATA 0 #endif #define MYNAME "SymmetricalBroccoli" #define MYSIG "fi.iki.tml." MYNAME #define X 0 #define Y 1 #define Z 2 #define PSI 3 #define THE 4 #define PHI 5 // XYZ are in centimetres, X-Plane wants metres. Additionally, exaggerate movement a bit. // Head movement: X: left and right, Y: vertical, Z: back and forward. #define X_FACTOR 0.015 #define Y_FACTOR -0.010 #define Z_FACTOR 0.030 // Head turning: PSI: left and right, THE: up and down, PHI: tilt left and right (not used) // Angles are in degrees. Turning of the head must be exaggerated more so that you can still see the // screen while turning your simulated head fully to the side (and even a bit towards the back). #define PSI_FACTOR 5 #define THE_FACTOR 3 #define PHI_FACTOR 1 #if DEBUGWINDOW static XPLMWindowID debug_window; #else static XPLMFlightLoopID flight_loop_id; #endif static XPLMDataRef view_type; static XPLMDataRef head_x, head_y, head_z, head_psi, head_the, head_phi; static SOCKET sock; static float current_time; static bool input_reset = true; #pragma pack(push, 2) struct PoseData { double d[6]; // x, y, z, yaw, pitch, roll }; #pragma pack(pop) #if !IBM static void strcpy_s(char *dest, size_t dest_size, const char *src) { strncpy(dest, src, dest_size); } static char *strerror_s(char *buf, size_t buflen, int errnum) { #if APL || (LIN && (_POSIX_C_SOURCE >= 200112L) && ! _GNU_SOURCE) // The XSI-compliant strerror_r() strerror_r(errnum, buf, buflen); return buf; #else // The GNU-specific one return strerror_r(errnum, buf, buflen); #endif } #endif #if IBM // From https://stackoverflow.com/questions/40159892/using-asprintf-on-windows static int vscprintf(const char * format, va_list pargs) { int retval; va_list argcopy; va_copy(argcopy, pargs); retval = vsnprintf(NULL, 0, format, argcopy); va_end(argcopy); return retval; } static int vasprintf(char **strp, const char *fmt, va_list ap) { int len = vscprintf(fmt, ap); if (len == -1) return -1; char *str = static_cast<char *>(malloc((size_t) len + 1)); if (!str) return -1; int r = vsnprintf(str, static_cast<size_t>(len) + 1, fmt, ap); if (r == -1) { free(str); return -1; } *strp = str; return r; } static int asprintf(char *strp[], const char *fmt, ...) { va_list ap; va_start(ap, fmt); int r = vasprintf(strp, fmt, ap); va_end(ap); return r; } #endif static void log_string(const char *message) { char *bufp; int n = static_cast<int>(floor(current_time)); asprintf(&bufp, "%0d:%02d:%02d.%03d " MYSIG ": %s\n", n/3600, n/60, n%60, static_cast<int>(floor((current_time - n) * 1000)), message); XPLMDebugString(bufp); free(bufp); } static void log_stringf(const char *format, ...) { va_list ap; va_start(ap, format); char *bufp; vasprintf(&bufp, format, ap); log_string(bufp); free(bufp); va_end(ap); } static void error_callback(const char *message) { log_stringf("error callback: %s", message); } static void report_syscall_error(const char *syscall) { int saved_errno = errno; char buf[100]; log_stringf("%s failed: %s", syscall, strerror_s(buf, sizeof(buf), saved_errno)); } static void report_socket_error(const char *syscall) { #if IBM int saved_errno = WSAGetLastError(); char *buf; if (FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, saved_errno, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL) == 0) { log_stringf("%s failed: %d", syscall, saved_errno); } else { log_stringf("%s failed: %s", syscall, buf); LocalFree(buf); } #else report_syscall_error(syscall); #endif } #if DEBUGWINDOW #if 0 static int dummy_mouse_handler(XPLMWindowID window_id, int x, int y, int is_down, void *refcon) { return 0; } static XPLMCursorStatus dummy_cursor_status_handler(XPLMWindowID window_id, int x, int y, void *refcon) { return xplm_CursorDefault; } static int dummy_wheel_handler(XPLMWindowID window_id, int x, int y, int wheel, int clicks, void *refcon) { return 0; } #else #define dummy_mouse_handler NULL #define dummy_cursor_status_handler NULL #define dummy_wheel_handler NULL #endif static void debug_window_key_handler(XPLMWindowID window_id, char key, XPLMKeyFlags flags, char virtual_key, void *refcon, int losing_focus) { if (static_cast<unsigned char>(virtual_key) == XPLM_VK_PERIOD) { log_string("Re-loading plug-ins"); XPLMReloadPlugins(); } } static void draw_debug_window(const char *string) { // Mandatory: We *must* set the OpenGL state before drawing // (we can't make any assumptions about it) XPLMSetGraphicsState(0 /* no fog */, 0 /* 0 texture units */, 0 /* no lighting */, 0 /* no alpha testing */, 1 /* do alpha blend */, 1 /* do depth testing */, 0 /* no depth writing */ ); int l, t, r, b; XPLMGetWindowGeometry(debug_window, &l, &t, &r, &b); float col_white[] = {1.0, 1.0, 1.0}; // red, green, blue XPLMDrawString(col_white, l + 10, t - 20, const_cast<char*>(string), NULL, xplmFont_Proportional); } #endif #if DEBUGLOGDATA static void log_data(const std::string kind, const PoseData &data, float pilot_head_x, float pilot_head_y, float pilot_head_z, float pilot_head_psi, float pilot_head_the) { static bool been_here = false; static FILE *output; if (!been_here) { time_t now = time(NULL); char filename[100]; strftime(filename, sizeof(filename), "/tmp/" MYNAME ".%F.%H.%M.log", localtime(&now)); output = fopen(filename, "wt"); if (output != NULL) log_stringf("Logging data to %s", filename); else log_stringf("Could not open %s for writing", filename); been_here = true; } if (output != NULL) { static float first_time = current_time; static float prev_time = current_time; fprintf(output, "%6.3f %5.3f %s ", current_time - first_time, current_time - prev_time, kind.c_str()); for (int i = 0; i < 3; i++) fprintf(output, "%+6.2f ", data.d[i]); fprintf(output, " "); for (int i = 3; i < 6; i++) fprintf(output, "%+3.0f ", data.d[i]); fprintf(output, "%+6.3f %+6.3f %+6.3f %+6.1f %+6.1f\n", pilot_head_x, pilot_head_y, pilot_head_z, pilot_head_psi, pilot_head_the); if (kind == "rcv") prev_time = current_time; } } #endif static void filter_data(double curr_value[6], const double prev_value[6], const float time_diff) { constexpr double ALPHA = 0.5; const double prev_weight = pow(ALPHA, time_diff); for (int i = 0; i < 6; i++) curr_value[i] = (1 - prev_weight) * curr_value[i] + prev_weight * prev_value[i]; } static void get_and_handle_data() { PoseData data; long n; bool got_something = false; current_time = XPLMGetElapsedTime(); // Get the most current data packet sent, i.e. read all buffered ones and use only the last. while (true) { n = recv(sock, reinterpret_cast<char *>(&data), sizeof(data), 0); if (n == -1) { #if IBM if (WSAGetLastError() == WSAEWOULDBLOCK) break; #else if (errno == EAGAIN) break; #endif static int errors = 0; if (errors <= 10) report_socket_error("recv"); if (errors == 10) log_string("No further recv errors will be reported"); errors++; return; } else if (n != sizeof(data)) { static int errors = 0; if (errors <= 10) { log_stringf("Got %ld bytes, expected %d", n, sizeof(data)); } if (errors == 10) log_string("No further data amount discrepancies will be reported"); errors++; return; } else { got_something = true; } } if (!got_something) return; // 1026 is the 3D Cockpit if (XPLMGetDatai(view_type) != 1026) return; #if DEBUGLOGDATA log_data("rcv", data, 0, 0, 0, 0, 0); #endif static PoseData first_data; static float initial_pilot_head_pos[6]; static PoseData prev_data; static float prev_time; static bool first_time = true; // The very first time we get data we save the initial pilot head position if (first_time) { initial_pilot_head_pos[X] = XPLMGetDataf(head_x); initial_pilot_head_pos[Y] = XPLMGetDataf(head_y); initial_pilot_head_pos[Z] = XPLMGetDataf(head_z); initial_pilot_head_pos[PSI] = XPLMGetDataf(head_psi); initial_pilot_head_pos[THE] = XPLMGetDataf(head_the); initial_pilot_head_pos[PHI] = XPLMGetDataf(head_phi); if (initial_pilot_head_pos[X] == 0 && initial_pilot_head_pos[Y] == 0 && initial_pilot_head_pos[X] == 0 && initial_pilot_head_pos[PSI] == 0 && initial_pilot_head_pos[THE] == 0 && initial_pilot_head_pos[PHI] == 0) return; log_stringf("Initial head pos: XYZ=(%5.2f,%5.2f,%5.2f) psi=%d the=%d", initial_pilot_head_pos[X], initial_pilot_head_pos[Y], initial_pilot_head_pos[Z], static_cast<int>(initial_pilot_head_pos[PSI]), static_cast<int>(initial_pilot_head_pos[THE])); first_time = false; } // The very first time, or when reset, we save the current tracked head poisition if (input_reset) { first_data = data; prev_data = data; prev_time = current_time; input_reset = false; return; } const float time_diff = current_time - prev_time; filter_data(data.d, prev_data.d, time_diff); #if DEBUGWINDOW static char *debug_buf; asprintf(&debug_buf, "(%.1f,%.1f,%.1f) %d %d", data.d[X], data.d[Y], data.d[Z], static_cast<int>(data.d[PSI]), static_cast<int>(data.d[THE])); draw_debug_window(debug_buf); free(debug_buf); #endif float pilot_head_x = static_cast<float>((data.d[X] - first_data.d[X]) * X_FACTOR + initial_pilot_head_pos[X]); float pilot_head_y = static_cast<float>((data.d[Y] - first_data.d[Y]) * Y_FACTOR + initial_pilot_head_pos[Y]); float pilot_head_z = static_cast<float>((data.d[Z] - first_data.d[Z]) * Z_FACTOR + initial_pilot_head_pos[Z]); float pilot_head_psi = static_cast<float>((data.d[PSI] - first_data.d[PSI]) * PSI_FACTOR + initial_pilot_head_pos[PSI]); float pilot_head_the = static_cast<float>((data.d[THE] - first_data.d[THE]) * THE_FACTOR + initial_pilot_head_pos[THE]); XPLMSetDataf(head_x, pilot_head_x); XPLMSetDataf(head_y, pilot_head_y); XPLMSetDataf(head_z, pilot_head_z); XPLMSetDataf(head_psi, pilot_head_psi); XPLMSetDataf(head_the, pilot_head_the); // No need to roll the head static int num_logs = 0; if (num_logs < 100) { log_stringf("Setting XYZ=(%.2f,%.2f,%.2f) psi=%d the=%d", pilot_head_x, pilot_head_y, pilot_head_z, static_cast<int>(pilot_head_psi), static_cast<int>(pilot_head_the)); num_logs++; } #if DEBUGLOGDATA log_data("set", data, pilot_head_x, pilot_head_y, pilot_head_z, pilot_head_psi, pilot_head_the); #endif prev_data = data; prev_time = current_time; } #if DEBUGWINDOW static void draw_debug_window_callback(XPLMWindowID in_window_id, void *refcon) { get_and_handle_data(); } #else static float flight_loop_callback(float inElapsedSinceLastCall, float inElapsedTimeSinceLastFlightLoop, int inCounter, void *refcon) { get_and_handle_data(); return 1.0f/30; } #endif static XPLMDataRef find_data_ref(const char *name, int expected_type) { XPLMDataRef result = XPLMFindDataRef(name); if (result == NULL) { log_stringf("Could not find %s"); return NULL; } if (XPLMGetDataRefTypes(result) != expected_type) { log_stringf("%s is of unexpected type", name); return NULL; } return result; } PLUGIN_API int XPluginStart(char * outName, char * outSig, char * outDesc) { // The buffers are mentioned in instructions to be 256 characters strcpy_s(outName, 256, MYNAME); strcpy_s(outSig, 256, MYSIG); strcpy_s(outDesc, 256, "A plug-in that receives an OpenTrack-compatible data stream and moves the pilot's head."); XPLMSetErrorCallback(error_callback); XPLMEnableFeature("XPLM_USE_NATIVE_PATHS", 1); sock = socket(PF_INET, SOCK_DGRAM, 0); if (sock == -1) { report_socket_error("socket"); return 0; } struct sockaddr_in sa; memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = INADDR_ANY; sa.sin_port = htons(4242); if (bind(sock, (struct sockaddr *)&sa, sizeof(sa)) == -1) { report_socket_error("bind"); CLOSESOCKET(sock); return 0; } #if !IBM if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1) { report_socket_error("fcntl"); CLOSESOCKET(sock); return 0; } #else u_long mode = 1; if (ioctlsocket(sock, FIONBIO, &mode) != NO_ERROR) { report_socket_error("ioctlsocket"); CLOSESOCKET(sock); return 0; } #endif log_string("Starting"); if ((view_type = find_data_ref("sim/graphics/view/view_type", xplmType_Int)) == NULL) return 0; if ((head_x = find_data_ref("sim/graphics/view/pilots_head_x", xplmType_Float)) == NULL) return 0; if ((head_y = find_data_ref("sim/graphics/view/pilots_head_y", xplmType_Float)) == NULL) return 0; if ((head_z = find_data_ref("sim/graphics/view/pilots_head_z", xplmType_Float)) == NULL) return 0; if ((head_psi = find_data_ref("sim/graphics/view/pilots_head_psi", xplmType_Float)) == NULL) return 0; if ((head_the = find_data_ref("sim/graphics/view/pilots_head_the", xplmType_Float)) == NULL) return 0; if ((head_phi = find_data_ref("sim/graphics/view/pilots_head_phi", xplmType_Float)) == NULL) return 0; #if DEBUGWINDOW int left, bottom, right, top; XPLMGetScreenBoundsGlobal(&left, &top, &right, &bottom); const XPLMCreateWindow_t window_params = { sizeof(XPLMCreateWindow_t), left + 50, // left bottom + 50 + 200, // top left + 50 + 400, // right bottom + 50, // bottom 1, // visible draw_debug_window_callback, dummy_mouse_handler, // handleMouseClickFunc debug_window_key_handler, // handleKeyFunc dummy_cursor_status_handler, // handleCursorFunc dummy_wheel_handler, // handleMouseWheelFunc NULL, // refcon xplm_WindowDecorationRoundRectangle, xplm_WindowLayerFloatingWindows, NULL, // handleRightClickFunc }; debug_window = XPLMCreateWindowEx(const_cast<XPLMCreateWindow_t*>(&window_params)); if (debug_window == NULL) return 0; XPLMSetWindowPositioningMode(debug_window, xplm_WindowPositionFree, -1); XPLMSetWindowResizingLimits(debug_window, 200, 200, 400, 400); XPLMSetWindowTitle(debug_window, MYNAME " Debug Window"); #else const XPLMCreateFlightLoop_t flight_loop_params = { sizeof(XPLMCreateFlightLoop_t), xplm_FlightLoop_Phase_BeforeFlightModel, flight_loop_callback, NULL }; flight_loop_id = XPLMCreateFlightLoop(const_cast<XPLMCreateFlightLoop_t*>(&flight_loop_params)); XPLMScheduleFlightLoop(flight_loop_id, 1.0f/30, true); #endif static int reset_item; XPLMMenuID plugins_menu = XPLMFindPluginsMenu(); int my_submenu_item = XPLMAppendMenuItem(plugins_menu, MYNAME, NULL, 0); XPLMMenuID my_menu = XPLMCreateMenu("", plugins_menu, my_submenu_item, [](void *menu, void *item) { if (item == &reset_item) input_reset = true; }, NULL); XPLMAppendMenuItem(my_menu, "Reset", &reset_item, 0); return 1; } PLUGIN_API void XPluginStop(void) { } PLUGIN_API void XPluginDisable(void) { } PLUGIN_API int XPluginEnable(void) { return 1; } PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom, int inMsg, void * inParam) { }
29.151652
170
0.636518
[ "vector", "3d" ]
b70bf8434f628130cb6bd2b02ed07d8c0f8a65e3
8,792
cpp
C++
src/subdivision.cpp
abhisachdev17/Subdivisions
34e1f2279318209f13d40f8117f5657238c76887
[ "CC0-1.0" ]
null
null
null
src/subdivision.cpp
abhisachdev17/Subdivisions
34e1f2279318209f13d40f8117f5657238c76887
[ "CC0-1.0" ]
null
null
null
src/subdivision.cpp
abhisachdev17/Subdivisions
34e1f2279318209f13d40f8117f5657238c76887
[ "CC0-1.0" ]
null
null
null
#include "subdivision.h" #include "types.h" #include "gputypes.h" #include <iostream> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "common.h" #include <chrono> void addFaceToMesh(Mesh* m, Vertex *v1, Vertex* v2, Vertex* v3, Vertex* v4, int id) { Vertex** vs = new Vertex * [4]; vs[0] = v1; vs[1] = v2; vs[2] = v3; vs[3] = v4; Face* face = new Face(id, vs); m->addFace(face); } int getEdge(std::vector <Edge> edges, int v1, int v2) { for (int i = 0; i < edges.size(); i++) { if (edges[i].vids[0] == v1 || edges[i].vids[1] == v1) { if (edges[i].vids[0] == v2 || edges[i].vids[1] == v2) { return i; } } } return -1; } Face* getSharingFace(Mesh* m, int f, int v1, int v2) { for (int i = 0; i < m->faces.size(); i++) { Face* face = m->faces[i]; if (face->id != f) { bool v1in = false; bool v2in = false; for (int v = 0; v < 4; v++) { if (v1 == face->vertices[v]->id) { v1in = true; } if (v2 == face->vertices[v]->id) { v2in = true; } } if (v1in && v2in) { return face; } } } return nullptr; } glm::vec3 calc_edgepoints(glm::vec3 v1, glm::vec3 v2, glm::vec3 f1, glm::vec3 f2) { glm::vec3 avg = (v1 + v2 + f1 + f2) / 4.0f; return avg; } glm::vec3 calc_new_vertex(Vertex* v, Vertex** facepoints) { glm::vec3 vdash, S, R; float n = v->faces.size(); for (int i = 0; i < v->faces.size(); i++) { S += facepoints[v->faces[i]->id - 1]->vertex; } S /= n; for (int i = 0; i < v->edges.size(); i++) { R += (v->vertex + v->edges[i]->vertex) / 2.0f; } R /= n; vdash = (n-3) * v->vertex + 2.0f * R + S; return vdash / n; } Mesh* cc_subdivide(Mesh* m, GLuint * program) { long long start = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); Mesh* subdivided = new Mesh(); std::vector <Edge> edges; Vertex** facepoints = new Vertex*[m->faces.size()]; int curr_id = 1; for (int i = 0; i < m->faces.size(); i++) { Face* face = m->faces[i]; glm::vec3 fp = face->facepoint; Vertex* fv = new Vertex(curr_id++, fp); facepoints[face->id - 1] = fv; subdivided->addVertex(fv); } for (int i = 0; i < m->faces.size(); i++) { Face* face = m->faces[i]; for (int e = 0; e < 4; e++) { Vertex* v1 = face->vertices[e]; Vertex* v2 = face->vertices[(e + 1) % 4]; Edge edge; int edgeidx = getEdge(edges, v1->id, v2->id); Vertex* edgeV; if (edgeidx == -1) { Edge new_edge; new_edge.vids[0] = v1->id; new_edge.vids[1] = v2->id; Face* shared = getSharingFace(m, face->id, v1->id, v2->id); new_edge.edgepoint = calc_edgepoints(v1->vertex, v2->vertex, face->facepoint, shared->facepoint); edgeV = new Vertex(curr_id++, new_edge.edgepoint); subdivided->addVertex(edgeV); new_edge.e = edgeV; edges.push_back(new_edge); edge = new_edge; } } } int curr_fid = 1; Vertex** newVertices = new Vertex * [m->vertices.size()]; for (int i = 0; i < m->vertices.size(); i++) { newVertices[i] = nullptr; } for (int i = 0; i < m->faces.size(); i++) { Face* face = m->faces[i]; for (int e = 0; e < 4; e++) { Vertex* v1 = face->vertices[e]; Vertex* v2 = face->vertices[(e + 1) % 4]; int edge = getEdge(edges, v1->id, v2->id); Vertex* v3 = face->vertices[(e + 2) % 4]; int nextedge = getEdge(edges, v2->id, v3->id); if (newVertices[v2->id - 1] == nullptr) { Vertex* newV = new Vertex(curr_id++, calc_new_vertex(v2, facepoints)); newVertices[v2->id - 1] = newV; subdivided->addVertex(newV); } addFaceToMesh(subdivided, edges[edge].e, facepoints[face->id - 1], edges[nextedge].e, newVertices[v2->id-1], curr_fid++); } } long long end = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); std::cout << "Time taken to perform subdivision on CPU: " << end - start << "ms" << std::endl; return subdivided; } void addFaceToMesh(GPUMesh* m, int v1, int v2, int v3, int v4, int id) { GPUFace f; f.id = id; f.vertices[0] = v1; f.vertices[1] = v2; f.vertices[2] = v3; f.vertices[3] = v4; m->addFace(f); } int getEdge(std::vector <GPUEdge> edges, int v1, int v2) { for (int i = 0; i < edges.size(); i++) { if (edges[i].vertices[0] == v1 || edges[i].vertices[1] == v1) { if (edges[i].vertices[0] == v2 || edges[i].vertices[1] == v2) { return i; } } } return -1; } GPUMesh* cc_subdivide(GPUMesh* m, GLuint * program) { GPUMesh* subdivided = new GPUMesh(); GPUEdge new_edge; // Create edges, they are needed as input for subdivision calculation int curr_id = m->faces.size() + 1; for (int i = 0; i < m->faces.size(); i++) { GPUFace &face = m->faces[i]; for (int e = 0; e < 4; e++) { GPUVertex &v1 = m->vertices[face.vertices[e] - 1]; GPUVertex &v2 = m->vertices[face.vertices[(e + 1) % 4] - 1]; int edgeidx = getEdge(m->edges, v1.id, v2.id); if (edgeidx == -1) { new_edge.vertices[0] = v1.id; new_edge.vertices[1] = v2.id; new_edge.face = face.id; new_edge.id = curr_id++; m->edges.push_back(new_edge); } } } GLuint uKT = glGetUniformLocation(program[0], "kernelType"); GLuint uFO = glGetUniformLocation(program[0], "FACE_OFFSET"); GLuint uEO = glGetUniformLocation(program[0], "EDGE_OFFSET"); long long start = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); // load all data in the GPU glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[1]); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GPUVertex) * m->vertices.size(), &m->vertices[0], GL_DYNAMIC_COPY); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, program[1]); glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[2]); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GPUFace) * m->faces.size(), &m->faces[0], GL_DYNAMIC_COPY); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, program[2]); glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[3]); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GPUVertex) * (m->faces.size() + m->edges.size() + m->vertices.size()), NULL, GL_DYNAMIC_COPY); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, program[3]); glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[4]); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GPUFace) * (m->faces.size() * 4), NULL, GL_DYNAMIC_COPY); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, program[4]); glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[5]); glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(GPUEdge) * m->edges.size(), &m->edges[0], GL_DYNAMIC_COPY); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 5, program[5]); glUseProgram(program[0]); glUniform1i(uFO, m->faces.size()); glUniform1i(uEO, m->edges.size()); glUniform1i(uKT, 0); // face point calculation glDispatchCompute(m->faces.size(), 1, 1); glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[2]); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); // Compute the Edgepoints glUniform1i(uKT, 1); glDispatchCompute(m->edges.size(), 1, 1); // Compute the Vertices in parallel glUniform1i(uKT, 2); glDispatchCompute(m->vertices.size(), 1, 1); // wait for the above to finish glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[3]); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); // create new subdivided mesh glUniform1i(uKT, 3); glDispatchCompute(1, 1, 1); glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[3]); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[4]); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); long long end = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); std::cout << "Time taken to perform subdivision on GPU: " << end - start << "ms" << std::endl; start = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); GLvoid* p = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY); // read the new mesh for rendering std::copy((GPUFace*)p, (GPUFace*)p + m->faces.size() * 4, std::back_inserter(subdivided->faces)); glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); glBindBuffer(GL_SHADER_STORAGE_BUFFER, program[3]); glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); p = glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY); std::copy((GPUVertex*)p, (GPUVertex*)p + m->faces.size() + m->edges.size() + m->vertices.size(), std::back_inserter(subdivided->vertices)); glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); end = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()).count(); std::cout << "Time taken to copy buffers to CPU: " << end - start << "ms" << std::endl; return subdivided; }
29.80339
141
0.651388
[ "mesh", "vector" ]
b70c17868da501a147cd7faa4b38c5813274df52
1,155
cpp
C++
Museum/src/Scene/Display3.cpp
coolzoom/Museum
7c177beda99bd47ac7c7af358fbad9cb08e74bbc
[ "Apache-2.0" ]
1
2021-04-01T12:27:39.000Z
2021-04-01T12:27:39.000Z
Museum/src/Scene/Display3.cpp
coolzoom/Museum
7c177beda99bd47ac7c7af358fbad9cb08e74bbc
[ "Apache-2.0" ]
null
null
null
Museum/src/Scene/Display3.cpp
coolzoom/Museum
7c177beda99bd47ac7c7af358fbad9cb08e74bbc
[ "Apache-2.0" ]
1
2021-04-01T12:30:35.000Z
2021-04-01T12:30:35.000Z
#include "Display3.h" #include "Frame1.h" #include "Frame2.h" #include "Model.h"" Display3::Display3() { painting1 = std::make_shared<Frame2>("res/textures/art/art3_1.jpg"); painting1->frameModel->transform.Translate(0.0f, .5f, 9.99f); painting1->frameModel->transform.Rotate(0.0f, 90.0f, 0.0f); painting1->frameModel->transform.Scale(1.0f, 3.0f, 4.0f); painting2 = std::make_shared<Frame2>("res/textures/art/art3_2.jpg"); painting2->frameModel->transform.Translate(3.0f, .5f, 9.99f); painting2->frameModel->transform.Rotate(0.0f, 90.0f, 0.0f); painting2->frameModel->transform.Scale(1.0f, 2.0f, 4.2f); painting3 = std::make_shared<Frame2>("res/textures/art/art3_3.jpg"); painting3->frameModel->transform.Translate(-3.0f, .5f, 9.99f); painting3->frameModel->transform.Rotate(0.0f, 90.0f, 0.0f); painting3->frameModel->transform.Scale(1.0f, 2.0f, 3.2f); painting4 = std::make_shared<Frame1>("res/textures/art/art3_4.jpg"); painting4->frameModel->transform.Translate(5.0f, -1.4f, 9.99f); painting4->frameModel->transform.Rotate(0.0f, 90.0f, 0.0f); painting4->frameModel->transform.Scale(1.0f, 1.4f, 0.4); }
41.25
70
0.700433
[ "model", "transform" ]
b7155440720f5a8a4bf62ee457278016ee784d12
2,280
cpp
C++
ext/stub/java/util/WeakHashMap_Entry-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/util/WeakHashMap_Entry-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/java/util/WeakHashMap_Entry-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <java/util/WeakHashMap_Entry.hpp> extern void unimplemented_(const char16_t* name); java::util::WeakHashMap_Entry::WeakHashMap_Entry(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } java::util::WeakHashMap_Entry::WeakHashMap_Entry(::java::lang::Object* key, ::java::lang::Object* value, ::java::lang::ref::ReferenceQueue* queue, int32_t hash, WeakHashMap_Entry* next) : WeakHashMap_Entry(*static_cast< ::default_init_tag* >(0)) { ctor(key, value, queue, hash, next); } void ::java::util::WeakHashMap_Entry::ctor(::java::lang::Object* key, ::java::lang::Object* value, ::java::lang::ref::ReferenceQueue* queue, int32_t hash, WeakHashMap_Entry* next) { /* stub */ /* super::ctor(); */ unimplemented_(u"void ::java::util::WeakHashMap_Entry::ctor(::java::lang::Object* key, ::java::lang::Object* value, ::java::lang::ref::ReferenceQueue* queue, int32_t hash, WeakHashMap_Entry* next)"); } bool java::util::WeakHashMap_Entry::equals(::java::lang::Object* o) { /* stub */ unimplemented_(u"bool java::util::WeakHashMap_Entry::equals(::java::lang::Object* o)"); return 0; } java::lang::Object* java::util::WeakHashMap_Entry::getKey() { /* stub */ unimplemented_(u"java::lang::Object* java::util::WeakHashMap_Entry::getKey()"); return 0; } java::lang::Object* java::util::WeakHashMap_Entry::getValue() { /* stub */ return value ; /* getter */ } int32_t java::util::WeakHashMap_Entry::hashCode() { /* stub */ unimplemented_(u"int32_t java::util::WeakHashMap_Entry::hashCode()"); return 0; } java::lang::Object* java::util::WeakHashMap_Entry::setValue(::java::lang::Object* newValue) { /* stub */ } java::lang::String* java::util::WeakHashMap_Entry::toString() { /* stub */ unimplemented_(u"java::lang::String* java::util::WeakHashMap_Entry::toString()"); return 0; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* java::util::WeakHashMap_Entry::class_() { static ::java::lang::Class* c = ::class_(u"java.util.WeakHashMap.Entry", 27); return c; } java::lang::Class* java::util::WeakHashMap_Entry::getClass0() { return class_(); }
32.571429
203
0.689474
[ "object" ]
b71c969828037efba533a22910202e007046d8da
31,817
cxx
C++
Source/CPack/cmCPackDragNDropGenerator.cxx
eWert-Online/esy-cmake
c0de72da9a1bc4d9b4fbe3766bafcbaca442cc2c
[ "MIT" ]
null
null
null
Source/CPack/cmCPackDragNDropGenerator.cxx
eWert-Online/esy-cmake
c0de72da9a1bc4d9b4fbe3766bafcbaca442cc2c
[ "MIT" ]
null
null
null
Source/CPack/cmCPackDragNDropGenerator.cxx
eWert-Online/esy-cmake
c0de72da9a1bc4d9b4fbe3766bafcbaca442cc2c
[ "MIT" ]
null
null
null
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCPackDragNDropGenerator.h" #include <algorithm> #include <cstdlib> #include <iomanip> #include <map> #include <CoreFoundation/CoreFoundation.h> #include <cm3p/kwiml/abi.h> #include "cmsys/Base64.h" #include "cmsys/FStream.hxx" #include "cmsys/RegularExpression.hxx" #include "cmCPackGenerator.h" #include "cmCPackLog.h" #include "cmDuration.h" #include "cmGeneratedFileStream.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmXMLWriter.h" #ifdef HAVE_CoreServices // For the old LocaleStringToLangAndRegionCodes() function, to convert // to the old Script Manager RegionCode values needed for the 'LPic' data // structure used for generating multi-lingual SLAs. # include <CoreServices/CoreServices.h> #endif static const uint16_t DefaultLpic[] = { /* clang-format off */ 0x0002, 0x0011, 0x0003, 0x0001, 0x0000, 0x0000, 0x0002, 0x0000, 0x0008, 0x0003, 0x0000, 0x0001, 0x0004, 0x0000, 0x0004, 0x0005, 0x0000, 0x000E, 0x0006, 0x0001, 0x0005, 0x0007, 0x0000, 0x0007, 0x0008, 0x0000, 0x0047, 0x0009, 0x0000, 0x0034, 0x000A, 0x0001, 0x0035, 0x000B, 0x0001, 0x0020, 0x000C, 0x0000, 0x0011, 0x000D, 0x0000, 0x005B, 0x0004, 0x0000, 0x0033, 0x000F, 0x0001, 0x000C, 0x0010, 0x0000, 0x000B, 0x000E, 0x0000 /* clang-format on */ }; static const std::vector<std::string> DefaultMenu = { { "English", "Agree", "Disagree", "Print", "Save...", // NOLINTNEXTLINE(bugprone-suspicious-missing-comma) "You agree to the License Agreement terms when " "you click the \"Agree\" button.", "Software License Agreement", "This text cannot be saved. " "This disk may be full or locked, or the file may be locked.", "Unable to print. Make sure you have selected a printer." } }; cmCPackDragNDropGenerator::cmCPackDragNDropGenerator() : singleLicense(false) { // default to one package file for components this->componentPackageMethod = ONE_PACKAGE; } cmCPackDragNDropGenerator::~cmCPackDragNDropGenerator() = default; int cmCPackDragNDropGenerator::InitializeInternal() { // Starting with Xcode 4.3, look in "/Applications/Xcode.app" first: // std::vector<std::string> paths; paths.emplace_back("/Applications/Xcode.app/Contents/Developer/Tools"); paths.emplace_back("/Developer/Tools"); const std::string hdiutil_path = cmSystemTools::FindProgram("hdiutil", std::vector<std::string>(), false); if (hdiutil_path.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate hdiutil command" << std::endl); return 0; } this->SetOptionIfNotSet("CPACK_COMMAND_HDIUTIL", hdiutil_path.c_str()); const std::string setfile_path = cmSystemTools::FindProgram("SetFile", paths, false); if (setfile_path.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate SetFile command" << std::endl); return 0; } this->SetOptionIfNotSet("CPACK_COMMAND_SETFILE", setfile_path.c_str()); const std::string rez_path = cmSystemTools::FindProgram("Rez", paths, false); if (rez_path.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate Rez command" << std::endl); return 0; } this->SetOptionIfNotSet("CPACK_COMMAND_REZ", rez_path.c_str()); if (this->IsSet("CPACK_DMG_SLA_DIR")) { slaDirectory = this->GetOption("CPACK_DMG_SLA_DIR"); if (!slaDirectory.empty() && this->IsSet("CPACK_RESOURCE_FILE_LICENSE")) { std::string license_file = this->GetOption("CPACK_RESOURCE_FILE_LICENSE"); if (!license_file.empty() && (license_file.find("CPack.GenericLicense.txt") == std::string::npos)) { cmCPackLogger( cmCPackLog::LOG_OUTPUT, "Both CPACK_DMG_SLA_DIR and CPACK_RESOURCE_FILE_LICENSE specified, " "using CPACK_RESOURCE_FILE_LICENSE as a license for all languages." << std::endl); singleLicense = true; } } if (!this->IsSet("CPACK_DMG_SLA_LANGUAGES")) { cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_DMG_SLA_DIR set but no languages defined " "(set CPACK_DMG_SLA_LANGUAGES)" << std::endl); return 0; } if (!cmSystemTools::FileExists(slaDirectory, false)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_DMG_SLA_DIR does not exist" << std::endl); return 0; } std::vector<std::string> languages = cmExpandedList(this->GetOption("CPACK_DMG_SLA_LANGUAGES")); if (languages.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "CPACK_DMG_SLA_LANGUAGES set but empty" << std::endl); return 0; } for (auto const& language : languages) { std::string license = slaDirectory + "/" + language + ".license.txt"; std::string license_rtf = slaDirectory + "/" + language + ".license.rtf"; if (!singleLicense) { if (!cmSystemTools::FileExists(license) && !cmSystemTools::FileExists(license_rtf)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Missing license file " << language << ".license.txt" << " / " << language << ".license.rtf" << std::endl); return 0; } } std::string menu = slaDirectory + "/" + language + ".menu.txt"; if (!cmSystemTools::FileExists(menu)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Missing menu file " << language << ".menu.txt" << std::endl); return 0; } } } return this->Superclass::InitializeInternal(); } const char* cmCPackDragNDropGenerator::GetOutputExtension() { return ".dmg"; } int cmCPackDragNDropGenerator::PackageFiles() { // gather which directories to make dmg files for // multiple directories occur if packaging components or groups separately // monolith if (this->Components.empty()) { return this->CreateDMG(toplevel, packageFileNames[0]); } // component install std::vector<std::string> package_files; std::map<std::string, cmCPackComponent>::iterator compIt; for (compIt = this->Components.begin(); compIt != this->Components.end(); ++compIt) { std::string name = GetComponentInstallDirNameSuffix(compIt->first); package_files.push_back(name); } std::sort(package_files.begin(), package_files.end()); package_files.erase(std::unique(package_files.begin(), package_files.end()), package_files.end()); // loop to create dmg files packageFileNames.clear(); for (auto const& package_file : package_files) { std::string full_package_name = std::string(toplevel) + std::string("/"); if (package_file == "ALL_IN_ONE") { full_package_name += this->GetOption("CPACK_PACKAGE_FILE_NAME"); } else { full_package_name += package_file; } full_package_name += std::string(GetOutputExtension()); packageFileNames.push_back(full_package_name); std::string src_dir = cmStrCat(toplevel, '/', package_file); if (0 == this->CreateDMG(src_dir, full_package_name)) { return 0; } } return 1; } bool cmCPackDragNDropGenerator::CopyFile(std::ostringstream& source, std::ostringstream& target) { if (!cmSystemTools::CopyFileIfDifferent(source.str(), target.str())) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying " << source.str() << " to " << target.str() << std::endl); return false; } return true; } bool cmCPackDragNDropGenerator::CreateEmptyFile(std::ostringstream& target, size_t size) { cmsys::ofstream fout(target.str().c_str(), std::ios::out | std::ios::binary); if (!fout) { return false; } // Seek to desired size - 1 byte fout.seekp(size - 1, std::ios::beg); char byte = 0; // Write one byte to ensure file grows fout.write(&byte, 1); return true; } bool cmCPackDragNDropGenerator::RunCommand(std::ostringstream& command, std::string* output) { int exit_code = 1; bool result = cmSystemTools::RunSingleCommand( command.str(), output, output, &exit_code, nullptr, this->GeneratorVerbose, cmDuration::zero()); if (!result || exit_code) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error executing: " << command.str() << std::endl); return false; } return true; } int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir, const std::string& output_file) { // Get optional arguments ... const std::string cpack_package_icon = this->GetOption("CPACK_PACKAGE_ICON") ? this->GetOption("CPACK_PACKAGE_ICON") : ""; const std::string cpack_dmg_volume_name = this->GetOption("CPACK_DMG_VOLUME_NAME") ? this->GetOption("CPACK_DMG_VOLUME_NAME") : this->GetOption("CPACK_PACKAGE_FILE_NAME"); const std::string cpack_dmg_format = this->GetOption("CPACK_DMG_FORMAT") ? this->GetOption("CPACK_DMG_FORMAT") : "UDZO"; const std::string cpack_dmg_filesystem = this->GetOption("CPACK_DMG_FILESYSTEM") ? this->GetOption("CPACK_DMG_FILESYSTEM") : "HFS+"; // Get optional arguments ... std::string cpack_license_file = this->GetOption("CPACK_RESOURCE_FILE_LICENSE") ? this->GetOption("CPACK_RESOURCE_FILE_LICENSE") : ""; const std::string cpack_dmg_background_image = this->GetOption("CPACK_DMG_BACKGROUND_IMAGE") ? this->GetOption("CPACK_DMG_BACKGROUND_IMAGE") : ""; const std::string cpack_dmg_ds_store = this->GetOption("CPACK_DMG_DS_STORE") ? this->GetOption("CPACK_DMG_DS_STORE") : ""; const std::string cpack_dmg_languages = this->GetOption("CPACK_DMG_SLA_LANGUAGES") ? this->GetOption("CPACK_DMG_SLA_LANGUAGES") : ""; const std::string cpack_dmg_ds_store_setup_script = this->GetOption("CPACK_DMG_DS_STORE_SETUP_SCRIPT") ? this->GetOption("CPACK_DMG_DS_STORE_SETUP_SCRIPT") : ""; const bool cpack_dmg_disable_applications_symlink = this->IsOn("CPACK_DMG_DISABLE_APPLICATIONS_SYMLINK"); // only put license on dmg if is user provided if (!cpack_license_file.empty() && cpack_license_file.find("CPack.GenericLicense.txt") != std::string::npos) { cpack_license_file = ""; } // use sla_dir if both sla_dir and license_file are set if (!cpack_license_file.empty() && !slaDirectory.empty() && !singleLicense) { cpack_license_file = ""; } // The staging directory contains everything that will end-up inside the // final disk image ... std::ostringstream staging; staging << src_dir; // Add a symlink to /Applications so users can drag-and-drop the bundle // into it unless this behavior was disabled if (!cpack_dmg_disable_applications_symlink) { std::ostringstream application_link; application_link << staging.str() << "/Applications"; cmSystemTools::CreateSymlink("/Applications", application_link.str()); } // Optionally add a custom volume icon ... if (!cpack_package_icon.empty()) { std::ostringstream package_icon_source; package_icon_source << cpack_package_icon; std::ostringstream package_icon_destination; package_icon_destination << staging.str() << "/.VolumeIcon.icns"; if (!this->CopyFile(package_icon_source, package_icon_destination)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying disk volume icon. " "Check the value of CPACK_PACKAGE_ICON." << std::endl); return 0; } } // Optionally add a custom .DS_Store file // (e.g. for setting background/layout) ... if (!cpack_dmg_ds_store.empty()) { std::ostringstream package_settings_source; package_settings_source << cpack_dmg_ds_store; std::ostringstream package_settings_destination; package_settings_destination << staging.str() << "/.DS_Store"; if (!this->CopyFile(package_settings_source, package_settings_destination)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying disk volume settings file. " "Check the value of CPACK_DMG_DS_STORE." << std::endl); return 0; } } // Optionally add a custom background image ... // Make sure the background file type is the same as the custom image // and that the file is hidden so it doesn't show up. if (!cpack_dmg_background_image.empty()) { const std::string extension = cmSystemTools::GetFilenameLastExtension(cpack_dmg_background_image); std::ostringstream package_background_source; package_background_source << cpack_dmg_background_image; std::ostringstream package_background_destination; package_background_destination << staging.str() << "/.background/background" << extension; if (!this->CopyFile(package_background_source, package_background_destination)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying disk volume background image. " "Check the value of CPACK_DMG_BACKGROUND_IMAGE." << std::endl); return 0; } } bool remount_image = !cpack_package_icon.empty() || !cpack_dmg_ds_store_setup_script.empty(); std::string temp_image_format = "UDZO"; // Create 1 MB dummy padding file in staging area when we need to remount // image, so we have enough space for storing changes ... if (remount_image) { std::ostringstream dummy_padding; dummy_padding << staging.str() << "/.dummy-padding-file"; if (!this->CreateEmptyFile(dummy_padding, 1048576)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error creating dummy padding file." << std::endl); return 0; } temp_image_format = "UDRW"; } // Create a temporary read-write disk image ... std::string temp_image = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/temp.dmg"); std::string create_error; std::ostringstream temp_image_command; temp_image_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); temp_image_command << " create"; temp_image_command << " -ov"; temp_image_command << " -srcfolder \"" << staging.str() << "\""; temp_image_command << " -volname \"" << cpack_dmg_volume_name << "\""; temp_image_command << " -fs \"" << cpack_dmg_filesystem << "\""; temp_image_command << " -format " << temp_image_format; temp_image_command << " \"" << temp_image << "\""; if (!this->RunCommand(temp_image_command, &create_error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error generating temporary disk image." << std::endl << create_error << std::endl); return 0; } if (remount_image) { // Store that we have a failure so that we always unmount the image // before we exit. bool had_error = false; std::ostringstream attach_command; attach_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); attach_command << " attach"; attach_command << " \"" << temp_image << "\""; std::string attach_output; if (!this->RunCommand(attach_command, &attach_output)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error attaching temporary disk image." << std::endl); return 0; } cmsys::RegularExpression mountpoint_regex(".*(/Volumes/[^\n]+)\n.*"); mountpoint_regex.find(attach_output.c_str()); std::string const temp_mount = mountpoint_regex.match(1); std::string const temp_mount_name = temp_mount.substr(sizeof("/Volumes/") - 1); // Remove dummy padding file so we have enough space on RW image ... std::ostringstream dummy_padding; dummy_padding << temp_mount << "/.dummy-padding-file"; if (!cmSystemTools::RemoveFile(dummy_padding.str())) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error removing dummy padding file." << std::endl); had_error = true; } // Optionally set the custom icon flag for the image ... if (!had_error && !cpack_package_icon.empty()) { std::string error; std::ostringstream setfile_command; setfile_command << this->GetOption("CPACK_COMMAND_SETFILE"); setfile_command << " -a C"; setfile_command << " \"" << temp_mount << "\""; if (!this->RunCommand(setfile_command, &error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error assigning custom icon to temporary disk image." << std::endl << error << std::endl); had_error = true; } } // Optionally we can execute a custom apple script to generate // the .DS_Store for the volume folder ... if (!had_error && !cpack_dmg_ds_store_setup_script.empty()) { std::ostringstream setup_script_command; setup_script_command << "osascript" << " \"" << cpack_dmg_ds_store_setup_script << "\"" << " \"" << temp_mount_name << "\""; std::string error; if (!this->RunCommand(setup_script_command, &error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error executing custom script on disk image." << std::endl << error << std::endl); had_error = true; } } std::ostringstream detach_command; detach_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); detach_command << " detach"; detach_command << " \"" << temp_mount << "\""; if (!this->RunCommand(detach_command)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error detaching temporary disk image." << std::endl); return 0; } if (had_error) { return 0; } } // Create the final compressed read-only disk image ... std::ostringstream final_image_command; final_image_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); final_image_command << " convert \"" << temp_image << "\""; final_image_command << " -format "; final_image_command << cpack_dmg_format; final_image_command << " -imagekey"; final_image_command << " zlib-level=9"; final_image_command << " -o \"" << output_file << "\""; std::string convert_error; if (!this->RunCommand(final_image_command, &convert_error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error compressing disk image." << std::endl << convert_error << std::endl); return 0; } if (!cpack_license_file.empty() || !slaDirectory.empty()) { // Use old hardcoded style if sla_dir is not set bool oldStyle = slaDirectory.empty(); std::string sla_xml = cmStrCat(this->GetOption("CPACK_TOPLEVEL_DIRECTORY"), "/sla.xml"); std::vector<std::string> languages; if (!oldStyle) { cmExpandList(cpack_dmg_languages, languages); } std::vector<uint16_t> header_data; if (oldStyle) { header_data = std::vector<uint16_t>( DefaultLpic, DefaultLpic + (sizeof(DefaultLpic) / sizeof(*DefaultLpic))); } else { /* * LPic Layout * (https://github.com/pypt/dmg-add-license/blob/master/main.c) * as far as I can tell (no official documentation seems to exist): * struct LPic { * uint16_t default_language; // points to a resid, defaulting to 0, * // which is the first set language * uint16_t length; * struct { * uint16_t language_code; * uint16_t resid; * uint16_t encoding; // Encoding from TextCommon.h, * // forcing MacRoman (0) for now. Might need to * // allow overwrite per license by user later * } item[1]; * } */ header_data.push_back(0); header_data.push_back(languages.size()); for (size_t i = 0; i < languages.size(); ++i) { CFStringRef language_cfstring = CFStringCreateWithCString( nullptr, languages[i].c_str(), kCFStringEncodingUTF8); CFStringRef iso_language = CFLocaleCreateCanonicalLanguageIdentifierFromString( nullptr, language_cfstring); if (!iso_language) { cmCPackLogger(cmCPackLog::LOG_ERROR, languages[i] << " is not a recognized language" << std::endl); } char iso_language_cstr[65]; CFStringGetCString(iso_language, iso_language_cstr, sizeof(iso_language_cstr) - 1, kCFStringEncodingMacRoman); LangCode lang = 0; RegionCode region = 0; #ifdef HAVE_CoreServices OSStatus err = LocaleStringToLangAndRegionCodes(iso_language_cstr, &lang, &region); if (err != noErr) #endif { cmCPackLogger(cmCPackLog::LOG_ERROR, "No language/region code available for " << iso_language_cstr << std::endl); return 0; } #ifdef HAVE_CoreServices header_data.push_back(region); header_data.push_back(i); header_data.push_back(0); #endif } } RezDoc rez; { RezDict lpic = { {}, 5000, {} }; lpic.Data.reserve(header_data.size() * sizeof(header_data[0])); for (uint16_t x : header_data) { // LPic header is big-endian. char* d = reinterpret_cast<char*>(&x); #if KWIML_ABI_ENDIAN_ID == KWIML_ABI_ENDIAN_ID_LITTLE lpic.Data.push_back(d[1]); lpic.Data.push_back(d[0]); #else lpic.Data.push_back(d[0]); lpic.Data.push_back(d[1]); #endif } rez.LPic.Entries.emplace_back(std::move(lpic)); } bool have_write_license_error = false; std::string error; if (oldStyle) { if (!this->WriteLicense(rez, 0, "", cpack_license_file, &error)) { have_write_license_error = true; } } else { for (size_t i = 0; i < languages.size() && !have_write_license_error; ++i) { if (singleLicense) { if (!this->WriteLicense(rez, i + 5000, languages[i], cpack_license_file, &error)) { have_write_license_error = true; } } else { if (!this->WriteLicense(rez, i + 5000, languages[i], "", &error)) { have_write_license_error = true; } } } } if (have_write_license_error) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error writing license file to SLA." << std::endl << error << std::endl); return 0; } this->WriteRezXML(sla_xml, rez); // Create the final compressed read-only disk image ... std::ostringstream embed_sla_command; embed_sla_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); embed_sla_command << " udifrez"; embed_sla_command << " -xml"; embed_sla_command << " \"" << sla_xml << "\""; embed_sla_command << " FIXME_WHY_IS_THIS_ARGUMENT_NEEDED"; embed_sla_command << " \"" << output_file << "\""; std::string embed_error; if (!this->RunCommand(embed_sla_command, &embed_error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error compressing disk image." << std::endl << embed_error << std::endl); return 0; } } return 1; } bool cmCPackDragNDropGenerator::SupportsComponentInstallation() const { return true; } std::string cmCPackDragNDropGenerator::GetComponentInstallDirNameSuffix( const std::string& componentName) { // we want to group components together that go in the same dmg package std::string package_file_name = this->GetOption("CPACK_PACKAGE_FILE_NAME"); // we have 3 mutually exclusive modes to work in // 1. all components in one package // 2. each group goes in its own package with left over // components in their own package // 3. ignore groups - if grouping is defined, it is ignored // and each component goes in its own package if (this->componentPackageMethod == ONE_PACKAGE) { return "ALL_IN_ONE"; } if (this->componentPackageMethod == ONE_PACKAGE_PER_GROUP) { // We have to find the name of the COMPONENT GROUP // the current COMPONENT belongs to. std::string groupVar = "CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP"; const char* _groupName = GetOption(groupVar); if (_groupName) { std::string groupName = _groupName; groupName = GetComponentPackageFileName(package_file_name, groupName, true); return groupName; } } std::string componentFileName = "CPACK_DMG_" + cmSystemTools::UpperCase(componentName) + "_FILE_NAME"; if (this->IsSet(componentFileName)) { return this->GetOption(componentFileName); } return GetComponentPackageFileName(package_file_name, componentName, false); } void cmCPackDragNDropGenerator::WriteRezXML(std::string const& file, RezDoc const& rez) { cmGeneratedFileStream fxml(file); cmXMLWriter xml(fxml); xml.StartDocument(); xml.StartElement("plist"); xml.Attribute("version", "1.0"); xml.StartElement("dict"); this->WriteRezArray(xml, rez.LPic); this->WriteRezArray(xml, rez.Menu); this->WriteRezArray(xml, rez.Text); this->WriteRezArray(xml, rez.RTF); xml.EndElement(); // dict xml.EndElement(); // plist xml.EndDocument(); fxml.Close(); } void cmCPackDragNDropGenerator::WriteRezArray(cmXMLWriter& xml, RezArray const& array) { if (array.Entries.empty()) { return; } xml.StartElement("key"); xml.Content(array.Key); xml.EndElement(); // key xml.StartElement("array"); for (RezDict const& dict : array.Entries) { this->WriteRezDict(xml, dict); } xml.EndElement(); // array } void cmCPackDragNDropGenerator::WriteRezDict(cmXMLWriter& xml, RezDict const& dict) { std::vector<char> base64buf(dict.Data.size() * 3 / 2 + 5); size_t base64len = cmsysBase64_Encode(dict.Data.data(), dict.Data.size(), reinterpret_cast<unsigned char*>(base64buf.data()), 0); std::string base64data(base64buf.data(), base64len); /* clang-format off */ xml.StartElement("dict"); xml.StartElement("key"); xml.Content("Attributes"); xml.EndElement(); xml.StartElement("string"); xml.Content("0x0000"); xml.EndElement(); xml.StartElement("key"); xml.Content("Data"); xml.EndElement(); xml.StartElement("data"); xml.Content(base64data); xml.EndElement(); xml.StartElement("key"); xml.Content("ID"); xml.EndElement(); xml.StartElement("string"); xml.Content(dict.ID); xml.EndElement(); xml.StartElement("key"); xml.Content("Name"); xml.EndElement(); xml.StartElement("string"); xml.Content(dict.Name); xml.EndElement(); xml.EndElement(); // dict /* clang-format on */ } bool cmCPackDragNDropGenerator::WriteLicense(RezDoc& rez, size_t licenseNumber, std::string licenseLanguage, const std::string& licenseFile, std::string* error) { if (!licenseFile.empty() && !singleLicense) { licenseNumber = 5002; licenseLanguage = "English"; } // License file RezArray* licenseArray = &rez.Text; std::string actual_license; if (!licenseFile.empty()) { if (cmHasLiteralSuffix(licenseFile, ".rtf")) { licenseArray = &rez.RTF; } actual_license = licenseFile; } else { std::string license_wo_ext = slaDirectory + "/" + licenseLanguage + ".license"; if (cmSystemTools::FileExists(license_wo_ext + ".txt")) { actual_license = license_wo_ext + ".txt"; } else { licenseArray = &rez.RTF; actual_license = license_wo_ext + ".rtf"; } } // License body { RezDict license = { licenseLanguage, licenseNumber, {} }; std::vector<std::string> lines; if (!this->ReadFile(actual_license, lines, error)) { return false; } this->EncodeLicense(license, lines); licenseArray->Entries.emplace_back(std::move(license)); } // Menu body { RezDict menu = { licenseLanguage, licenseNumber, {} }; if (!licenseFile.empty() && !singleLicense) { this->EncodeMenu(menu, DefaultMenu); } else { std::vector<std::string> lines; std::string actual_menu = slaDirectory + "/" + licenseLanguage + ".menu.txt"; if (!this->ReadFile(actual_menu, lines, error)) { return false; } this->EncodeMenu(menu, lines); } rez.Menu.Entries.emplace_back(std::move(menu)); } return true; } void cmCPackDragNDropGenerator::EncodeLicense( RezDict& dict, std::vector<std::string> const& lines) { // License text uses CR newlines. for (std::string const& l : lines) { dict.Data.insert(dict.Data.end(), l.begin(), l.end()); dict.Data.push_back('\r'); } dict.Data.push_back('\r'); } void cmCPackDragNDropGenerator::EncodeMenu( RezDict& dict, std::vector<std::string> const& lines) { // Menu resources start with a big-endian uint16_t for number of lines: { uint16_t numLines = static_cast<uint16_t>(lines.size()); char* d = reinterpret_cast<char*>(&numLines); #if KWIML_ABI_ENDIAN_ID == KWIML_ABI_ENDIAN_ID_LITTLE dict.Data.push_back(d[1]); dict.Data.push_back(d[0]); #else dict.Data.push_back(d[0]); dict.Data.push_back(d[1]); #endif } // Each line starts with a uint8_t length, plus the bytes themselves: for (std::string const& l : lines) { dict.Data.push_back(static_cast<unsigned char>(l.length())); dict.Data.insert(dict.Data.end(), l.begin(), l.end()); } } bool cmCPackDragNDropGenerator::ReadFile(std::string const& file, std::vector<std::string>& lines, std::string* error) { cmsys::ifstream ifs(file); std::string line; while (std::getline(ifs, line)) { if (!this->BreakLongLine(line, lines, error)) { return false; } } return true; } bool cmCPackDragNDropGenerator::BreakLongLine(const std::string& line, std::vector<std::string>& lines, std::string* error) { const size_t max_line_length = 255; size_t line_length = max_line_length; for (size_t i = 0; i < line.size(); i += line_length) { line_length = max_line_length; if (i + line_length > line.size()) { line_length = line.size() - i; } else { while (line_length > 0 && line[i + line_length - 1] != ' ') { line_length = line_length - 1; } } if (line_length == 0) { *error = "Please make sure there are no words " "(or character sequences not broken up by spaces or newlines) " "in your license file which are more than 255 characters long."; return false; } lines.push_back(line.substr(i, line_length)); } return true; }
34.248654
79
0.623252
[ "vector" ]
b71f3bc1af55894b24fe479dcde7de9fcd99132b
17,749
cpp
C++
src/cpp/NAM/FS_NameService.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
10
2021-02-19T20:19:24.000Z
2021-09-16T05:11:50.000Z
src/cpp/NAM/FS_NameService.cpp
xguerin/openstreams
7000370b81a7f8778db283b2ba9f9ead984b7439
[ "Apache-2.0" ]
7
2021-02-20T01:17:12.000Z
2021-06-08T14:56:34.000Z
src/cpp/NAM/FS_NameService.cpp
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
4
2021-02-19T18:43:10.000Z
2022-02-23T14:18:16.000Z
/* * Copyright 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <dirent.h> #include <errno.h> #include <fstream> #include <libgen.h> #include <sstream> #include <string> #include <sys/stat.h> #include <sys/types.h> #include <NAM/FS_NameService.h> #include <NAM/NAMMessages.h> #include <TRC/DistilleryDebug.h> #include <TRC/RuntimeTrcAspects.h> #include <UTILS/Directory.h> #include <UTILS/RegEx.h> #include <UTILS/SupportFunctions.h> using namespace std; UTILS_NAMESPACE_USE; NAM_NAMESPACE_USE; DEBUG_NAMESPACE_USE; using namespace UTILS_RUNTIME_NS::mr; #define SCOPE_SUB "sub" #define SCOPE_ONE "one" FS_NameService::FS_NameService(const string& ns_arg, const string& distID) : _distillery_id(distID) { SPCDBG(L_INFO, "FS_NameService::FS_NameService(" << QT(ns_arg) << ")", NAM_GET_INSTANCE); initServer(ns_arg); } FS_NameService::FS_NameService(const string& ns_arg, const string& domainID, const string& distID) : _distillery_id(distID) { SPCDBG(L_INFO, "FS_NameService::FS_NameService(" << QT(ns_arg) << ")", NAM_GET_INSTANCE); initServer(ns_arg); } void FS_NameService::initServer(const std::string& ns_arg) { SPCDBG(L_DEBUG, "initServer(" << QT(ns_arg) << ")", NAM_GET_INSTANCE); _stg_path = ns_arg.substr(3); if (!_stg_path.length()) { _stg_path = getenv("HOME"); _stg_path += "/.fsnameserver"; } try { Directory::smkdir(_stg_path, 0755); } catch (DirectoryException e) { THROW_NESTED(NAM, "Unable to create or access storage directory: " << _stg_path, e, NAMUnableToAccessDir, _stg_path.c_str()); } SPCDBG(L_DEBUG, "Exit", NAM_GET_INSTANCE); } FS_NameService::~FS_NameService() {} string FS_NameService::createObjName(const string& name) { string nsname; nsname = _stg_path; if (name.at(0) != '/') { nsname += "/"; } nsname += name; nsname += "@"; nsname += _distillery_id; SPCDBG(L_TRACE, "createObjName(" << QT(name) << ", " << QT(nsname) << ")", NAM_GENERAL); return nsname; } string FS_NameService::createObjDir(const string& name) { string nsname; nsname = _stg_path; if (name.at(0) != '/') { nsname += "/"; } nsname += name; SPCDBG(L_TRACE, "createObjDir(" << QT(name) << ", " << QT(nsname) << ")", NAM_GENERAL); return nsname; } void FS_NameService::addOrUpdateObject(const string& name, const NameRecord& obj, int numRetries, bool update) { SPCDBG(L_DEBUG, "addOrUpdateObject(" << QT(name) << ")", NAM_REGISTER_ENTRY); string tmpfilename = createObjName(name + ".new"); string filename = createObjName(name); string last_error = "unknown error"; char errno_buffer[1024]; if (Directory::sisAFile(filename) && !update) { THROW(NameExists, "Registering " << QT(filename) << " failed (already exists)", NAMNameExists, filename.c_str()); } SPCDBG(L_TRACE, "Registering object " << name, NAM_REGISTER_ENTRY); if (numRetries == -1) { numRetries = max_retry; } bool abort = false; while (!abort) { ofstream of(tmpfilename.c_str(), ios::out | ios::trunc); if (of.is_open()) { of << obj.toString(); of.flush(); of.close(); int rc = rename(tmpfilename.c_str(), filename.c_str()); if (rc == 0) { SPCDBG(L_INFO, "Registered object " << name, NAM_REGISTER_ENTRY); return; } else { last_error = strerror_r(errno, errno_buffer, 1023); SPCDBG(L_WARN, "Renaming " << QT(tmpfilename) << " to " << QT(filename) << " failed: " << last_error, NAM_REGISTER_ENTRY); string trashfilename = createObjName(name + ".trash"); rc = rename(filename.c_str(), trashfilename.c_str()); if (rc == 0) { rc = rename(tmpfilename.c_str(), filename.c_str()); if (rc == 0) { if (unlink(trashfilename.c_str()) != 0) { last_error = strerror_r(errno, errno_buffer, 1023); SPCDBG(L_WARN, "Fail to remove the temp trash file " << QT(trashfilename) << ": " << last_error, NAM_REGISTER_ENTRY); } SPCDBG(L_INFO, "Registered object " << name, NAM_REGISTER_ENTRY); return; } else { last_error = strerror_r(errno, errno_buffer, 1023); SPCDBG(L_WARN, "Renaming " << QT(tmpfilename) << " to " << QT(filename) << " failed again: " << last_error, NAM_REGISTER_ENTRY); } } else { last_error = strerror_r(errno, errno_buffer, 1023); SPCDBG(L_WARN, "Renaming " << QT(filename) << " to " << QT(trashfilename) << " failed: " << last_error, NAM_REGISTER_ENTRY); } } } else { last_error = strerror_r(errno, errno_buffer, 1023); SPCDBG(L_WARN, "Unable to open or create " << QT(tmpfilename) << ": " << last_error, NAM_REGISTER_ENTRY); } numRetries--; if (max_retry < numRetries) { // we want to make sure that if someone sets max_retry to a lower // number that it gets picked up dynamically numRetries = max_retry; } if (numRetries < 0 || shutdown_request) { abort = true; } else { sleep(1); } } // failed to register..remove the .new file unlink(tmpfilename.c_str()); THROW(NAM, "Registering an object failed " << QT(name) << ": " << last_error, NAMRegisterFailed, name.c_str(), last_error.c_str()); } void FS_NameService::registerObject(const string& name, const NameRecord& obj, int numRetries) { SPCDBG(L_DEBUG, "registerObject: " << name, NAM_REGISTER_ENTRY); addOrUpdateObject(name, obj, numRetries, false); SPCDBG(L_DEBUG, "Exit", NAM_REGISTER_ENTRY); } void FS_NameService::unregisterObject(const string& name, int numRetries) { SPCDBG(L_DEBUG, "unregisterObject(" << QT(name) << ")", NAM_UNREGISTER_ENTRY); string filename = createObjName(name); kickIt(filename.c_str()); int rc = unlink(filename.c_str()); if (rc) { char errno_buffer[1024]; SPCDBG(L_WARN, "unlink(" << filename << ") failed: " << strerror_r(errno, errno_buffer, 1023), NAM_UNREGISTER_ENTRY); } else { SPCDBG(L_INFO, "Unregistered file " << filename, NAM_UNREGISTER_ENTRY); } } void FS_NameService::updateObject(const string& name, const NameRecord& obj, int numRetries) { SPCDBG(L_DEBUG, "updateObject: " << name, NAM_REGISTER_ENTRY); addOrUpdateObject(name, obj, numRetries, true); SPCDBG(L_DEBUG, "Exit", NAM_REGISTER_ENTRY); } void FS_NameService::lookupObject(const string& name, NameRecord& nr, int numRetries, const bool force) { SPCDBG(L_DEBUG, "lookupObject(" << QT(name) << ")", NAM_LOOKUP_ENTRY); string last_error = "unknown error"; char errno_buffer[1024]; string filename = createObjName(name); if (numRetries == -1) { numRetries = max_retry; } bool abort = false; while (!abort) { kickIt(filename.c_str()); ifstream file(filename.c_str()); if (file.is_open()) { stringstream ss; if (copyStream(file, ss) > 0) { try { nr.setObject(ss.str()); SPCDBG(L_INFO, "Done lookupObject for (" << QT(name) << "), got value: " << ss.str(), NAM_LOOKUP_ENTRY); return; } catch (...) { SPCDBG(L_WARN, "Parsing object " << QT(name) << " failed", NAM_LOOKUP_ENTRY); break; } } else { SPCDBG(L_WARN, "Lookup for " << QT(name) << " failed - empty file, sleeping 1 sec", NAM_LOOKUP_ENTRY); } } else { last_error = strerror_r(errno, errno_buffer, 1023); SPCDBG(L_WARN, "Lookup for " << QT(name) << " failed: " << last_error, NAM_LOOKUP_ENTRY); } numRetries--; if (max_retry < numRetries) { // we want to make sure that if someone sets max_retry to a lower // number that it gets picked up dynamically numRetries = max_retry; } if (numRetries < 0 || shutdown_request) { abort = true; } else { sleep(1); } } THROW(NameNotFound, "Lookup for " << QT(name) << " failed: " << last_error, NAMNameNotFound, name.c_str()); } void FS_NameService::createSubdir(const string& name, int numRetries) { // have to loop through the name hierarchy. string nsname = createObjDir(name); try { Directory::smkdir(nsname, 0755); } catch (DirectoryException e) { THROW_NESTED(NAM, "Unable to create or access storage directory: " << nsname, e, NAMUnableToAccessDir, nsname.c_str()); } } void FS_NameService::destroySubdir(const string& name, int numRetries) { string nsname = createObjDir(name); try { Directory::srmdir(nsname, true); } catch (DirectoryException e) { THROW_NESTED(NAM, "Unable to remove directory: " << nsname, e, NAMUnableToRemoveDir, nsname.c_str()); } } vector<string> FS_NameService::listObjects(const string& pattern, int numRetries) { SPCDBG(L_DEBUG, "Enter: listObjects with patten (" << QT(pattern) << ")", NAM_LIST_ENTRY); size_t ind = pattern.rfind("/"); string newPattern = pattern; string loc = _stg_path; if (ind != string::npos) { newPattern = pattern.substr(ind + 1); loc = _stg_path + "/" + pattern.substr(0, ind); } SPCDBG(L_TRACE, "listObjects with modified patten (" << QT(newPattern) << ", " << loc << ")", NAM_LIST_ENTRY); vector<string> records = listObjects(newPattern, loc, SCOPE_SUB, numRetries); // adding the dir back to each entry. if (ind != string::npos) { for (unsigned int i = 0; i < records.size(); i++) { records[i] = pattern.substr(0, ind + 1) + records[i]; } } SPCDBG(L_INFO, "Got listed objects (" << debug::join(records.begin(), records.end()) << ")", NAM_LIST_ENTRY); return records; } vector<string> FS_NameService::listObjects(const string& pattern, const string& startDir, const string& scope, int numRetries) { vector<string> result; SPCDBG(L_DEBUG, "listObjects('" << QT(pattern) << ", " << startDir << ", " << scope << "')", NAM_LIST_ENTRY); RegEx re(RegEx::glob2regex(pattern)); string did = "@"; did += _distillery_id; // SCOPE_ONE means just search for current level, no sub-dir been searched. if (scope.compare(SCOPE_ONE) == 0) { try { Directory dir(startDir, false, Directory::NODOTS | Directory::NODIRECTORIES); for (ConstDirEntryIterator i = dir.begin(); i != dir.end(); ++i) { string name = i->getBaseName(); SPCDBG(L_TRACE, "Considering match between '" << QT(name) << "' and RE '" << QT(pattern) << "' (did=" << _distillery_id << ")", NAM_LIST_ENTRY); string::size_type pos = name.rfind(did); if (pos != string::npos) { name = name.substr(0, pos); if (re.match(name)) { SPCDBG(L_TRACE, "Match found: '" << QT(name) << "' (did=" << _distillery_id << ")", NAM_LIST_ENTRY); result.push_back(name); } } } } catch (const DirectoryException& de) { // DirectoryException thrown from Directory if the directory not found. // In this case, log. Returned name list will be empty. SPCDBG(L_WARN, "Caught DirectoryException " << de.getExplanation() << " due to directory '" << startDir << "' not found or accessible.", NAM_LIST_ENTRY); } } // Default behavior will be search current dir and all sub-dir. else { vector<string> res = listObjects(startDir, re, did, numRetries, startDir); result.insert(result.end(), res.begin(), res.end()); } SPCDBG(L_DEBUG, "Got listed objects (" << debug::join(result.begin(), result.end()) << ")", NAM_LIST_ENTRY); return result; } vector<string> FS_NameService::listObjects(const string& d, const RegEx& re, const string& did, int numRetries, const string& oriDir) { vector<string> result; SPCDBG(L_DEBUG, "listObjects('" << d << ", " << re << ", " << did << "')", NAM_LIST_ENTRY); try { Directory dir(d, false, Directory::NODOTS); for (ConstDirEntryIterator i = dir.begin(); i != dir.end(); ++i) { string n = i->getName(); if (dir.isAFile(n)) { string name = i->getBaseName(); SPCDBG(L_TRACE, "Considering match between '" << QT(name) << "' and RE '" << re << "' (did=" << _distillery_id << ")", NAM_LIST_ENTRY); string::size_type pos = name.rfind(did); if (pos != string::npos) { name = name.substr(0, pos); if (re.match(name)) { if (d.compare(oriDir) != 0) { string::size_type startpos = d.find(oriDir) + oriDir.length(); if (oriDir.compare("/") != 0) { startpos += 1; } string relativeDir = d.substr(startpos); name = relativeDir + "/" + name; } SPCDBG(L_TRACE, "Match found: '" << QT(name) << "' (did=" << _distillery_id << ") with relative path of " << n, NAM_LIST_ENTRY); result.push_back(name); } } } else if (dir.isADirectory(n)) { string absPath(d); if (d.compare("/") != 0) { absPath += "/"; } absPath += n; vector<string> res = listObjects(absPath, re, did, numRetries, oriDir); result.insert(result.end(), res.begin(), res.end()); } else { SPCDBG(L_TRACE, "name of " << n << "is not a directory or a file.", NAM_LIST_ENTRY); } } } catch (const DirectoryException& de) { // DirectoryException thrown from Directory if the directory not found. // In this case, log. Returned name list will be empty. SPCDBG(L_WARN, "Caught DirectoryException " << de.getExplanation() << " due to directory '" << d << "' not found or accessible.", NAM_LIST_ENTRY); } SPCDBG(L_DEBUG, "Got listed objects (" << debug::join(result.begin(), result.end()) << ")", NAM_LIST_ENTRY); return result; } void FS_NameService::kickIt(const string& name) { char* _name = strdup(name.c_str()); char* dir = dirname(_name); DIR* d = opendir(dir); free(_name); if (d) { closedir(d); } } void FS_NameService::setMessageRecordingConfiguration( const UTILS_RUNTIME_NS::mr::MessageRecordingConfigurationType& mrct, int numRetries) { // Nothing to do here. } void FS_NameService::getMessageRecordingConfiguration( UTILS_RUNTIME_NS::mr::MessageRecordingConfigurationType& mrct, int numRetries) { // Nothing to do here. }
36.900208
100
0.523015
[ "object", "vector" ]
b7256615492cfb68a8efc022928db346b835d3ea
1,443
cpp
C++
901-1000/981-990/986-intervalIntersection/intervalIntersection.cpp
xuychen/Leetcode
c8bf33af30569177c5276ffcd72a8d93ba4c402a
[ "MIT" ]
null
null
null
901-1000/981-990/986-intervalIntersection/intervalIntersection.cpp
xuychen/Leetcode
c8bf33af30569177c5276ffcd72a8d93ba4c402a
[ "MIT" ]
null
null
null
901-1000/981-990/986-intervalIntersection/intervalIntersection.cpp
xuychen/Leetcode
c8bf33af30569177c5276ffcd72a8d93ba4c402a
[ "MIT" ]
null
null
null
#include <vector> #include <algorithm> using namespace std; class Solution { public: vector<vector<int>> intervalIntersection(vector<vector<int>>& a, vector<vector<int>>& b) { size_t aIndex = 0, bIndex = 0; size_t aLength = a.size(), bLength = b.size(); vector<vector<int>> result; while (aIndex < aLength && bIndex < bLength) { vector<int> aInterval = a[aIndex], bInterval = b[bIndex]; int left, right; left = max(aInterval[0], bInterval[0]); if (aInterval[1] <= bInterval[1]) { ++aIndex; right = aInterval[1]; } if (aInterval[1] >= bInterval[1]) { ++bIndex; right = bInterval[1]; } if (left <= right) result.push_back({left, right}); } return result; } vector<vector<int>> intervalIntersection2(vector<vector<int>>& a, vector<vector<int>>& b) { size_t aIndex = 0, bIndex = 0; size_t aLength = a.size(), bLength = b.size(); vector<vector<int>> result; while (aIndex < aLength && bIndex < bLength) { int left = max(a[aIndex][0], b[bIndex][0]); int right = a[aIndex][1] <= b[bIndex][1] ? a[aIndex++][1] : b[bIndex++][1]; if (left <= right) result.push_back({left, right}); } return result; } };
29.44898
95
0.505891
[ "vector" ]
b72660f9aabed0725ddf6c80d844715516814f7b
2,917
cpp
C++
ICPC_Mirrors/Nitc_44/g.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
ICPC_Mirrors/Nitc_44/g.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
ICPC_Mirrors/Nitc_44/g.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "/debug.h" #else #define db(...) #endif #define all(v) v.begin(), v.end() #define pb push_back using ll = long long; const int NAX = 2e5 + 5, MOD = 1000000007; struct Bit { int size; vector<int> table; Bit(int size) { this->size = size; table.resize(size); } void update(int i, int delta) { while (i < size) { table[i] += delta; i = i | (1 + i); } } int sum(int i) { int ret = 0; while (i >= 0) { ret += table[i]; i = (i & (i + 1)) - 1; } return ret; } int rangeSum(int i, int j) { if (i == 0) return sum(j); return sum(j) - sum(i - 1); } void print() { #ifdef LOCAL for (int i = 0; i < size; i++) cout << rangeSum(i, i) << ' '; cout << '\n'; #else #endif } }; void solveCase() { int n = 1000, k = 100; cin >> n >> k; vector<vector<int>> arr(n); for (auto &x : arr) { x.resize(k); for (auto &y : x) { y = rand() % MOD; cin >> y; --y; } } sort(all(arr)); auto comp = [&](int i, int j) -> int { vector<int> inv_mapper(n); for (size_t l = 0; l < k; l++) inv_mapper[arr[i][l]] = l; vector<int> other(n); for (size_t l = 0; l < k; l++) other[l] = inv_mapper[arr[j][l]]; Bit b(k); int res = 0; for (int l = k - 1; l >= 0; l--) { b.update(other[l], 1); int curr = b.rangeSum(other[l], k - 1); res = max(res, curr); } return n - res; }; vector<vector<int>> pre(n, vector<int>(n)); for (size_t i = 0; i < n; i++) for (size_t j = i + 1; j < n; j++) { pre[j][i] = pre[i][j] = comp(i, j); db(i, j, pre[i][j]); } auto get_cost = [&](int i, int j) -> int { if (i <= 0 || j <= 0) return 0; return pre[i - 1][j - 1]; }; vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1)); function<int(int, int)> solve_dp = [&](int i, int prev) -> int { if (prev > i) swap(i, prev); if (i == (n + 1)) return get_cost(i, prev); auto &ret = dp[i][prev]; if (ret >= 0) return ret; ret = MOD; ret = min(ret, get_cost(i, i - 1) + solve_dp(i + 1, prev)); ret = min(ret, get_cost(i, prev) + solve_dp(i + 1, i - 1)); return ret; }; cout << solve_dp(1, 0) << '\n'; } int32_t main() { srand(time(NULL)); #ifndef LOCAL ios_base::sync_with_stdio(0); cin.tie(0); #endif int t = 5; cin >> t; for (int i = 1; i <= t; ++i) solveCase(); return 0; }
21.448529
68
0.41241
[ "vector" ]
b72c7bea1aa9c685434d439179eb4ae1ae48e72a
4,391
cc
C++
test/integration/server_fixture.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
5
2017-07-14T19:36:51.000Z
2020-04-01T06:47:59.000Z
test/integration/server_fixture.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
20
2017-07-20T21:04:49.000Z
2017-10-19T19:32:38.000Z
test/integration/server_fixture.cc
otamachan/ros-indigo-gazebo7-deb
abc6b40247cdce14d9912096a0ad5135d420ce04
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2016 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "gazebo/test/ServerFixture.hh" #include "gazebo/test/helper_physics_generator.hh" using namespace gazebo; class ServerFixtureTest : public ServerFixture, public testing::WithParamInterface<const char*> { public: void LoadPaused(const std::string &_physicsType); public: void LoadEmptyOfType(const std::string &_physicsType); public: void SpawnSDF(const std::string &_physicsType); }; //////////////////////////////////////////////////////////////////////// // LoadPaused: // Verify that ServerFixture can load world in paused state // Gazebo issue #334 //////////////////////////////////////////////////////////////////////// void ServerFixtureTest::LoadPaused(const std::string &_physicsType) { // Note the second argument of Load sets the pause state Load("worlds/empty.world", true, _physicsType); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); gzdbg << "Check IsPaused with no delay\n"; EXPECT_TRUE(world->IsPaused()); common::Time::MSleep(100); gzdbg << "Check IsPaused with 100 ms delay\n"; EXPECT_TRUE(world->IsPaused()); common::Time::MSleep(900); gzdbg << "Check IsPaused with 1000 ms delay\n"; EXPECT_TRUE(world->IsPaused()); } TEST_P(ServerFixtureTest, LoadPaused) { LoadPaused(GetParam()); } //////////////////////////////////////////////////////////////////////// // LoadEmptyOfType: // Verify that ServerFixture can load empty world with different types // of physics engines (issue #486) //////////////////////////////////////////////////////////////////////// void ServerFixtureTest::LoadEmptyOfType(const std::string &_physicsType) { // Note the second argument of Load sets the pause state Load("worlds/empty.world", true, _physicsType); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); physics::PhysicsEnginePtr physics = world->GetPhysicsEngine(); ASSERT_TRUE(physics != NULL); EXPECT_EQ(physics->GetType(), _physicsType); } TEST_P(ServerFixtureTest, LoadEmptyOfType) { LoadEmptyOfType(GetParam()); } //////////////////////////////////////////////////////////////////////// // SpawnSDF: // Verify that the SpawnSDF function does not get stuck in a loop // Gazebo issue #530 //////////////////////////////////////////////////////////////////////// void ServerFixtureTest::SpawnSDF(const std::string &_physicsType) { // Note the second argument of Load sets the pause state Load("worlds/blank.world", true, _physicsType); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); EXPECT_TRUE(world->IsPaused()); std::stringstream sdfStr; math::Pose pose(1, 2, 3, 0, 0, 0); sdfStr << "<sdf version='" << SDF_VERSION << "'>" << "<model name='box'>" << " <pose>" << pose << "</pose>" << " <link name='link'>" << " <collision name='col'>" << " <geometry>" << " <box><size>1 1 1</size></box>" << " </geometry>" << " </collision>" << " <visual name='vis'>" << " <geometry>" << " <box><size>1 1 1</size></box>" << " </geometry>" << " </visual>" << " </link>" << "</model>" << "</sdf>"; ServerFixture::SpawnSDF(sdfStr.str()); physics::ModelPtr model; model = world->GetModel("box"); ASSERT_TRUE(model != NULL); EXPECT_EQ(pose.pos, model->GetWorldPose().pos); } TEST_P(ServerFixtureTest, SpawnSDF) { SpawnSDF(GetParam()); } INSTANTIATE_TEST_CASE_P(PhysicsEngines, ServerFixtureTest, PHYSICS_ENGINE_VALUES); int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
32.768657
75
0.59622
[ "geometry", "model" ]
b72ebf5c6f17cd1ab908b9a57ef4957a3c6421e5
1,090
hpp
C++
Getopt.hpp
jancarlsson/snarkfront
7f90a4181721f758f114497382aa462185e71dae
[ "MIT" ]
60
2015-01-02T12:28:40.000Z
2021-04-13T01:40:07.000Z
Getopt.hpp
artree222/snarkfront
7f90a4181721f758f114497382aa462185e71dae
[ "MIT" ]
8
2015-03-05T13:12:39.000Z
2018-07-03T07:17:45.000Z
Getopt.hpp
artree222/snarkfront
7f90a4181721f758f114497382aa462185e71dae
[ "MIT" ]
17
2015-01-22T03:10:49.000Z
2020-12-27T12:22:17.000Z
#ifndef _SNARKFRONT_GETOPT_HPP_ #define _SNARKFRONT_GETOPT_HPP_ #include <cstdint> #include <map> #include <set> #include <string> #include <vector> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // command line handling // class Getopt { public: Getopt(int argc, char *argv[], const std::string& string_opts, const std::string& number_opts, const std::string& flag_opts); bool operator! () const; bool empty() const; bool valid(const std::string& string_opts, const std::string& number_opts, const std::string& flag_opts); std::string getString(const char c); std::size_t getNumber(const char c); bool getFlag(const char c); const std::vector<std::string>& getArgs() const; private: std::map<int, std::string> m_string; std::map<int, std::size_t> m_number; std::set<int> m_flag, m_string_opts, m_number_opts, m_flag_opts; std::vector<std::string> m_args; bool m_error; }; } // namespace snarkfront #endif
22.244898
80
0.607339
[ "vector" ]
b731155366ded032c06206e10c9975aae7705735
11,205
cpp
C++
spatial/core/resources/cppgen/datastructures/static/DeliteCpp.cpp
dkoeplin/spatial
55e9a67b28f83caf3606e0c7bbead82a12cfbd2a
[ "MIT" ]
107
2017-02-14T03:05:33.000Z
2022-01-05T08:41:15.000Z
spatial/core/resources/cppgen/datastructures/static/DeliteCpp.cpp
dkoeplin/spatial
55e9a67b28f83caf3606e0c7bbead82a12cfbd2a
[ "MIT" ]
258
2017-02-16T08:03:45.000Z
2018-11-30T19:39:37.000Z
spatial/core/resources/cppgen/datastructures/static/DeliteCpp.cpp
dkoeplin/spatial
55e9a67b28f83caf3606e0c7bbead82a12cfbd2a
[ "MIT" ]
15
2017-02-17T01:01:35.000Z
2018-11-24T05:49:49.000Z
#include "DeliteCpp.h" bool regex_metachar(char c) { switch (c) { case '\\': case '^': case '$': case '.': case '|': case '?': case '*': case '+': case '(': case ')': case '[': case '{': return true; default: return false; } } char find_delim(const string &pattern) { if (pattern.length()==1 && !regex_metachar(pattern.at(0))) { return pattern.at(0); } else if (pattern.length()==2 && pattern.at(0)=='\\' && regex_metachar(pattern.at(1))) { return pattern.at(1); } else return -1; } string *growStringArray(const resourceInfo_t *resourceInfo, string *input, int &length) { string *result = new (resourceInfo) string[length * 4]; for(int i=0; i<length; i++) { result[i] = input[i]; } length *= 4; return result; } #ifdef __USE_STD_STRING__ #ifdef MEMMGR_REFCNT std::shared_ptr<cppDeliteArraystring> string_split(const resourceInfo_t *resourceInfo, const string &str, const string &pattern, int32_t lim) { #else cppDeliteArraystring *string_split(const resourceInfo_t *resourceInfo, const string &str, const string &pattern, int32_t lim) { #endif //TODO: current g++ does not fully support c++11 regex, // so below code does not work. /* std::string s(str); std::regex e(pattern.c_str()); std::vector<std::string> *elems = new std::vector<std::string>(); const std::sregex_token_iterator endOfSequence; std::sregex_token_iterator token(s.begin(), s.end(), e, -1); while(token != endOfSequence) { elems->push_back(*token++); std::cout << *token++ << std::endl; } cppDeliteArray<string> *ret = new cppDeliteArray<string>(elems->size()); for(int i=0; i<elems->size(); i++) ret->update(i,elems->at(i)); return ret; */ //Since above code is not working, we currently only support simple regular expressions // http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c std::vector<std::string> elems; int num_tokens = 0; std::string token; std::stringstream ss(str); char delim; if (pattern.compare("\\s+")==0) { while (ss >> token) { num_tokens += 1; if (num_tokens == lim) { std::string remainder; getline(ss, remainder, (char)NULL); elems.push_back(token+remainder); break; } else { elems.push_back(token); } } } else if ((delim = find_delim(pattern)) != -1) { while (getline(ss, token, delim)) { num_tokens += 1; if (num_tokens == lim) { std::string remainder; getline(ss, remainder, (char)NULL); elems.push_back(token+remainder); break; } else { elems.push_back(token); } } } else { assert(false && "Given regex is not supported"); } // remove the trailing empty strings when the limit is 0 if (lim == 0) { while(elems.back().compare("") == 0) { elems.pop_back(); } } //construct cppDeliteArray from vector #ifdef MEMMGR_REFCNT std::shared_ptr<cppDeliteArraystring> ret(new cppDeliteArraystring(elems.size()), cppDeliteArraystringD()); #else cppDeliteArraystring *ret = new cppDeliteArraystring(elems.size()); //cppDeliteArraystring *ret = new cppDeliteArraystring(tokens, num_tokens); #endif #ifdef __USE_STD_STRING__ for(int i=0; i<elems.size(); i++) ret->update(i,elems.at(i)); #else for(int i=0; i<elems.size(); i++) ret->update(i,string(elems.at(i).c_str())); #endif return ret; } #else // of __USE_STD_STRING__ #ifdef MEMMGR_REFCNT std::shared_ptr<cppDeliteArraystring> string_split(const resourceInfo_t *resourceInfo, const string &str, const string &pattern, int32_t lim) { #else cppDeliteArraystring *string_split(const resourceInfo_t *resourceInfo, const string &str, const string &pattern, int32_t lim) { #endif if (lim > 0) assert(false && "string_split with lim > 0 is not implemented yet"); int strarrlen = 8; // default length for tokens array string *tokens = new (resourceInfo) string[strarrlen]; int num_tokens = 0; int length = str.length(); char *strptr = new (resourceInfo) char[length+1]; strcpy(strptr, str.c_str()); char delim; char *savePtr; if (pattern.compare("\\s+")==0) { //NOTE: strtok() is not thread-safe, so use strtok_r() char *ptr = strtok_r(strptr, " \t", &savePtr); while (ptr != NULL) { tokens[num_tokens++] = string(ptr, strlen(ptr), 0); ptr = strtok_r(NULL, " \t", &savePtr); if(num_tokens == strarrlen) { tokens = growStringArray(resourceInfo, tokens, strarrlen); } } } else if ((delim = find_delim(pattern)) != -1) { int offset = 0; for (int i=0; i<length; i++) { if (strptr[i] == delim) { strptr[i] = 0; tokens[num_tokens++] = string(strptr+offset,i-offset,0); offset = i + 1; if(num_tokens == strarrlen) { tokens = growStringArray(resourceInfo, tokens, strarrlen); } } } tokens[num_tokens++] = string(strptr+offset, length-offset, 0); //remove the trailing empty strings when the limit is 0 if (lim == 0) { int i = num_tokens-1; while (tokens[i].length() == 0 && i >= 0) { tokens[i] = string(); i--; } } } else { fprintf(stderr, "regex: %s\n", pattern.c_str()); assert(false && "Given regex is not supported"); } #ifdef MEMMGR_REFCNT std::shared_ptr<cppDeliteArraystring> ret(new cppDeliteArraystring(tokens, num_tokens), cppDeliteArraystringD()); #else cppDeliteArraystring *ret = new cppDeliteArraystring(tokens, num_tokens); #endif return ret; } #endif // of __USE_STD_STRING__ int32_t string_toInt(const string &str) { return atoi(str.c_str()); } float string_toFloat(const string &str) { return strtof(str.c_str(),NULL); } double string_toDouble(const string &str) { return strtod(str.c_str(),NULL); } bool string_toBoolean(const string &str) { string b = str; std::transform(b.begin(), b.end(), b.begin(), ::tolower); if (str.compare("true") == 0) return true; else if (str.compare("false") == 0) return false; else assert(false && "Cannot parse boolean string"); } #ifdef __USE_STD_STRING__ // Code from http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring string &ltrim(string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } string &rtrim(string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } string string_trim(const string &str) { string ret = str; return ltrim(rtrim(ret)); } #else string string_trim(const string &str) { return str.trim(); } #endif int8_t string_charAt(const string &str, int idx) { return str.at(idx); } bool string_startsWith(const string &str, const string &substr) { if (str.compare(0,substr.length(),substr) == 0) return true; else return false; } string string_plus(const string &str1, const string &str2) { return str1 + str2; } string string_substr(const string &str, int32_t offset, int32_t end) { return str.substr(offset,end-offset+1); } string string_substr(const string &str, int32_t offset) { return str.substr(offset); } int32_t string_length(const string &str) { return str.length(); } template<class T> string convert_to_string(T in) { std::ostringstream convert; convert << in; #ifdef __USE_STD_STRING__ return convert.str(); #else return string(convert.str().c_str()); #endif } // Explicit instantiation of template functions to enable separate compilation template string convert_to_string<bool>(bool); template string convert_to_string<int8_t>(int8_t); template string convert_to_string<uint16_t>(uint16_t); template string convert_to_string<int16_t>(int16_t); template string convert_to_string<int32_t>(int32_t); template string convert_to_string<int64_t>(int64_t); template string convert_to_string<float>(float); template string convert_to_string<double>(double); template string convert_to_string<void*>(void*); template<> string convert_to_string<string>(string str) { return str; } string readFirstLineFile(const string &filename) { #ifdef __USE_STD_STRING__ std::ifstream fs(filename.c_str()); std::string line; if (fs.good()) { getline(fs, line); } fs.close(); return line; #else std::ifstream fs(filename.c_str()); std::string line; if (fs.good()) { getline(fs, line); } fs.close(); return string(line.c_str()); #endif } template <class K> uint32_t delite_hashcode(K key) { return key->hashcode(); } template<> uint32_t delite_hashcode<bool>(bool key) { return (uint32_t) key; } template<> uint32_t delite_hashcode<int8_t>(int8_t key) { return (uint32_t) key; } template<> uint32_t delite_hashcode<uint16_t>(uint16_t key) { return (uint32_t) key; } template<> uint32_t delite_hashcode<int32_t>(int32_t key) { return (uint32_t) key; } template<> uint32_t delite_hashcode<int64_t>(int64_t key) { return (uint32_t) key; } template<> uint32_t delite_hashcode<float>(float key) { return (uint32_t) key; } template<> uint32_t delite_hashcode<double>(double key) { return (uint32_t) key; } template<> uint32_t delite_hashcode<string>(string key) { //http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#hashCode%28%29 int32_t multiplier = 1; int32_t hc = 0; int n = key.length(); for(int i=n-1; i>=0; i--) { hc += multiplier * key.at(i); multiplier *= 31; } return (uint32_t)hc; } template <class K> bool delite_equals(K key1, K key2) { return key1->equals(key2); } template<> bool delite_equals<bool>(bool key1, bool key2) { return key1 == key2; } template<> bool delite_equals<int8_t>(int8_t key1, int8_t key2) { return key1 == key2; } template<> bool delite_equals<uint16_t>(uint16_t key1, uint16_t key2) { return key1 == key2; } template<> bool delite_equals<int32_t>(int32_t key1, int32_t key2) { return key1 == key2; } template<> bool delite_equals<int64_t>(int64_t key1, int64_t key2) { return key1 == key2; } template<> bool delite_equals<float>(float key1, float key2) { return key1 == key2; } template<> bool delite_equals<double>(double key1, double key2) { return key1 == key2; } template<> bool delite_equals<string>(string key1, string key2) { return key1.compare(key2) == 0; } template<class T> T cppDeepCopy(const resourceInfo_t *resourceInfo, T in) { assert(false); } void cppDeepCopy(const resourceInfo_t *resourceInfo) { } /* helper methods and data structures only required for execution with Delite */ #ifndef __DELITE_CPP_STANDALONE__ pthread_mutex_t lock_objmap = PTHREAD_MUTEX_INITIALIZER; std::map<int,jobject> *JNIObjectMap = new std::map<int,jobject>(); jobject JNIObjectMap_find(int key) { pthread_mutex_lock (&lock_objmap); jobject ret = JNIObjectMap->find(key)->second; pthread_mutex_unlock (&lock_objmap); return ret; } void JNIObjectMap_insert(int key, jobject value) { pthread_mutex_lock (&lock_objmap); std::map<int,jobject>::iterator it = JNIObjectMap->find(key); if(it != JNIObjectMap->end()) it->second = value; else JNIObjectMap->insert(std::pair<int,jobject>(key,value)); pthread_mutex_unlock (&lock_objmap); } #endif
30.867769
143
0.676484
[ "vector", "transform" ]
b7363f95a5e61c9c9fe70430772a7fc8424339b3
6,803
cpp
C++
apps/src/libvideostitch-gui/widgets/crop/croprectangleeditor.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
1
2022-02-04T20:42:25.000Z
2022-02-04T20:42:25.000Z
apps/src/libvideostitch-gui/widgets/crop/croprectangleeditor.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
null
null
null
apps/src/libvideostitch-gui/widgets/crop/croprectangleeditor.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
1
2021-12-11T07:56:51.000Z
2021-12-11T07:56:51.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "croprectangleeditor.hpp" #include <QMouseEvent> #include <QPainter> CropRectangleEditor::CropRectangleEditor(const QSize thumbnailSize, const QSize frameSize, const Crop &initCrop, QWidget *const parent) : CropShapeEditor(thumbnailSize, frameSize, initCrop, parent) {} void CropRectangleEditor::setDefaultCrop() { Q_ASSERT(getRatio() > 0); shape.setTop(0); shape.setLeft(0); shape.setHeight(thumbnailSize.height()); shape.setWidth(thumbnailSize.width()); update(); } const QRectF CropRectangleEditor::getTopArea(const QRectF rectangle) const { return QRectF(rectangle.left() + SEL_OFFSET, rectangle.top() - SEL_OFFSET, rectangle.width() - PEN_THICK * SEL_OFFSET, 2 * SEL_OFFSET); } const QRectF CropRectangleEditor::getBottomArea(const QRectF rectangle) const { return QRectF(rectangle.left() + SEL_OFFSET, rectangle.bottom() - SEL_OFFSET, rectangle.width() - PEN_THICK * SEL_OFFSET, 2 * SEL_OFFSET); } const QRectF CropRectangleEditor::getLeftArea(const QRectF rectangle) const { return QRectF(rectangle.left() - SEL_OFFSET, rectangle.top() + SEL_OFFSET, 2 * SEL_OFFSET, rectangle.height() - PEN_THICK * SEL_OFFSET); } const QRectF CropRectangleEditor::getRightArea(const QRectF rectangle) const { return QRectF(rectangle.right() - SEL_OFFSET, rectangle.top() + SEL_OFFSET, 2 * SEL_OFFSET, rectangle.height() - PEN_THICK * SEL_OFFSET); } const QRectF CropRectangleEditor::getTopLeftCorner(const QRectF rectangle) const { return QRectF(rectangle.left() - SEL_OFFSET, rectangle.top() - SEL_OFFSET, 2 * SEL_OFFSET, 2 * SEL_OFFSET); } const QRectF CropRectangleEditor::getTopRightCorner(const QRectF rectangle) const { return QRectF(rectangle.right() - SEL_OFFSET, rectangle.top() - SEL_OFFSET, 2 * SEL_OFFSET, 2 * SEL_OFFSET); } const QRectF CropRectangleEditor::getBottomLeftCorner(const QRectF rectangle) const { return QRectF(rectangle.left() - SEL_OFFSET, rectangle.bottom() - SEL_OFFSET, 2 * SEL_OFFSET, 2 * SEL_OFFSET); } const QRectF CropRectangleEditor::getBottomRightCorner(const QRectF rectangle) const { return QRectF(rectangle.right() - SEL_OFFSET, rectangle.bottom() - SEL_OFFSET, 2 * SEL_OFFSET, 2 * SEL_OFFSET); } void CropRectangleEditor::drawCropShape(QPainter &painter) { QPainterPath background; background.setFillRule(Qt::WindingFill); background.addRect(rect()); QPainterPath rectangle; rectangle.addRect(shape); const QPainterPath intersection = background.subtracted(rectangle); painter.setOpacity(opacity); painter.fillPath(intersection, currentFill); painter.setOpacity(1.0); painter.strokePath(rectangle.simplified(), border); } void CropRectangleEditor::mouseMoveEvent(QMouseEvent *event) { if (ignoreEvent) { event->ignore(); return; } switch (modificationMode) { case ModificationMode::NoModification: break; case ModificationMode::ResizeFromTop: shape.setTop(qMin(qreal(event->pos().y()), shape.bottom())); break; case ModificationMode::ResizeFromBottom: shape.setBottom(qMax(qreal(event->pos().y()), shape.top())); break; case ModificationMode::ResizeFromLeft: shape.setLeft(qMin(qreal(event->pos().x()), shape.right())); break; case ModificationMode::ResizeFromRight: shape.setRight(qMax(qreal(event->pos().x()), shape.left())); break; case ModificationMode::ResizeFromTopLeft: shape.setTop(qMin(qreal(event->pos().y()), shape.bottom())); shape.setLeft(qMin(qreal(event->pos().x()), shape.right())); break; case ModificationMode::ResizeFromTopRight: shape.setTop(qMin(qreal(event->pos().y()), shape.bottom())); shape.setRight(qMax(qreal(event->pos().x()), shape.left())); break; case ModificationMode::ResizeFromBottomLeft: shape.setBottom(qMax(qreal(event->pos().y()), shape.top())); shape.setLeft(qMin(qreal(event->pos().x()), shape.right())); break; case ModificationMode::ResizeFromBottomRight: shape.setBottom(qMax(qreal(event->pos().y()), shape.top())); shape.setRight(qMax(qreal(event->pos().x()), shape.left())); break; case ModificationMode::Move: shape.moveCenter(event->pos() - distanceToCenter); break; } if (modificationMode != ModificationMode::NoModification) { update(); emit notifyCropSet(getCrop()); } if (getTopArea(shape).contains(event->pos()) || getBottomArea(shape).contains(event->pos())) { setCursor(QCursor(Qt::CursorShape::SizeVerCursor)); } else if (getLeftArea(shape).contains(event->pos()) || getRightArea(shape).contains(event->pos())) { setCursor(QCursor(Qt::CursorShape::SizeHorCursor)); } else if (getTopLeftCorner(shape).contains(event->pos()) || getBottomRightCorner(shape).contains(event->pos())) { setCursor(QCursor(Qt::CursorShape::SizeFDiagCursor)); } else if (getTopRightCorner(shape).contains(event->pos()) || getBottomLeftCorner(shape).contains(event->pos())) { setCursor(QCursor(Qt::CursorShape::SizeBDiagCursor)); } else if (getCentralArea(shape).contains(event->pos())) { setCursor(QCursor(Qt::CursorShape::SizeAllCursor)); } else { setCursor(QCursor(Qt::CursorShape::ArrowCursor)); } } void CropRectangleEditor::mousePressEvent(QMouseEvent *event) { if (ignoreEvent) { event->ignore(); return; } if (getTopArea(shape).contains(event->pos())) { modificationMode = ModificationMode::ResizeFromTop; } else if (getBottomArea(shape).contains(event->pos())) { modificationMode = ModificationMode::ResizeFromBottom; } else if (getLeftArea(shape).contains(event->pos())) { modificationMode = ModificationMode::ResizeFromLeft; } else if (getRightArea(shape).contains(event->pos())) { modificationMode = ModificationMode::ResizeFromRight; } else if (getTopLeftCorner(shape).contains(event->pos())) { modificationMode = ModificationMode::ResizeFromTopLeft; } else if (getTopRightCorner(shape).contains(event->pos())) { modificationMode = ModificationMode::ResizeFromTopRight; } else if (getBottomLeftCorner(shape).contains(event->pos())) { modificationMode = ModificationMode::ResizeFromBottomLeft; } else if (getBottomRightCorner(shape).contains(event->pos())) { modificationMode = ModificationMode::ResizeFromBottomRight; } else if (getCentralArea(shape).contains(event->pos())) { modificationMode = ModificationMode::Move; distanceToCenter = event->pos() - shape.center(); } } void CropRectangleEditor::mouseReleaseEvent(QMouseEvent *event) { if (ignoreEvent) { event->ignore(); return; } modificationMode = ModificationMode::NoModification; }
40.736527
120
0.710128
[ "shape" ]
b739c34ccd0969e48a980cecebbe95ad0ef374c2
1,222
cpp
C++
L1_Vector/src/main.cpp
JoshuaCrotts/C-Tutorials
01a75a5f23609e4f6c0d725488f6ea486a8076a7
[ "MIT" ]
2
2020-08-19T19:00:30.000Z
2020-08-20T20:50:47.000Z
L1_Vector/src/main.cpp
JoshuaCrotts/Cpp-Tutorials
01a75a5f23609e4f6c0d725488f6ea486a8076a7
[ "MIT" ]
null
null
null
L1_Vector/src/main.cpp
JoshuaCrotts/Cpp-Tutorials
01a75a5f23609e4f6c0d725488f6ea486a8076a7
[ "MIT" ]
null
null
null
#include "../include/commons.hpp" #include "../include/vector.hpp" template <class T> static void printVector( const Vector<T> &v ); template <class T> static void printCapacityAndSize( const Vector<T> &v ); int main( int argc, char *argv[] ) { Vector<int> v; printCapacityAndSize( v ); v.addElement( 10 ); v.addElement( 20 ); v.addElement( 30 ); v.addElement( 17 ); v.addElement( 12 ); v.addElement( 11 ); printCapacityAndSize( v ); printVector( v ); std::cout << "Removing index 1 (should be 20): " << v.removeElement( 1 ) << std::endl; printCapacityAndSize( v ); printVector( v ); std::cout << "Removing index 3 (should be 12): " << v.removeElement( 3 ) << std::endl; printCapacityAndSize( v ); printVector( v ); } /** * Prints the vector. Simple as that. */ template <class T> static void printVector( const Vector<T> &v ) { for ( int i = 0; i < v.getSize(); i++ ) { std::cout << "Index: " << i << ": " << v.getElement( i ) << std::endl; } } /** * Prints the logical size and capacity of the vector. */ template <class T> static void printCapacityAndSize( const Vector<T> &v ) { std::cout << "Capacity: " << v.getCapacity() << ", Size: " << v.getSize() << std::endl; }
27.155556
89
0.620295
[ "vector" ]
b747090e7ff69f743a62e25fca8c48900fba7a2c
5,690
cpp
C++
gcodejam/2021/quals/B/B.cpp
mathemage/CompetitiveProgramming
fe39017e3b017f9259f9c1e6385549270940be64
[ "MIT" ]
2
2015-08-18T09:51:19.000Z
2019-01-29T03:18:10.000Z
gcodejam/2021/quals/B/B.cpp
mathemage/CompetitiveProgramming
fe39017e3b017f9259f9c1e6385549270940be64
[ "MIT" ]
null
null
null
gcodejam/2021/quals/B/B.cpp
mathemage/CompetitiveProgramming
fe39017e3b017f9259f9c1e6385549270940be64
[ "MIT" ]
null
null
null
/* ======================================== * File Name : B.cpp * Creation Date : 26-03-2021 * Last Modified : Sat 27 Mar 2021 08:29:31 PM CET * Created By : Karel Ha <mathemage@gmail.com> * URL : https://codingcompetitions.withgoogle.com/codejam/round/000000000043580a/00000000006d1145 * Points/Time : * 1h * +1h19m10s = 2h19m10s :-/ * * Total/ETA : 5+11+1pts ~40m * Status : * AC (the 2 visible testsets) * + WA (hidden testset) :-/ * ==========================================*/ #include <algorithm> #include <bits/stdc++.h> #include <string> using namespace std; #define endl "\n" #define REP(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) #define ALL(A) (A).begin(), (A).end() #define REVALL(A) (A).rbegin(), (A).rend() #define F first #define S second #define PB push_back #define MP make_pair #define MTP make_tuple #define MINUPDATE(A,B) A = min((A), (B)); #define MAXUPDATE(A,B) A = max((A), (B)); #define SGN(X) ((X) ? ( (X)>0?1:-1 ) : 0) #define CONTAINS(S,E) ((S).find(E) != (S).end()) #define SZ(x) ((int) (x).size()) #ifdef ONLINE_JUDGE #undef MATHEMAGE_DEBUG #endif #ifdef MATHEMAGE_DEBUG #define MSG(a) cerr << "> " << (#a) << ": " << (a) << endl; #define MSG_VEC_VEC(v) cerr << "> " << (#v) << ":\n" << (v) << endl; #define MSG_VEC_PAIRS(v) print_vector_pairs((v), (#v)); #define LINESEP1 cerr << "----------------------------------------------- " << endl; #define LINESEP2 cerr << "_________________________________________________________________" << endl; #else #define MSG(a) #define MSG_VEC_VEC(v) #define MSG_VEC_PAIRS(v) #define LINESEP1 #define LINESEP2 #endif ostream& operator<<(ostream& os, const vector<string> & vec) { os << endl; for (const auto & s: vec) cerr << s << endl; return os; } template<typename T> ostream& operator<<(ostream& os, const vector<T> & vec) { for (const auto & x: vec) os << x << " "; return os; } template<typename T> ostream& operator<<(ostream& os, const vector<vector<T>> & vec) { for (const auto & v: vec) os << v << endl; return os; } template<typename T> ostream& operator<<(ostream& os, const set<T>& vec) { os << "{ | "; for (const auto & x: vec) os << x << "| "; os << "}"; return os; } template<typename T1, typename T2> void print_vector_pairs(const vector<pair<T1, T2>> & vec, const string & name) { cerr << "> " << name << ": "; for (const auto & x: vec) cerr << "(" << x.F << ", " << x.S << ")\t"; cerr << endl; } template<typename T> inline bool bounded(const T & x, const T & u, const T & l=0) { return min(l,u)<=x && x<max(l,u); } const int CLEAN = -1; // const int UNDEF = -42; const char UNDEF = '_'; const long long MOD = 1000000007; const double EPS = 1e-8; const int INF = INT_MAX; const long long INF_LL = LLONG_MAX; const long long INF_ULL = ULLONG_MAX; const vector<int> DX4 = { 0, 0, -1, 1}; const vector<int> DY4 = {-1, 1, 0, 0}; const vector<pair<int,int>> DXY4 = { {0,-1}, {0,1}, {-1,0}, {1,0} }; const vector<int> DX8 = {-1, -1, -1, 0, 0, 1, 1, 1}; const vector<int> DY8 = {-1, 0, 1, -1, 1, -1, 0, 1}; const vector<pair<int,int>> DXY8 = { {-1,-1}, {-1,0}, {-1,1}, { 0,-1}, { 0,1}, { 1,-1}, { 1,0}, { 1,1} }; void solve() { int x,y; string s; cin >> x >> y >> s; MSG(s); vector<string> options = {"CC", "JJ", "CJ", "JC"}; map<string, int> cost; cost["CC"] = cost["JJ"] = 0; cost["CJ"] = x; cost["JC"] = y; map<string, char> prevChar; // for (auto & opt: options) prevChar[opt]=UNDEF; for (auto & opt: options) prevChar[opt]=opt[0]; map<string, int> deltas; int n=s.size(); int result = 0; int delta; string key; FOR(pos,1,n-1) { LINESEP1; // MSG(pos-1); MSG(pos); MSG(s.substr(pos-1)); MSG(s[pos-1]); MSG(s[pos]); if (s[pos]=='?') { LINESEP1; MSG(prevChar["CC"]) MSG(prevChar["JJ"]) MSG(prevChar["CJ"]) MSG(prevChar["JC"]); if (s[pos-1]=='?') { // ?? for (auto & opt: {"CJ", "JC"} ) { s[pos-1]=opt[0]; s[pos]=opt[1]; deltas[opt] += cost[s.substr(pos-1,2)]; prevChar[opt]^='C'^'J'; } s[pos-1]='?'; } else { // C? or J? for (auto & opt: options) { s[pos]=opt[0]; deltas[opt] += cost[s.substr(pos-1,2)]; prevChar[opt]=opt[0]; } } s[pos]='?'; LINESEP1; MSG(prevChar["CC"]) MSG(prevChar["JJ"]) MSG(prevChar["CJ"]) MSG(prevChar["JC"]); MSG(deltas["CC"]) MSG(deltas["JJ"]) MSG(deltas["CJ"]) MSG(deltas["JC"]); if (pos==n-1) { result+=min( min(deltas["CC"], deltas["JJ"]), min(deltas["CJ"], deltas["JC"]) ); } } else { // J or C if (s[pos-1]=='?') { // ?C or ?J MSG(prevChar["CC"]) MSG(prevChar["JJ"]) MSG(prevChar["CJ"]) MSG(prevChar["JC"]); for (auto & opt: options) { s[pos-1]=prevChar[opt]; deltas[opt] += cost[s.substr(pos-1,2)]; } delta=min( min(deltas["CC"], deltas["JJ"]), min(deltas["CJ"], deltas["JC"]) ); MSG(deltas["CC"]) MSG(deltas["JJ"]) MSG(deltas["CJ"]) MSG(deltas["JC"]) deltas["CC"]=deltas["JJ"]=deltas["CJ"]=deltas["JC"]=0; s[pos-1]='?'; } else { delta=cost[s.substr(pos-1,2)]; } MSG(delta); result += delta; } MSG(result); } cout << result << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int cases = 1; cin >> cases; REP(i,cases) { cout << "Case #" << i+1 << ": "; solve(); LINESEP2; } return 0; }
26.465116
103
0.520211
[ "vector" ]
b7483566cd5126225050f907d7557ff17b964c00
396
cpp
C++
tutorials/zetcode/02_strings/01_simple_methods/simple_methods.cpp
ASHellos/CS311
c23802f7ab587f69c6a3ba95c9d220d52e1a085e
[ "MIT" ]
null
null
null
tutorials/zetcode/02_strings/01_simple_methods/simple_methods.cpp
ASHellos/CS311
c23802f7ab587f69c6a3ba95c9d220d52e1a085e
[ "MIT" ]
null
null
null
tutorials/zetcode/02_strings/01_simple_methods/simple_methods.cpp
ASHellos/CS311
c23802f7ab587f69c6a3ba95c9d220d52e1a085e
[ "MIT" ]
4
2021-11-06T17:00:00.000Z
2021-12-18T14:51:04.000Z
#include <QTextStream> #include <iostream> #include <vector> using entry = std::pair<QString, int> int main() { //Initialiasing a strea on stdout QTextStream out(stdout); QString temp("Welcome %1 This your %2 th login"); vector<entry> values {{"Hafsa", 2},{"Khadija", 10}, {"Rim", 20}}; out << temp.arg("Class").arg(4).mid(4, 5) << '\n'; return 0; }
12.375
69
0.583333
[ "vector" ]
b74b8e9b5aaf28b92554adbbc2db4e8b4e4a862b
8,059
cc
C++
cpp/test/test_mp_values.cc
waffle-iron/Cap
c3e1f585177211bdd5b8cd4637291d659738eb41
[ "BSD-3-Clause" ]
null
null
null
cpp/test/test_mp_values.cc
waffle-iron/Cap
c3e1f585177211bdd5b8cd4637291d659738eb41
[ "BSD-3-Clause" ]
null
null
null
cpp/test/test_mp_values.cc
waffle-iron/Cap
c3e1f585177211bdd5b8cd4637291d659738eb41
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2016, the Cap authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE MaterialPropertyValues #include "main.cc" #include <cap/geometry.h> #include <cap/mp_values.h> #include <boost/property_tree/ptree.hpp> #include <boost/test/unit_test.hpp> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/dofs/dof_handler.h> BOOST_AUTO_TEST_CASE(test_mp_values_throw) { std::shared_ptr<boost::property_tree::ptree> empty_database; std::shared_ptr<cap::MPValues<2>> mp_values = std::make_shared<cap::MPValues<2>>( cap::MPValuesParameters<2>(empty_database)); dealii::Triangulation<2> triangulation; dealii::GridGenerator::hyper_cube(triangulation); dealii::DoFHandler<2> dof_handler(triangulation); dealii::DoFHandler<2>::active_cell_iterator cell = dof_handler.begin_active(); std::vector<double> values; std::vector<dealii::Tensor<1, 2>> vectors; BOOST_CHECK_THROW(mp_values->get_values("key", cell, values), std::runtime_error); BOOST_CHECK_THROW(mp_values->get_values("key", cell, vectors), std::runtime_error); } BOOST_AUTO_TEST_CASE(test_mp_values) { // Fill in the geometry database std::shared_ptr<boost::property_tree::ptree> geometry_database( new boost::property_tree::ptree()); boost::property_tree::ptree material_0_database; material_0_database.put("name", "anode"); material_0_database.put("material_id", 1); boost::property_tree::ptree material_1_database; material_1_database.put("name", "separator"); material_1_database.put("material_id", 2); boost::property_tree::ptree material_2_database; material_2_database.put("name", "cathode"); material_2_database.put("material_id", 3); boost::property_tree::ptree material_3_database; material_3_database.put("name", "collector"); material_3_database.put("material_id", 4); geometry_database->put("type", "file"); geometry_database->put("mesh_file", "mesh_2d.ucd"); geometry_database->put("anode_collector_thickness", 5.0e-4); geometry_database->put("anode_electrode_thickness", 50.0e-4); geometry_database->put("separator_thickness", 25.0e-4); geometry_database->put("cathode_electrode_thickness", 50.0e-4); geometry_database->put("cathode_collector_thickness", 5.0e-4); geometry_database->put("geometric_area", 25.0e-2); geometry_database->put("tab_height", 5.0e-4); geometry_database->put("materials", 4); geometry_database->put("anode_collector_material_id", 4); geometry_database->put("anode_electrode_material_id", 1); geometry_database->put("separator_material_id", 2); geometry_database->put("cathode_electrode_material_id", 3); geometry_database->put("cathode_collector_material_id", 5); geometry_database->put_child("material_0", material_0_database); geometry_database->put_child("material_1", material_1_database); geometry_database->put_child("material_2", material_2_database); geometry_database->put_child("material_3", material_3_database); geometry_database->put("boundary_values.anode_boundary_id", "1"); geometry_database->put("boundary_values.cathode_boundary_id", "2"); std::shared_ptr<cap::Geometry<2>> geometry = std::make_shared<cap::Geometry<2>>(geometry_database, boost::mpi::communicator()); // Fill in the material properties database std::shared_ptr<boost::property_tree::ptree> material_properties_database( new boost::property_tree::ptree()); boost::property_tree::ptree anode_database; anode_database.put("type", "porous_electrode"); anode_database.put("matrix_phase", "electrode_material"); anode_database.put("solution_phase", "electrolyte"); boost::property_tree::ptree cathode_database; cathode_database.put("type", "porous_electrode"); cathode_database.put("matrix_phase", "electrode_material"); cathode_database.put("solution_phase", "electrolyte"); boost::property_tree::ptree separator_database; separator_database.put("type", "permeable_membrane"); separator_database.put("matrix_phase", "separator_material"); separator_database.put("solution_phase", "electrolyte"); boost::property_tree::ptree collector_database; collector_database.put("type", "current_collector"); collector_database.put("metal_foil", "collector_material"); boost::property_tree::ptree separator_material_database; separator_material_database.put("void_volume_fraction", 0.6); separator_material_database.put("tortuosity_factor", 1.29); separator_material_database.put("pores_characteristic_dimension", 1.5e-7); separator_material_database.put("pores_geometry_factor", 2.0); separator_material_database.put("mass_density", 3.2); separator_material_database.put("heat_capacity", 1.2528e3); separator_material_database.put("thermal_conductivity", 0.0019e2); boost::property_tree::ptree electrode_material_database; electrode_material_database.put("differential_capacitance", 3.134); electrode_material_database.put("exchange_current_density", 7.463e-10); electrode_material_database.put("void_volume_fraction", 0.67); electrode_material_database.put("tortuosity_factor", 2.3); electrode_material_database.put("pores_characteristic_dimension", 1.5e-7); electrode_material_database.put("pores_geometry_factor", 2.0); electrode_material_database.put("mass_density", 2.3); electrode_material_database.put("electrical_resistivity", 1.92); electrode_material_database.put("heat_capacity", 0.93e3); electrode_material_database.put("thermal_conductivity", 0.0011e2); boost::property_tree::ptree collector_material_database; collector_material_database.put("mass_density", 2.7); collector_material_database.put("electrical_resistivity", 28.2e-7); collector_material_database.put("heat_capacity", 2.7e3); collector_material_database.put("thermal_conductivity", 237.0); boost::property_tree::ptree electrolyte_database; electrolyte_database.put("mass_density", 1.2); electrolyte_database.put("electrical_resistivity", 1.49e3); electrolyte_database.put("heat_capacity", 0.0); electrolyte_database.put("thermal_conductivity", 0.0); material_properties_database->put_child("anode", anode_database); material_properties_database->put_child("cathode", cathode_database); material_properties_database->put_child("separator", separator_database); material_properties_database->put_child("collector", collector_database); material_properties_database->put_child("separator_material", separator_material_database); material_properties_database->put_child("electrode_material", electrode_material_database); material_properties_database->put_child("collector_material", collector_material_database); material_properties_database->put_child("electrolyte", electrolyte_database); cap::MPValuesParameters<2> params(material_properties_database); params.geometry = geometry; std::shared_ptr<cap::MPValues<2>> mp_values = std::make_shared<cap::MPValues<2>>(params); dealii::DoFHandler<2> dof_handler(*(geometry->get_triangulation())); dealii::DoFHandler<2>::active_cell_iterator cell = dof_handler.begin_active(); std::vector<double> values(1); double const tolerance = 1e-2; mp_values->get_values("density", cell, values); BOOST_TEST(values[0] == 1563.); mp_values->get_values("solid_electrical_conductivity", cell, values); BOOST_TEST(std::abs(values[0] - 17.1785) < tolerance); // Move to another material for (unsigned int i = 0; i < 300; ++i) ++cell; mp_values->get_values("density", cell, values); BOOST_TEST(values[0] == 2000.); mp_values->get_values("solid_electrical_conductivity", cell, values); BOOST_TEST(std::abs(values[0]) == 0.); }
44.772222
80
0.756918
[ "geometry", "vector" ]
b74ef43d5ab009ba02df542d76b643b8db1e3095
16,245
cxx
C++
PHOS/PHOSrec/AliPHOSTrackSegmentMakerv2.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
PHOS/PHOSrec/AliPHOSTrackSegmentMakerv2.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
PHOS/PHOSrec/AliPHOSTrackSegmentMakerv2.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /* History of cvs commits: * * $Log$ * Revision 1.6 2007/08/22 09:20:50 hristov * Updated QA classes (Yves) * * Revision 1.5 2007/07/11 13:43:30 hristov * New class AliESDEvent, backward compatibility with the old AliESD (Christian) * * Revision 1.4 2007/05/04 14:49:29 policheh * AliPHOSRecPoint inheritance from AliCluster * * Revision 1.3 2007/04/25 19:39:42 kharlov * Track extracpolation improved * * Revision 1.2 2007/04/01 19:16:52 kharlov * D.P.: Produce EMCTrackSegments using TPC/ITS tracks (no CPV) * * */ //_________________________________________________________________________ // Implementation version 2 of algorithm class to construct PHOS track segments // Track segment for PHOS is list of // EMC RecPoint + (possibly) projection of TPC track // To find TrackSegments we do the following: // for each EMC RecPoints we look at // TPC projections radius fRtpc. // If there is such a track // we make "Link" it is just indexes of EMC and TPC track and distance // between them in the PHOS plane. // Then we sort "Links" and starting from the // least "Link" pointing to the unassined EMC and TPC assing them to // new TrackSegment. // If there is no TPC track we make TrackSegment // consisting from EMC alone. There is no TrackSegments without EMC RecPoint. //// In principle this class should be called from AliPHOSReconstructor, but // one can use it as well in standalone mode. // Use case: // root [0] AliPHOSTrackSegmentMakerv2 * t = new AliPHOSTrackSegmentMaker("galice.root", "tracksegmentsname", "recpointsname") // Warning in <TDatabasePDG::TDatabasePDG>: object already instantiated // // reads gAlice from header file "galice.root", uses recpoints stored in the branch names "recpointsname" (default = "Default") // // and saves recpoints in branch named "tracksegmentsname" (default = "recpointsname") // root [1] t->ExecuteTask() // root [3] t->SetTrackSegmentsBranch("max distance 5 cm") // root [4] t->ExecuteTask("deb all time") // //*-- Author: Dmitri Peressounko (RRC Ki & SUBATECH) & Yves Schutz (SUBATECH) // // --- ROOT system --- #include "TFile.h" #include "TTree.h" #include "TBenchmark.h" // --- Standard library --- #include "Riostream.h" // --- AliRoot header files --- #include "AliPHOSGeometry.h" #include "AliPHOSTrackSegmentMakerv2.h" #include "AliPHOSTrackSegment.h" #include "AliPHOSLink.h" #include "AliPHOSEmcRecPoint.h" #include "AliPHOSCpvRecPoint.h" #include "AliESDEvent.h" #include "AliESDtrack.h" ClassImp( AliPHOSTrackSegmentMakerv2) //____________________________________________________________________________ AliPHOSTrackSegmentMakerv2::AliPHOSTrackSegmentMakerv2() : AliPHOSTrackSegmentMaker(), fDefaultInit(kTRUE), fWrite(kFALSE), fNTrackSegments(0), fRtpc(0.f), fVtx(0.,0.,0.), fLinkUpArray(0), fTPCtracks(), fEmcFirst(0), fEmcLast(0), fModule(0), fTrackSegments(NULL) { // default ctor (to be used mainly by Streamer) for(Int_t i=0; i<5; i++)fNtpcTracks[i]=0 ; InitParameters() ; } //____________________________________________________________________________ AliPHOSTrackSegmentMakerv2::AliPHOSTrackSegmentMakerv2(AliPHOSGeometry *geom) : AliPHOSTrackSegmentMaker(geom), fDefaultInit(kFALSE), fWrite(kFALSE), fNTrackSegments(0), fRtpc(0.f), fVtx(0.,0.,0.), fLinkUpArray(0), fTPCtracks(), fEmcFirst(0), fEmcLast(0), fModule(0), fTrackSegments(NULL) { // ctor for(Int_t i=0; i<5; i++)fNtpcTracks[i]=0 ; InitParameters() ; Init() ; fESD = 0; } //____________________________________________________________________________ AliPHOSTrackSegmentMakerv2::AliPHOSTrackSegmentMakerv2(const AliPHOSTrackSegmentMakerv2 & tsm) : AliPHOSTrackSegmentMaker(tsm), fDefaultInit(kFALSE), fWrite(kFALSE), fNTrackSegments(0), fRtpc(0.f), fVtx(0.,0.,0.), fLinkUpArray(0), fTPCtracks(), fEmcFirst(0), fEmcLast(0), fModule(0), fTrackSegments(NULL) { // cpy ctor: no implementation yet // requested by the Coding Convention Fatal("cpy ctor", "not implemented") ; } //____________________________________________________________________________ AliPHOSTrackSegmentMakerv2::~AliPHOSTrackSegmentMakerv2() { // dtor // fDefaultInit = kTRUE if TrackSegmentMaker created by default ctor (to get just the parameters) if (!fDefaultInit) delete fLinkUpArray ; if (fTrackSegments) { fTrackSegments->Delete(); delete fTrackSegments; } } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::FillOneModule() { // Finds first and last indexes between which // clusters from one PHOS module are //First EMC clusters Int_t totalEmc = fEMCRecPoints->GetEntriesFast() ; for(fEmcFirst = fEmcLast; (fEmcLast < totalEmc) && ((static_cast<AliPHOSRecPoint *>(fEMCRecPoints->At(fEmcLast)))->GetPHOSMod() == fModule ); fEmcLast ++) ; //Now TPC tracks if(fESD){ //Do it ones, only first time if(fModule==1){ Int_t nTracks = fESD->GetNumberOfTracks(); Int_t nPHOSmod = fGeom->GetNModules() ; if(fTPCtracks[0].size()<(UInt_t)nTracks){ for(Int_t i=0; i<nPHOSmod; i++) fTPCtracks[i].resize(nTracks) ; } for(Int_t i=0; i<5; i++)fNtpcTracks[i]=0 ; TVector3 inPHOS ; //In this particular case we use fixed vertex position at zero Double_t vtx[3]={0.,0.,0.} ; AliESDtrack *track; Double_t xyz[3] ; Double_t rEMC = fGeom->GetIPtoCrystalSurface() ; //Use here ideal geometry for (Int_t iTrack=0; iTrack<nTracks; iTrack++) { track = fESD->GetTrack(iTrack); for(Int_t iTestMod=1; iTestMod<=nPHOSmod; iTestMod++){ Double_t modAngle=270.+fGeom->GetPHOSAngle(iTestMod) ; modAngle*=TMath::Pi()/180. ; track->Rotate(modAngle); if (!track->GetXYZAt(rEMC, fESD->GetMagneticField(), xyz)) continue; //track coord on the cylinder of PHOS radius if ((TMath::Abs(xyz[0])+TMath::Abs(xyz[1])+TMath::Abs(xyz[2]))<=0) continue; //Check if this track hits PHOS inPHOS.SetXYZ(xyz[0],xyz[1],xyz[2]); Int_t modNum ; Double_t x,z ; fGeom->ImpactOnEmc(vtx, inPHOS.Theta(), inPHOS.Phi(), modNum, z, x) ; if(modNum==iTestMod){ //Mark this track as one belonging to module TrackInPHOS_t &t = fTPCtracks[modNum-1][fNtpcTracks[modNum-1]++] ; t.track = track ; t.x = x ; t.z = z ; break ; } } } } } } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::GetDistanceInPHOSPlane(AliPHOSEmcRecPoint * emcClu, AliESDtrack *track, Float_t &dx, Float_t &dz) const { // Calculates the distance between the EMC RecPoint and the CPV RecPoint // Clusters are sorted in "rows" and "columns" of width 1 cm TVector3 emcGlobal; // Global position of the EMC recpoint fGeom->GetGlobalPHOS((AliPHOSRecPoint*)emcClu,emcGlobal); //Calculate actual distance to the PHOS surface Double_t modAngle=270.+fGeom->GetPHOSAngle(emcClu->GetPHOSMod()) ; modAngle*=TMath::Pi()/180. ; Double_t rEMC = emcGlobal.X()*TMath::Cos(modAngle)+emcGlobal.Y()*TMath::Sin(modAngle) ; track->Rotate(modAngle); Double_t xyz[3] ; if(!track->GetXYZAt(rEMC, fESD->GetMagneticField(), xyz)){ dx=999. ; dz=999. ; return ; //track coord on the cylinder of PHOS radius } if((TMath::Abs(xyz[0])+TMath::Abs(xyz[1])+TMath::Abs(xyz[2]))<=0){ dx=999. ; dz=999. ; return ; } dx=(emcGlobal.X()-xyz[0])*TMath::Sin(modAngle)-(emcGlobal.Y()-xyz[1])*TMath::Cos(modAngle) ; dx=TMath::Sign(dx,(Float_t)(emcGlobal.X()-xyz[0])) ; //set direction dz=emcGlobal.Z()-xyz[2] ; return ; } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::Init() { // Make all memory allocations that are not possible in default constructor fLinkUpArray = new TClonesArray("AliPHOSLink", 1000); fTrackSegments = new TClonesArray("AliPHOSTrackSegment",100); } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::InitParameters() { //Initializes parameters fRtpc = 4. ; fEmcFirst = 0 ; fEmcLast = 0 ; fLinkUpArray = 0 ; fWrite = kTRUE ; } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::MakeLinks() { // Finds distances (links) between all EMC and CPV clusters, // which are not further apart from each other than fRcpv // and sort them in accordance with this distance fLinkUpArray->Clear() ; AliPHOSEmcRecPoint * emcclu ; Int_t iLinkUp = 0 ; Int_t iEmcRP; for(iEmcRP = fEmcFirst; iEmcRP < fEmcLast; iEmcRP++ ) { emcclu = static_cast<AliPHOSEmcRecPoint *>(fEMCRecPoints->At(iEmcRP)) ; TVector3 vecEmc ; emcclu->GetLocalPosition(vecEmc) ; Int_t mod=emcclu->GetPHOSMod() ; for(Int_t itr=0; itr<fNtpcTracks[mod-1] ; itr++){ TrackInPHOS_t &t = fTPCtracks[mod-1][itr] ; //calculate raw distance Double_t rawdx = t.x - vecEmc.X() ; Double_t rawdz = t.z - vecEmc.Z() ; if(TMath::Sqrt(rawdx*rawdx+rawdz*rawdz)<fRtpc){ Float_t dx,dz ; //calculate presize difference accounting misalignment GetDistanceInPHOSPlane(emcclu, t.track, dx,dz) ; Int_t itrack = t.track->GetID() ; new ((*fLinkUpArray)[iLinkUp++]) AliPHOSLink(dx, dz, iEmcRP, itrack, -1) ; } } } fLinkUpArray->Sort() ; //first links with smallest distances } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::MakePairs() { // Using the previously made list of "links", we found the smallest link - i.e. // link with the least distance between EMC and CPV and pointing to still // unassigned RecParticles. We assign these RecPoints to TrackSegment and // remove them from the list of "unassigned". //Make arrays to mark clusters already chosen Int_t * emcExist = 0; if(fEmcLast > fEmcFirst) emcExist = new Int_t[fEmcLast-fEmcFirst] ; else AliFatal(Form("fEmcLast > fEmcFirst: %d > %d is not true!",fEmcLast,fEmcFirst)); Int_t index; for(index = 0; index <fEmcLast-fEmcFirst; index ++) emcExist[index] = 1 ; Bool_t * tpcExist = 0; Int_t nTracks = fESD->GetNumberOfTracks(); if(nTracks>0) tpcExist = new Bool_t[nTracks] ; for(index = 0; index <nTracks; index ++) tpcExist[index] = 1 ; // Finds the smallest links and makes pairs of CPV and EMC clusters with smallest distance TIter nextUp(fLinkUpArray) ; AliPHOSLink * linkUp ; AliPHOSCpvRecPoint * nullpointer = 0 ; while ( (linkUp = static_cast<AliPHOSLink *>(nextUp()) ) ){ if(emcExist[linkUp->GetEmc()-fEmcFirst] != -1){ if(tpcExist[linkUp->GetCpv()]){ //Track still exist Float_t dx,dz ; linkUp->GetXZ(dx,dz) ; new ((* fTrackSegments)[fNTrackSegments]) AliPHOSTrackSegment(static_cast<AliPHOSEmcRecPoint *>(fEMCRecPoints->At(linkUp->GetEmc())) , nullpointer, linkUp->GetTrack(),dx,dz) ; (static_cast<AliPHOSTrackSegment *>(fTrackSegments->At(fNTrackSegments)))->SetIndexInList(fNTrackSegments); fNTrackSegments++ ; emcExist[linkUp->GetEmc()-fEmcFirst] = -1 ; //Mark emc that Cpv was found //mark track as already used tpcExist[linkUp->GetCpv()] = kFALSE ; } //if CpvUp still exist } } //look through emc recPoints left without CPV if(emcExist){ //if there is emc rec point Int_t iEmcRP ; for(iEmcRP = 0; iEmcRP < fEmcLast-fEmcFirst ; iEmcRP++ ){ if(emcExist[iEmcRP] > 0 ){ new ((*fTrackSegments)[fNTrackSegments]) AliPHOSTrackSegment(static_cast<AliPHOSEmcRecPoint *>(fEMCRecPoints->At(iEmcRP+fEmcFirst)), nullpointer) ; (static_cast<AliPHOSTrackSegment *>(fTrackSegments->At(fNTrackSegments)))->SetIndexInList(fNTrackSegments); fNTrackSegments++; } } } delete [] emcExist ; delete [] tpcExist ; } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::Clusters2TrackSegments(Option_t *option) { // Steering method to perform track segment construction for events // in the range from fFirstEvent to fLastEvent. // This range is optionally set by SetEventRange(). // if fLastEvent=-1 (by default), then process events until the end. if(strstr(option,"tim")) gBenchmark->Start("PHOSTSMaker"); if(strstr(option,"print")) { Print() ; return ; } //Make some initializations fNTrackSegments = 0 ; fEmcFirst = 0 ; fEmcLast = 0 ; fTrackSegments->Clear(); // if(!ReadRecPoints(ievent)) continue; //reads RecPoints for event ievent for(fModule = 1; fModule <= fGeom->GetNModules() ; fModule++ ) { FillOneModule() ; MakeLinks() ; MakePairs() ; } if(strstr(option,"deb")) PrintTrackSegments(option); if(strstr(option,"tim")){ gBenchmark->Stop("PHOSTSMaker"); Info("Exec", "took %f seconds for making TS", gBenchmark->GetCpuTime("PHOSTSMaker")); } } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::Print(const Option_t *)const { // Print TrackSegmentMaker parameters TString message("") ; if( strcmp(GetName(), "") != 0 ) { message = "\n======== AliPHOSTrackSegmentMakerv2 ========\n" ; message += "Making Track segments\n" ; message += "with parameters:\n" ; message += " Maximal EMC - TPC distance (cm) %f\n" ; message += "============================================\n" ; Info("Print", message.Data(),fRtpc) ; } else Info("Print", "AliPHOSTrackSegmentMakerv2 not initialized ") ; } //____________________________________________________________________________ void AliPHOSTrackSegmentMakerv2::PrintTrackSegments(Option_t * option) { // option deb - prints # of found TrackSegments // option deb all - prints as well indexed of found RecParticles assigned to the TS Info("PrintTrackSegments", "Results from TrackSegmentMaker:") ; printf(" Found %d TrackSegments\n", fTrackSegments->GetEntriesFast() ); if(strstr(option,"all")) { // printing found TS printf("TrackSegment # EMC RP# CPV RP#\n") ; Int_t index; for (index = 0 ; index <fTrackSegments->GetEntriesFast() ; index++) { AliPHOSTrackSegment * ts = (AliPHOSTrackSegment * )fTrackSegments->At(index) ; printf(" %d %d %d \n", ts->GetIndexInList(), ts->GetEmcIndex(), ts->GetTrackIndex() ) ; } } }
34.56383
144
0.654786
[ "geometry", "object" ]
b753bb9d84e923b35a6254a378cbd01356477fd4
8,642
cpp
C++
Engine/src/Audio/AudioSystem.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
1
2021-07-24T03:10:38.000Z
2021-07-24T03:10:38.000Z
Engine/src/Audio/AudioSystem.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
null
null
null
Engine/src/Audio/AudioSystem.cpp
Proyecto03/Motor
9e7f379f1f64bc911293434fdfb8aa18bb8f99ab
[ "MIT" ]
2
2021-05-11T10:47:37.000Z
2021-07-24T03:10:39.000Z
#include "AudioSystem.h" #include <vector> #include <iostream> #include "Vector3.h" #include <math.h> #include <chrono> #include <thread> #include "checkML.h" AudioSystem* AudioSystem::instance_ = nullptr; AudioSystem* AudioSystem::getInstance() { return instance_; } bool AudioSystem::setupInstance() { if (instance_ == nullptr) { try { instance_ = new AudioSystem(); } catch (...) { return false; } } return true; } void AudioSystem::clean() { } void AudioSystem::destroy() { instance_->clean(); delete instance_; } AudioSystem::AudioSystem() { mpSystem = NULL; errorCheck(FMOD::System_Create(&mpSystem)); errorCheck(mpSystem->init(512, FMOD_INIT_NORMAL, nullptr)); init(); } AudioSystem::~AudioSystem() { errorCheck(mpSystem->close()); errorCheck(mpSystem->release()); } void AudioSystem::update() { std::vector<ChannelMap::iterator> pStoppedChannels; for (auto it = instance_->mChannels.begin(), itEnd = instance_->mChannels.end(); it != itEnd; ++it) { bool bIsPlaying = false; it->second->isPlaying(&bIsPlaying); if (!bIsPlaying) { pStoppedChannels.push_back(it); } } for (auto& it : pStoppedChannels) { instance_->mChannels.erase(it); } errorCheck(instance_->mpSystem->update()); } AudioSystem::SoundMap& AudioSystem::getSoundMap() { return mSounds; } const AudioSystem::SoundMap& AudioSystem::getSoundMap() const { return mSounds; } AudioSystem::ChannelMap& AudioSystem::getSoundChannels() { return mChannels; } const AudioSystem::ChannelMap& AudioSystem::getSoundChannels() const { return mChannels; } AudioSystem::ChannelGroupMap& AudioSystem::getChanGroupMap() { return mGroup; } const AudioSystem::ChannelGroupMap& AudioSystem::getChanGroupMap() const { return mGroup; } FMOD::System* AudioSystem::getSystem() { return mpSystem; } FMOD::System* AudioSystem::getSystem() const { return mpSystem; } int& AudioSystem::getNextChannelId() { return mnNextChannelId; } const int& AudioSystem::getNextChannelId() const { return mnNextChannelId; } void AudioSystem::init() { } //Comprueba si hay un error en la ejecucion de comando fmod int AudioSystem::errorCheck(FMOD_RESULT result) { if (result != FMOD_OK) { std::cout << "FMOD ERROR " << result << std::endl; return 1; } return 0; } /// <summary> /// Carga un sonido en el sistema /// </summary> /// <param name="strSoundName"> string del archivo </param> /// <param name="b3d"> bool 3d /2d</param> /// <param name="bLooping">bool bool on /off</param> /// <param name="bStream">bool stream /compresses sample</param> void AudioSystem::loadSound(const std::string& strSoundName, bool b3d, bool bLooping, bool bStream) { auto encontrado = instance_->getSoundMap().find(strSoundName); if (encontrado != instance_->getSoundMap().end()) return; FMOD_MODE eMode = FMOD_DEFAULT; eMode |= b3d ? FMOD_3D : FMOD_2D; eMode |= bLooping ? FMOD_LOOP_NORMAL : FMOD_LOOP_OFF; eMode |= bStream ? FMOD_CREATESTREAM : FMOD_CREATECOMPRESSEDSAMPLE; FMOD::Sound* pSound = nullptr; errorCheck(instance_->getSystem()->createSound(strSoundName.c_str(), eMode, nullptr, &pSound)); if (pSound) { instance_->getSoundMap()[strSoundName] = pSound; } } /// <summary> /// Libera un sonido del sistema /// </summary> /// <param name="strSoundName"></param> void AudioSystem::unloadSound(const std::string& strSoundName) { auto encontrado = instance_->getSoundMap().find(strSoundName); if (encontrado == instance_->getSoundMap().end()) return; errorCheck(encontrado->second->release()); instance_->getSoundMap().erase(encontrado); } /// <summary> /// NO IMPLEMENTADO /// </summary> /// <param name="vPos"></param> /// <param name="fVolumedB"></param> void AudioSystem::set3dListenerAndOrientation(const Vector3& vPos = Vector3{ 0, 0, 0 }, float fVolumedB) { } /// <summary> /// Reproduce un sonido , si no existe lo carga /// </summary> /// <param name="strSoundName">nombre del archivo </param> /// <param name="vPos">posicion</param> /// <param name="groupName">nombre del grupo perteneciente si es null lo crea al general </param> /// <param name="fVolumedB"> volumen </param> /// <returns></returns> int AudioSystem::playSound(const std::string& strSoundName, const Vector3& vPos = Vector3{ 0, 0, 0 }, const char* groupName, float fVolumedB) { int nChannelId = instance_->getNextChannelId()++; auto encontrado = instance_->getSoundMap().find(strSoundName); if (encontrado == instance_->getSoundMap().end()) { loadSound(strSoundName); encontrado = instance_->getSoundMap().find(strSoundName); if (encontrado == instance_->getSoundMap().end()) { return nChannelId; } } FMOD::Channel* pChannel = nullptr; FMOD::ChannelGroup* pGruoup = nullptr; if (instance_->getChanGroupMap().count(groupName) == 0 && groupName != nullptr) { pGruoup = createChannelGroup(groupName); } errorCheck(instance_->getSystem()->playSound(encontrado->second , pGruoup, true, &pChannel)); if (pChannel) { FMOD_MODE currMode; encontrado->second->getMode(&currMode); if (currMode & FMOD_3D) { FMOD_VECTOR position = vectorToFmod(vPos); errorCheck(pChannel->set3DAttributes(&position, nullptr)); } errorCheck(pChannel->setVolume(dbToVolume(fVolumedB))); errorCheck(pChannel->setPaused(false)); instance_->getSoundChannels()[nChannelId] = pChannel; } return nChannelId; } //Para un canal void AudioSystem::stopChannel(int nChannelId) { auto encontrado = instance_->getSoundChannels().find(nChannelId); if (encontrado == instance_->getSoundChannels().end()) return; errorCheck(encontrado->second->stop()); } //Para todos los canales void AudioSystem::stopAllChannels() { for (auto x : instance_->getSoundChannels()) errorCheck(x.second->stop()); } //Coloca un canal en una posicion 3d void AudioSystem::setChannel3dPosition(int nChannelId, const Vector3& vPosition) { auto encontrado = instance_->getSoundChannels().find(nChannelId); if (encontrado == instance_->getSoundChannels().end()) return; FMOD_VECTOR position = vectorToFmod(vPosition); errorCheck(encontrado->second->set3DAttributes(&position, NULL)); } //Devuelve true si un canal esta reproduciendose bool AudioSystem::isPlaying(int nChannelId) const { auto encontrado = instance_->getSoundChannels().find(nChannelId); if (encontrado == instance_->getSoundChannels().end()) return false; bool isplay = false; errorCheck(instance_->getSoundChannels().at(nChannelId)->isPlaying(&isplay)); return isplay; } //Si esta pausado el canal lo resume y si esta sonando lo pausa void AudioSystem::pause_Resume_Channel(int nChannelId) { auto encontrado = instance_->getSoundChannels().find(nChannelId); if (encontrado == instance_->getSoundChannels().end()) return; bool ch = false; errorCheck(instance_->getSoundChannels().at(nChannelId)->getPaused(&ch)); errorCheck(instance_->getSoundChannels().at(nChannelId)->setPaused(!ch)); } //Convierte un vector fmod FMOD_VECTOR& AudioSystem::vectorToFmod(const Vector3& vPosition) { FMOD_VECTOR fVec; fVec.x = vPosition.x; fVec.y = vPosition.y; fVec.z = vPosition.z; return fVec; } //Crea un grupo de canales FMOD::ChannelGroup* AudioSystem::createChannelGroup(const char* name) { FMOD::ChannelGroup* channelGroup = nullptr; errorCheck(instance_->getSystem()->createChannelGroup(name, &channelGroup)); instance_->getChanGroupMap()[name] = channelGroup; return channelGroup; } //Mutea un grupo de canales especifico void AudioSystem::muteChannelGroup(const char* name) { bool mute = false; errorCheck(instance_->getChanGroupMap()[name]->getMute(&mute)); errorCheck(instance_->getChanGroupMap()[name]->setMute(!mute)); } float AudioSystem::dbToVolume(float dB) { return powf(10.0f, 0.05f * dB); } float AudioSystem::volumeTodb(float volume) { return 20.0f * log10f(volume); } //Cambia el volumen del canal void AudioSystem::setChannelvolume(int nChannelId, float fVolumedB) { auto encontrado = instance_->getSoundChannels().find(nChannelId); if (encontrado == instance_->getSoundChannels().end()) return; errorCheck(encontrado->second->setVolume(dbToVolume(fVolumedB))); }
27.434921
142
0.679125
[ "vector", "3d" ]
b759f481211c4b565b9c04b0a1ce926367fa77bd
14,039
cpp
C++
build-image_proc_sys-Desktop_Qt_5_5_1_MinGW_32bit-Release/release/qrc_qml.cpp
tong123/image_proc_sys
8f5b3a8a88b8f946529e84cb1c48bd7e5e4d9440
[ "Apache-2.0" ]
null
null
null
build-image_proc_sys-Desktop_Qt_5_5_1_MinGW_32bit-Release/release/qrc_qml.cpp
tong123/image_proc_sys
8f5b3a8a88b8f946529e84cb1c48bd7e5e4d9440
[ "Apache-2.0" ]
null
null
null
build-image_proc_sys-Desktop_Qt_5_5_1_MinGW_32bit-Release/release/qrc_qml.cpp
tong123/image_proc_sys
8f5b3a8a88b8f946529e84cb1c48bd7e5e4d9440
[ "Apache-2.0" ]
2
2022-02-25T08:53:21.000Z
2022-02-25T09:51:36.000Z
/**************************************************************************** ** Resource object code ** ** Created by: The Resource Compiler for Qt version 5.5.1 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ static const unsigned char qt_resource_data[] = { // E:/image_proc_sys/image_proc_sys/CustomMenuBar.qml 0x0,0x0,0x1,0xde, 0x0, 0x0,0x9,0xf,0x78,0x9c,0xa5,0x55,0xcb,0x4e,0xc2,0x50,0x10,0xdd,0x93,0xf0,0xf, 0x8d,0x2b,0xdd,0x34,0x6a,0x5c,0xb9,0x54,0x37,0x2e,0x4c,0xc4,0xe8,0x7,0x18,0xbd, 0x92,0x46,0x68,0xb1,0x5c,0x12,0x1f,0x21,0xa9,0x1a,0x44,0xc4,0xb7,0x68,0x55,0x82, 0xa,0x21,0xbe,0x1,0x13,0x94,0x0,0xe5,0xf1,0x33,0xdc,0xdb,0xb2,0xf2,0x17,0xa4, 0x80,0x41,0x45,0xa4,0x1d,0x67,0xd5,0x69,0xe7,0xcc,0x9c,0x39,0x73,0xe7,0xf6,0x5d, 0x29,0x73,0x4e,0x97,0x20,0x62,0xc6,0x86,0x6d,0x1e,0x6e,0x6e,0x91,0x19,0x64,0xfb, 0xad,0x96,0xef,0xef,0xd8,0x51,0x81,0xc7,0xa2,0xe0,0x70,0x33,0x3,0xec,0x90,0xd5, 0x62,0xb5,0x4c,0x20,0xde,0x33,0x32,0x2b,0x32,0x6b,0x56,0xb,0x53,0x33,0xdd,0xfd, 0x7c,0xd6,0xd,0x73,0xd8,0x81,0x86,0x99,0x1e,0x7a,0xe6,0xaf,0x28,0x99,0x9e,0xd6, 0x7,0x3d,0x70,0x1c,0x23,0xe7,0x97,0xd8,0x7a,0x3c,0x5a,0xc6,0x7a,0x78,0xe0,0x84, 0x14,0x24,0xfa,0x16,0xd4,0x52,0xa7,0x6d,0x50,0xdd,0x4,0x7e,0x5a,0xe4,0xec,0x76, 0x24,0xa2,0xf9,0x61,0xe6,0x47,0xe,0xdd,0x16,0x38,0x7,0x1a,0xe3,0x66,0x1d,0x82, 0x9d,0x15,0x5c,0x88,0xef,0xed,0xfb,0x1e,0xe2,0x6d,0xb9,0x5e,0x73,0x9c,0x34,0xff, 0x23,0x49,0x5e,0x56,0x72,0x81,0x36,0x5a,0x86,0x13,0x91,0xf8,0x1e,0xd9,0xbf,0x86, 0x20,0x69,0xd6,0x57,0xbd,0x88,0x43,0x90,0x55,0x49,0x22,0xfe,0xbc,0x49,0x11,0x6d, 0x98,0x5d,0xf2,0x70,0xf8,0x6f,0xf1,0x1a,0x8e,0xf7,0xef,0xf1,0xab,0x65,0x45,0x2b, 0x3e,0x1b,0x1f,0xff,0xcb,0x2b,0xc9,0xa5,0x41,0xda,0x5e,0x6d,0xa8,0xe1,0x57,0x90, 0xb6,0xf5,0x9a,0x9d,0xf0,0x5d,0xfa,0x23,0xc5,0x18,0x95,0xd6,0xd,0xf7,0xa7,0xf9, 0xe,0xb5,0x4b,0x9,0xc2,0x52,0xdb,0xba,0xd7,0x36,0x41,0x48,0xfd,0xec,0x96,0xf, 0xd5,0xa4,0xc,0x3a,0x3e,0x72,0x2,0xe,0x6e,0x88,0x43,0x12,0xb7,0x34,0x96,0x22, 0xf9,0x5b,0x50,0xfd,0x68,0x86,0x64,0x8b,0x20,0xa4,0x72,0xf4,0x2b,0xb2,0xcb,0x40, 0xa9,0x12,0xa7,0xe9,0x98,0xe1,0x81,0x92,0x88,0x9f,0x48,0x5,0x10,0xbf,0xa7,0x73, 0x7a,0x96,0x82,0x20,0x2b,0xd9,0x4,0xb0,0x26,0x39,0xd8,0xd5,0x4a,0x39,0xd3,0x9a, 0xa8,0x85,0x7,0x1a,0x2a,0x19,0x5f,0xe2,0x50,0x89,0xc4,0xef,0x7a,0x27,0x57,0x66, 0x5c,0x7d,0x10,0x96,0xb5,0x72,0xe4,0xe5,0x0,0x8e,0x6f,0xd6,0x9f,0x42,0x6e,0x6e, 0x15,0xfd,0x87,0x41,0xc7,0xc,0xdd,0xce,0x90,0x1c,0x34,0x73,0xe9,0x55,0xa3,0x79, 0x2a,0x67,0xaa,0xc7,0xdb,0x54,0xbe,0x69,0x93,0xda,0xc4,0xa6,0x34,0xb3,0xfc,0x23, 0x85,0xb4,0xd5,0x48,0x1,0x2,0x87,0x33,0x8d,0xbe,0x3b,0xd5,0xef,0x76,0x93,0x66, 0x93,0x64,0xe7,0xc1,0xb0,0x68,0x6a,0x60,0x9b,0x46,0x36,0x41,0x4b,0xe0,0x4b,0x57, 0xf2,0xfb,0xbf,0xf2,0xab,0xff,0xd5,0x3e,0x0,0xfa,0xa0,0x75,0x71, // E:/image_proc_sys/image_proc_sys/main.qml 0x0,0x0,0x6,0xd1, 0xef, 0xbb,0xbf,0x69,0x6d,0x70,0x6f,0x72,0x74,0x20,0x51,0x74,0x51,0x75,0x69,0x63,0x6b, 0x20,0x32,0x2e,0x33,0xd,0xa,0x69,0x6d,0x70,0x6f,0x72,0x74,0x20,0x51,0x74,0x51, 0x75,0x69,0x63,0x6b,0x2e,0x57,0x69,0x6e,0x64,0x6f,0x77,0x20,0x32,0x2e,0x32,0xd, 0xa,0x69,0x6d,0x70,0x6f,0x72,0x74,0x20,0x51,0x74,0x51,0x75,0x69,0x63,0x6b,0x2e, 0x43,0x6f,0x6e,0x74,0x72,0x6f,0x6c,0x73,0x20,0x31,0x2e,0x34,0xd,0xa,0x69,0x6d, 0x70,0x6f,0x72,0x74,0x20,0x51,0x74,0x51,0x75,0x69,0x63,0x6b,0x2e,0x44,0x69,0x61, 0x6c,0x6f,0x67,0x73,0x20,0x31,0x2e,0x32,0xd,0xa,0x69,0x6d,0x70,0x6f,0x72,0x74, 0x20,0x49,0x6d,0x61,0x67,0x65,0x49,0x74,0x65,0x6d,0x20,0x31,0x2e,0x30,0xd,0xa, 0x41,0x70,0x70,0x6c,0x69,0x63,0x61,0x74,0x69,0x6f,0x6e,0x57,0x69,0x6e,0x64,0x6f, 0x77,0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x76,0x69,0x73,0x69,0x62,0x6c,0x65, 0x3a,0x20,0x74,0x72,0x75,0x65,0xd,0xa,0x20,0x20,0x20,0x20,0x77,0x69,0x64,0x74, 0x68,0x3a,0x20,0x38,0x35,0x30,0xd,0xa,0x20,0x20,0x20,0x20,0x68,0x65,0x69,0x67, 0x68,0x74,0x3a,0x20,0x34,0x38,0x30,0xd,0xa,0xd,0xa,0x20,0x20,0x20,0x20,0x6d, 0x65,0x6e,0x75,0x42,0x61,0x72,0x3a,0x43,0x75,0x73,0x74,0x6f,0x6d,0x4d,0x65,0x6e, 0x75,0x42,0x61,0x72,0x7b,0xd,0xa,0xd,0xa,0x20,0x20,0x20,0x20,0x7d,0xd,0xa, 0x20,0x20,0x20,0x20,0x52,0x6f,0x77,0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x61,0x6e,0x63,0x68,0x6f,0x72,0x73,0x2e,0x63,0x65,0x6e,0x74,0x65, 0x72,0x49,0x6e,0x3a,0x20,0x70,0x61,0x72,0x65,0x6e,0x74,0xd,0xa,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x73,0x70,0x61,0x63,0x69,0x6e,0x67,0x3a,0x20,0x32,0x30, 0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x43,0x6f,0x6c,0x75,0x6d,0x6e, 0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x77,0x69,0x64,0x74,0x68,0x3a,0x20,0x34,0x30,0x30,0xd,0xa,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x68,0x65,0x69,0x67,0x68,0x74,0x3a,0x20, 0x34,0x35,0x30,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x73,0x70,0x61,0x63,0x69,0x6e,0x67,0x3a,0x20,0x31,0x30,0xd,0xa,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x52,0x65,0x63,0x74,0x61,0x6e, 0x67,0x6c,0x65,0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x77,0x69,0x64,0x74,0x68,0x3a,0x20,0x34,0x30, 0x30,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x68,0x65,0x69,0x67,0x68,0x74,0x3a,0x20,0x34,0x30,0x30,0xd,0xa, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x62,0x6f,0x72,0x64,0x65,0x72,0x2e,0x77,0x69,0x64,0x74,0x68,0x3a,0x20,0x31,0xd, 0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x62,0x6f,0x72,0x64,0x65,0x72,0x2e,0x63,0x6f,0x6c,0x6f,0x72,0x3a,0x20,0x22, 0x62,0x6c,0x61,0x63,0x6b,0x22,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x49,0x6d,0x61,0x67,0x65,0x7b,0xd,0xa, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x69,0x64,0x3a,0x20,0x73,0x72,0x63,0x5f,0x69,0x6d,0x67,0xd, 0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x61,0x6e,0x63,0x68,0x6f,0x72,0x73,0x2e,0x66,0x69,0x6c, 0x6c,0x3a,0x20,0x70,0x61,0x72,0x65,0x6e,0x74,0xd,0xa,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73, 0x6f,0x75,0x72,0x63,0x65,0x3a,0x20,0x22,0x70,0x6f,0x73,0x69,0x74,0x69,0x6f,0x6e, 0x2e,0x69,0x72,0x70,0x2e,0x6a,0x70,0x67,0x22,0xd,0xa,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x7d,0xd,0xa,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x7d,0xd,0xa,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x54,0x65,0x78,0x74,0x20,0x7b,0xd, 0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x69,0x64,0x3a,0x20,0x73,0x72,0x63,0x5f,0x74,0x78,0x74,0xd,0xa,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x74,0x65, 0x78,0x74,0x3a,0x20,0x71,0x73,0x54,0x72,0x28,0x22,0xe6,0xba,0x90,0xe5,0x9b,0xbe, 0xe5,0x83,0x8f,0x22,0x29,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x7d,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x7d,0xd, 0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x43,0x6f,0x6c,0x75,0x6d,0x6e,0x20, 0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x77, 0x69,0x64,0x74,0x68,0x3a,0x20,0x34,0x30,0x30,0xd,0xa,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x68,0x65,0x69,0x67,0x68,0x74,0x3a,0x20,0x34, 0x35,0x30,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x73,0x70,0x61,0x63,0x69,0x6e,0x67,0x3a,0x20,0x31,0x30,0xd,0xa,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x52,0x65,0x63,0x74,0x61,0x6e,0x67, 0x6c,0x65,0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x77,0x69,0x64,0x74,0x68,0x3a,0x20,0x34,0x30,0x30, 0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x68,0x65,0x69,0x67,0x68,0x74,0x3a,0x20,0x34,0x30,0x30,0xd,0xa,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x62, 0x6f,0x72,0x64,0x65,0x72,0x2e,0x77,0x69,0x64,0x74,0x68,0x3a,0x20,0x31,0xd,0xa, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x62,0x6f,0x72,0x64,0x65,0x72,0x2e,0x63,0x6f,0x6c,0x6f,0x72,0x3a,0x20,0x22,0x62, 0x6c,0x61,0x63,0x6b,0x22,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x49,0x6d,0x61,0x67,0x65,0x49,0x74,0x65,0x6d, 0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3a,0x20,0x69,0x6d,0x61,0x67, 0x65,0x5f,0x69,0x74,0x65,0x6d,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x61,0x6e,0x63,0x68, 0x6f,0x72,0x73,0x2e,0x66,0x69,0x6c,0x6c,0x3a,0x20,0x70,0x61,0x72,0x65,0x6e,0x74, 0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x7d,0xd,0xa,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x7d,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x54,0x65,0x78,0x74,0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64,0x3a,0x20,0x64,0x65, 0x73,0x5f,0x74,0x78,0x74,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x74,0x65,0x78,0x74,0x3a,0x20,0x71,0x73,0x54, 0x72,0x28,0x22,0xe5,0xa4,0x84,0xe7,0x90,0x86,0xe7,0xbb,0x93,0xe6,0x9e,0x9c,0x22, 0x29,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x7d, 0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x7d,0xd,0xa,0x20,0x20,0x20, 0x20,0x7d,0xd,0xa,0x20,0x20,0x20,0x20,0x46,0x69,0x6c,0x65,0x44,0x69,0x61,0x6c, 0x6f,0x67,0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x64, 0x3a,0x20,0x66,0x69,0x6c,0x65,0x44,0x69,0x61,0x6c,0x6f,0x67,0xd,0xa,0x20,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x74,0x69,0x74,0x6c,0x65,0x3a,0x20,0x22,0xe8,0xaf, 0xb7,0xe9,0x80,0x89,0xe6,0x8b,0xa9,0xe4,0xb8,0x80,0xe5,0xbc,0xa0,0xe5,0x9b,0xbe, 0xe7,0x89,0x87,0xe6,0x96,0x87,0xe4,0xbb,0xb6,0x22,0xd,0xa,0x20,0x20,0x20,0x20, 0x20,0x20,0x20,0x20,0x6f,0x6e,0x41,0x63,0x63,0x65,0x70,0x74,0x65,0x64,0x3a,0x20, 0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x73, 0x72,0x63,0x5f,0x69,0x6d,0x67,0x2e,0x73,0x6f,0x75,0x72,0x63,0x65,0x20,0x3d,0x20, 0x66,0x69,0x6c,0x65,0x44,0x69,0x61,0x6c,0x6f,0x67,0x2e,0x66,0x69,0x6c,0x65,0x55, 0x72,0x6c,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x76,0x61,0x72,0x20,0x73,0x5f,0x69,0x72,0x5f,0x66,0x69,0x6c,0x65,0x20,0x3d,0x20, 0x66,0x69,0x6c,0x65,0x44,0x69,0x61,0x6c,0x6f,0x67,0x2e,0x66,0x69,0x6c,0x65,0x55, 0x72,0x6c,0x2e,0x74,0x6f,0x53,0x74,0x72,0x69,0x6e,0x67,0x28,0x29,0xd,0xa,0x20, 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x69,0x6d,0x61,0x67,0x65, 0x5f,0x69,0x74,0x65,0x6d,0x2e,0x69,0x72,0x46,0x69,0x6c,0x65,0x50,0x61,0x74,0x68, 0x20,0x3d,0x20,0x73,0x5f,0x69,0x72,0x5f,0x66,0x69,0x6c,0x65,0x2e,0x73,0x6c,0x69, 0x63,0x65,0x28,0x38,0x29,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x7d, 0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x6f,0x6e,0x52,0x65,0x6a,0x65, 0x63,0x74,0x65,0x64,0x3a,0x20,0x7b,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20, 0x20,0x7d,0xd,0xa,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x43,0x6f,0x6d,0x70, 0x6f,0x6e,0x65,0x6e,0x74,0x2e,0x6f,0x6e,0x43,0x6f,0x6d,0x70,0x6c,0x65,0x74,0x65, 0x64,0x3a,0x20,0x76,0x69,0x73,0x69,0x62,0x6c,0x65,0x20,0x3d,0x20,0x66,0x61,0x6c, 0x73,0x65,0xd,0xa,0x20,0x20,0x20,0x20,0x7d,0xd,0xa,0x7d,0xd,0xa,0xd,0xa, }; static const unsigned char qt_resource_name[] = { // CustomMenuBar.qml 0x0,0x11, 0x5,0xe9,0xf9,0xdc, 0x0,0x43, 0x0,0x75,0x0,0x73,0x0,0x74,0x0,0x6f,0x0,0x6d,0x0,0x4d,0x0,0x65,0x0,0x6e,0x0,0x75,0x0,0x42,0x0,0x61,0x0,0x72,0x0,0x2e,0x0,0x71,0x0,0x6d,0x0,0x6c, // main.qml 0x0,0x8, 0x8,0x1,0x5a,0x5c, 0x0,0x6d, 0x0,0x61,0x0,0x69,0x0,0x6e,0x0,0x2e,0x0,0x71,0x0,0x6d,0x0,0x6c, }; static const unsigned char qt_resource_struct[] = { // : 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1, // :/CustomMenuBar.qml 0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0, // :/main.qml 0x0,0x0,0x0,0x28,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x1,0xe2, }; #ifdef QT_NAMESPACE # define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name # define QT_RCC_MANGLE_NAMESPACE0(x) x # define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b # define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b) # define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \ QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE)) #else # define QT_RCC_PREPEND_NAMESPACE(name) name # define QT_RCC_MANGLE_NAMESPACE(name) name #endif #ifdef QT_NAMESPACE namespace QT_NAMESPACE { #endif bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); #ifdef QT_NAMESPACE } #endif int QT_RCC_MANGLE_NAMESPACE(qInitResources_qml)(); int QT_RCC_MANGLE_NAMESPACE(qInitResources_qml)() { QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData) (0x01, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_qml)(); int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_qml)() { QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData) (0x01, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } namespace { struct initializer { initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_qml)(); } ~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_qml)(); } } dummy; }
61.03913
146
0.754612
[ "object" ]
b75d03017dc1b441b608b8201980d34898e99d60
10,186
hpp
C++
samples/datasets/src/middlebury2005.hpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
97
2015-10-16T04:32:33.000Z
2022-03-29T07:04:02.000Z
samples/datasets/src/middlebury2005.hpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
19
2016-07-01T16:37:02.000Z
2020-09-10T06:09:39.000Z
samples/datasets/src/middlebury2005.hpp
jpjodoin/litiv
435556bea20d60816aff492f50587b1a2d748b21
[ "BSD-3-Clause" ]
41
2015-11-17T05:59:23.000Z
2022-02-16T09:30:28.000Z
// 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 "litiv/datasets.hpp" namespace lv { // unique identifier for the demo dataset -- might cause problems if same code reused elsewhere static const DatasetList Dataset_Middlebury2005_demo = DatasetList(Dataset_Custom+1); // override the dataset evaluation type utility getter function to always set the eval type for this dataset as 'none' when used for cosegm template<> // full specialization of 'getDatasetEval' declared in datasets/utils.hpp constexpr DatasetEvalList getDatasetEval<DatasetTask_Cosegm,Dataset_Middlebury2005_demo>() { return DatasetEval_None; } // top-level dataset interface specialization; this allows us to simplify the default constructor template<DatasetTaskList eDatasetTask, lv::ParallelAlgoType eEvalImpl> // two parameters that will be specified by the user at compile time struct Dataset_<eDatasetTask,Dataset_Middlebury2005_demo,eEvalImpl> : // partial specialization of 'Dataset_' declared in datasets/utils.hpp public IDataset_<eDatasetTask,DatasetSource_ImageArray,Dataset_Middlebury2005_demo,lv::getDatasetEval<eDatasetTask,Dataset_Middlebury2005_demo>(),eEvalImpl> { // dataset specializations should always inherit from 'IDataset_' static_assert((eDatasetTask==DatasetTask_Cosegm || eDatasetTask==DatasetTask_StereoReg),"bad task chosen for middlebury stereo dataset"); // this dataset only supports two task types protected: // should still be protected, as creation should always be done via datasets::create (avoids problems with shared_from_this) Dataset_( // local specialization constructor (can receive any extra parameters you may which to have) const std::string& sOutputDirPath, // output directory path for debug logs, evaluation reports and pushed results bool bEvalOutput=false, // defines whether pushed results should be evaluated or not bool bSaveOutput=true // defines whether pushed results should be saved or not ) : IDataset_<eDatasetTask,DatasetSource_ImageArray,Dataset_Middlebury2005_demo,lv::getDatasetEval<eDatasetTask,Dataset_Middlebury2005_demo>(),eEvalImpl>( // need to provide all necessary params to base 'IDataset_' constructor "middlebury2005", // name of the dataset (for debug purposes only) lv::addDirSlashIfMissing(SAMPLES_DATA_ROOT)+"middlebury2005_dataset_ex/", // location of the dataset's root folder sOutputDirPath, // location of the dataet's output folder std::vector<std::string>{"art","dolls"}, // name of work batches for this dataset (here, one work batch = one stereo pair) std::vector<std::string>(), // names of directories which should be ignored by the parser (here, none in particular) bSaveOutput, // toggles whether pushed results will be saved or not bEvalOutput // toggles whether pushed results should be evaluated or not ) {} }; // dataset group handler specialization; this allows us to completely bypass the notion of 'groups', as there are no categories in middlebury2005 template<DatasetTaskList eDatasetTask> struct DataGroupHandler_<eDatasetTask,DatasetSource_ImageArray,Dataset_Middlebury2005_demo> : public DataGroupHandler { protected: // override the 'parseData()' member from DataGroupHandler to bypass dataset categories (there are none) virtual void parseData() override { // 'this' is required below since name lookup is done during instantiation because of not-fully-specialized class template this->m_vpBatches.clear(); // clear all children if re-parsing this->m_bIsBare = true; // in this dataset, work batch groups are always bare (i.e. there are no data 'categories') this->m_vpBatches.push_back(this->createWorkBatch(this->getName(),this->getRelativePath())); // push directly with current-level params } }; // work batch data producer specialization; this allows us to define what data will be parsed, and how it should be exposed to the end user template<DatasetTaskList eDatasetTask> struct DataProducer_<eDatasetTask,DatasetSource_ImageArray,Dataset_Middlebury2005_demo> : public IDataProducerWrapper_<eDatasetTask,DatasetSource_ImageArray,Dataset_Middlebury2005_demo> { // return the array size of each input packet virtual size_t getInputStreamCount() const override final { return 2; // this dataset always exposes two input images simultaneously (i.e. one per stereo head) } // return the array size of each gt packet virtual size_t getGTStreamCount() const override final { return 2; // this dataset always exposes two gt disparity maps simultaneously (i.e. one per stereo head) } // OPTIONAL: provide a user-friendly name for input streams (in this case, it specifies the left/right stereo head) virtual std::string getInputStreamName(size_t nStreamIdx) const override final { return ((nStreamIdx==0)?"Left input":(nStreamIdx==1)?"Right input":"UNKNOWN"); } // OPTIONAL: provide a user-friendly name for gt streams (in this case, it specifies the left/right stereo head) virtual std::string getGTStreamName(size_t nStreamIdx) const override final { return ((nStreamIdx==0)?"Left gt":(nStreamIdx==1)?"Right gt":"UNKNOWN"); } protected: // implement the 'parseData()' abstract member from IDataHandler with our own parsing routine virtual void parseData() override final { // 'this' is required below since name lookup is done during instantiation because of not-fully-specialized class template // we have to fill the following member vars, declared in 'IDataProducer_<DatasetSource_ImageArray>', which is the base data producer for this dataset: // m_mGTIndexLUT,m_vvsInputPaths,m_vvsGTPaths,m_vvInputInfos,m_vvGTInfos,m_bIsInputInfoConst,m_bIsGTInfoConst this->m_vvsInputPaths.clear();this->m_vvsGTPaths.clear(); // start with empty vectors, useful if re-parsing over a previous attempt this->m_vvsInputPaths.push_back(std::vector<std::string>{this->getDataPath()+"view1.png",this->getDataPath()+"view5.png"}); // batch contains only one 'packet', i.e. one stereo image array containing two images const cv::Mat oInput_L = cv::imread(this->m_vvsInputPaths[0][0]); // load 'left' image from the stereo pair const cv::Mat oInput_R = cv::imread(this->m_vvsInputPaths[0][1]); // load 'right' image from the stereo pair lvAssert(!oInput_L.empty() && !oInput_R.empty() && oInput_L.size()==oInput_R.size()); // make sure the data fits expectations this->m_vvsGTPaths.push_back(std::vector<std::string>{this->getDataPath()+"disp1.png",this->getDataPath()+"disp5.png"}); // do the same for GT data (one packet = two disparity maps, one for each stereo head) const cv::Mat oGT_L = cv::imread(this->m_vvsGTPaths[0][0],cv::IMREAD_GRAYSCALE); // load 'left' disparity map const cv::Mat oGT_R = cv::imread(this->m_vvsGTPaths[0][1],cv::IMREAD_GRAYSCALE); // load 'right' disparity map lvAssert(!oGT_L.empty() && !oGT_R.empty() && oGT_L.size()==oGT_R.size() && oGT_L.size()==oInput_L.size()); this->m_bIsInputInfoConst = this->m_bIsGTInfoConst = true; // all packets have the same size/type (there is only one packet anyway) this->m_vvInputInfos = std::vector<std::vector<lv::MatInfo>>{{lv::MatInfo{oInput_L.size(),oInput_L.type()},lv::MatInfo{oInput_R.size(),oInput_R.type()}}}; this->m_vvGTInfos = std::vector<std::vector<lv::MatInfo>>{{lv::MatInfo{oGT_L.size(),oGT_L.type()},lv::MatInfo{oGT_R.size(),oGT_R.type()}}}; this->m_mGTIndexLUT[0] = 0; // gt packet with index #0 is associated with input packet with index #0 } // overrides the default getRawGTArray implementation to properly scale disparity values virtual std::vector<cv::Mat> getRawGTArray(size_t nPacketIdx) override final { const cv::Size oImageSize(463,370); // size of the expected GT frames std::vector<cv::Mat> vGTs(getGTStreamCount()); // output gt array (which may keep empty mats) if(this->m_mGTIndexLUT.count(nPacketIdx)) { // if the GT LUT maps to an existing index const size_t nGTIdx = this->m_mGTIndexLUT[nPacketIdx]; // get the corresponding GT packet index if(nGTIdx<this->m_vvsGTPaths.size()) { // make sure it maps to a valid GT path array const std::vector<std::string>& vsGTPaths = this->m_vvsGTPaths[nGTIdx]; // shorthand for access lvAssert_(vsGTPaths.size()==getGTStreamCount(),"GT path count did not match stream count"); for(size_t nStreamIdx=0; nStreamIdx<vsGTPaths.size(); ++nStreamIdx) { vGTs[nStreamIdx] = cv::imread(vsGTPaths[nStreamIdx],cv::IMREAD_UNCHANGED); vGTs[nStreamIdx] /= 3; // scale down pixel values (disparities) due to 1/3 size dataset } } } return vGTs; } }; } // namespace lv
78.96124
238
0.69625
[ "vector" ]
b765732346b76fff7bd440c9289c424f23b533e7
3,957
hpp
C++
ThirdParty-mod/java2cpp/java/io/WriteAbortedException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/java/io/WriteAbortedException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/java/io/WriteAbortedException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.io.WriteAbortedException ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_DECL #define J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_DECL namespace j2cpp { namespace java { namespace io { class ObjectStreamException; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Throwable; } } } namespace j2cpp { namespace java { namespace lang { class Exception; } } } #include <java/io/ObjectStreamException.hpp> #include <java/lang/Exception.hpp> #include <java/lang/String.hpp> #include <java/lang/Throwable.hpp> namespace j2cpp { namespace java { namespace io { class WriteAbortedException; class WriteAbortedException : public object<WriteAbortedException> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_FIELD(0) explicit WriteAbortedException(jobject jobj) : object<WriteAbortedException>(jobj) , detail(jobj) { } operator local_ref<java::io::ObjectStreamException>() const; WriteAbortedException(local_ref< java::lang::String > const&, local_ref< java::lang::Exception > const&); local_ref< java::lang::String > getMessage(); local_ref< java::lang::Throwable > getCause(); field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), local_ref< java::lang::Exception > > detail; }; //class WriteAbortedException } //namespace io } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_IMPL #define J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_IMPL namespace j2cpp { java::io::WriteAbortedException::operator local_ref<java::io::ObjectStreamException>() const { return local_ref<java::io::ObjectStreamException>(get_jobject()); } java::io::WriteAbortedException::WriteAbortedException(local_ref< java::lang::String > const &a0, local_ref< java::lang::Exception > const &a1) : object<java::io::WriteAbortedException>( call_new_object< java::io::WriteAbortedException::J2CPP_CLASS_NAME, java::io::WriteAbortedException::J2CPP_METHOD_NAME(0), java::io::WriteAbortedException::J2CPP_METHOD_SIGNATURE(0) >(a0, a1) ) , detail(get_jobject()) { } local_ref< java::lang::String > java::io::WriteAbortedException::getMessage() { return call_method< java::io::WriteAbortedException::J2CPP_CLASS_NAME, java::io::WriteAbortedException::J2CPP_METHOD_NAME(1), java::io::WriteAbortedException::J2CPP_METHOD_SIGNATURE(1), local_ref< java::lang::String > >(get_jobject()); } local_ref< java::lang::Throwable > java::io::WriteAbortedException::getCause() { return call_method< java::io::WriteAbortedException::J2CPP_CLASS_NAME, java::io::WriteAbortedException::J2CPP_METHOD_NAME(2), java::io::WriteAbortedException::J2CPP_METHOD_SIGNATURE(2), local_ref< java::lang::Throwable > >(get_jobject()); } J2CPP_DEFINE_CLASS(java::io::WriteAbortedException,"java/io/WriteAbortedException") J2CPP_DEFINE_METHOD(java::io::WriteAbortedException,0,"<init>","(Ljava/lang/String;Ljava/lang/Exception;)V") J2CPP_DEFINE_METHOD(java::io::WriteAbortedException,1,"getMessage","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(java::io::WriteAbortedException,2,"getCause","()Ljava/lang/Throwable;") J2CPP_DEFINE_FIELD(java::io::WriteAbortedException,0,"detail","Ljava/lang/Exception;") } //namespace j2cpp #endif //J2CPP_JAVA_IO_WRITEABORTEDEXCEPTION_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
31.15748
144
0.718221
[ "object" ]
b768caa487f434be12b482d43fe2a908174f05d2
5,984
cpp
C++
src/add-ons/kernel/drivers/audio/echo/generic/CEchoGalsMTC.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/add-ons/kernel/drivers/audio/echo/generic/CEchoGalsMTC.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/add-ons/kernel/drivers/audio/echo/generic/CEchoGalsMTC.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
// **************************************************************************** // // CEchoGalsMTC.cpp // // CEchoGalsMTC is used to add MIDI time code sync to the base // CEchoGals class. CEchoGalsMTC derives from CEchoGals; CLayla and // CLayla24 derive in turn from CEchoGalsMTC. // // Set editor tabs to 3 for your viewing pleasure. // // ---------------------------------------------------------------------------- // // This file is part of Echo Digital Audio's generic driver library. // Copyright Echo Digital Audio Corporation (c) 1998 - 2005 // All rights reserved // www.echoaudio.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // **************************************************************************** #include "CEchoGalsMTC.h" //**************************************************************************** // // Constructor and destructor // //**************************************************************************** CEchoGalsMTC::CEchoGalsMTC( PCOsSupport pOsSupport ) : CEchoGals( pOsSupport ) { ECHO_DEBUGPRINTF( ( "CEchoGalsMTC::CEchoGalsMTC() is born!\n" ) ); m_wInputClock = ECHO_CLOCK_INTERNAL; } // CEchoGalsMTC::CEchoGalsMTC() CEchoGalsMTC::~CEchoGalsMTC() { ECHO_DEBUGPRINTF( ( "CEchoGalsMTC::~CEchoGalsMTC() is toast!\n" ) ); } // CEchoGalsMTC::~CEchoGalsMTC() //**************************************************************************** // // Input clock // //**************************************************************************** //============================================================================ // // Set the input clock // // This needs to intercept the input clock value here since MTC sync is // actually implemented in software // //============================================================================ ECHOSTATUS CEchoGalsMTC::SetInputClock(WORD wClock) { ECHOSTATUS Status; Status = ECHOSTATUS_OK; // // Check for MTC clock // if (ECHO_CLOCK_MTC == wClock) { if (ECHO_CLOCK_MTC != m_wInputClock) { // // Tell the MIDI input object to enable MIDI time code sync // Status = m_MidiIn.ArmMtcSync(); if (ECHOSTATUS_OK == Status) { // // Store the current clock as MTC... // m_wInputClock = ECHO_CLOCK_MTC; // // but set the real clock to internal. // Status = CEchoGals::SetInputClock( ECHO_CLOCK_INTERNAL ); } } } else { // // Pass the clock setting to the base class // Status = CEchoGals::SetInputClock( wClock ); if (ECHOSTATUS_OK == Status) { WORD wOldClock; DWORD dwRate; // // Get the base rate for MTC sync // m_MidiIn.GetMtcBaseRate( &dwRate ); // // Make sure MTC sync is off // m_MidiIn.DisarmMtcSync(); // // Store the new clock // wOldClock = m_wInputClock; m_wInputClock = wClock; // // If the previous clock was MTC, re-set the sample rate // if (ECHO_CLOCK_MTC == wOldClock) SetAudioSampleRate( dwRate ); } } return Status; } // SetInputClock //============================================================================ // // Get the input clock // //============================================================================ ECHOSTATUS CEchoGalsMTC::GetInputClock(WORD &wClock) { wClock = m_wInputClock; return ECHOSTATUS_OK; } //**************************************************************************** // // Sample rate // //**************************************************************************** //============================================================================ // // Set the sample rate // // Again, the rate needs to be intercepted here. // //============================================================================ ECHOSTATUS CEchoGalsMTC::SetAudioSampleRate( DWORD dwSampleRate ) { ECHOSTATUS Status; // // Syncing to MTC? // if (ECHO_CLOCK_MTC == m_wInputClock) { // // Test the rate // Status = QueryAudioSampleRate( dwSampleRate ); // // Set the base rate if it's OK // if (ECHOSTATUS_OK == Status) { m_MidiIn.SetMtcBaseRate( dwSampleRate ); } } else { // // Call the base class // Status = CEchoGals::SetAudioSampleRate( dwSampleRate ); } return Status; } // SetAudioSampleRate //============================================================================ // // Get the sample rate // //============================================================================ ECHOSTATUS CEchoGalsMTC::GetAudioSampleRate( PDWORD pdwSampleRate ) { ECHOSTATUS Status; if (NULL == pdwSampleRate) return ECHOSTATUS_INVALID_PARAM; // // Syncing to MTC? // if (ECHO_CLOCK_MTC == m_wInputClock) { // // Get the MTC base rate // Status = m_MidiIn.GetMtcBaseRate( pdwSampleRate ); } else { // // Call the base class // Status = CEchoGals::GetAudioSampleRate( pdwSampleRate ); } return Status; } // GetAudioSampleRate //**************************************************************************** // // Call this periodically to change the sample rate based on received MTC // data // //**************************************************************************** void CEchoGalsMTC::ServiceMtcSync() { m_MidiIn.ServiceMtcSync(); } // *** CEchoGalsMTC.cpp ***
22.666667
79
0.502005
[ "object" ]
b76c73558e48ca87fa5b2b3641c85e7eaa10b339
1,492
hpp
C++
Ryukuo Injector/advancedinjectorwindow.hpp
Iciclez/ryukuo-injector
d7de5b71bdc6dfa2ab09493bf45de7538caa5d8e
[ "MIT" ]
null
null
null
Ryukuo Injector/advancedinjectorwindow.hpp
Iciclez/ryukuo-injector
d7de5b71bdc6dfa2ab09493bf45de7538caa5d8e
[ "MIT" ]
null
null
null
Ryukuo Injector/advancedinjectorwindow.hpp
Iciclez/ryukuo-injector
d7de5b71bdc6dfa2ab09493bf45de7538caa5d8e
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <string> #include "window.hpp" #include "numericupdown.hpp" #include "button.hpp" #include "checklistview.hpp" #include "groupbox.hpp" #include "inject.hpp" class mainwindow; typedef HINSTANCE hinstance; typedef HANDLE handle; class advancedinjectorwindow { private: std::string windowname(); void set_message_handler(); const std::vector<std::string> getdlllist() const; public: enum id : int32_t { menu_librarylist_add = 1, menu_librarylist_remove, menu_librarylist_removeselected, menu_librarylist_opencontainingfolder, menu_librarylist_clear, menu_processlist_refresh, menu_processlist_suspend, menu_processlist_resume, menu_processlist_terminate, button_inject, checklistview_processlist, checklistview_dlllist, groupbox_processlist, groupbox_dlllist, }; private: hinstance inst; window *w; button *m_button_inject; checklistview *m_checklistview_processlist; checklistview *m_checklistview_dlllist; groupbox *m_groupbox_processlist; groupbox *m_groupbox_dlllist; private: mainwindow *mw; HIMAGELIST processlist_imagelist; std::function<void(inject::injection_error)> injection_error_handler; public: advancedinjectorwindow(mainwindow *mw, hinstance inst); ~advancedinjectorwindow(); void show(); void hide(); void refresh_processlist(); bool set_dlllist(const std::unordered_map<std::string, bool> &dlllist); const std::unordered_map<std::string, bool> get_dlllist(); };
19.128205
72
0.784853
[ "vector" ]
b777e0fb8a09f951fae12f396132d9eb690ad811
6,769
cpp
C++
ohm/VoxelBlockCompressionQueue.cpp
jmackay2/ohm
15f7b9f221419d2faf3802404a2f378ef570a990
[ "Zlib" ]
45
2020-06-09T23:26:47.000Z
2022-03-16T12:16:33.000Z
ohm/VoxelBlockCompressionQueue.cpp
jmackay2/ohm
15f7b9f221419d2faf3802404a2f378ef570a990
[ "Zlib" ]
1
2022-01-10T05:50:36.000Z
2022-01-24T02:50:01.000Z
ohm/VoxelBlockCompressionQueue.cpp
jmackay2/ohm
15f7b9f221419d2faf3802404a2f378ef570a990
[ "Zlib" ]
5
2021-02-25T15:08:46.000Z
2022-03-30T13:08:03.000Z
// Copyright (c) 2019 // Commonwealth Scientific and Industrial Research Organisation (CSIRO) // ABN 41 687 119 230 // // Author: Kazys Stepanas #include "VoxelBlockCompressionQueue.h" #include "VoxelBlock.h" #include "private/VoxelBlockCompressionQueueDetail.h" #include <algorithm> #include <chrono> #include <cinttypes> #include <iostream> namespace ohm { const int kSleepIntervalMs = 50; VoxelBlockCompressionQueue &VoxelBlockCompressionQueue::instance() { static VoxelBlockCompressionQueue queue_instance; return queue_instance; } VoxelBlockCompressionQueue::VoxelBlockCompressionQueue(bool test_mode) : imp_(new VoxelBlockCompressionQueueDetail) { imp_->test_mode = test_mode; } VoxelBlockCompressionQueue::~VoxelBlockCompressionQueue() { if (imp_->running) { std::unique_lock<VoxelBlockCompressionQueueDetail::Mutex> guard(imp_->ref_lock); joinCurrentThread(); } } void VoxelBlockCompressionQueue::retain() { std::unique_lock<VoxelBlockCompressionQueueDetail::Mutex> guard(imp_->ref_lock); if (++imp_->reference_count == 1) { // Start the thread. imp_->running = true; imp_->processing_thread = std::thread([this]() { this->run(); }); } } void VoxelBlockCompressionQueue::release() { std::unique_lock<VoxelBlockCompressionQueueDetail::Mutex> guard(imp_->ref_lock); int ref = --imp_->reference_count; if (ref == 0) { joinCurrentThread(); } else if (ref < 0) { imp_->reference_count = 0; } } uint64_t VoxelBlockCompressionQueue::highTide() const { return imp_->high_tide; } void VoxelBlockCompressionQueue::setHighTide(uint64_t tide) { imp_->high_tide = tide; } uint64_t VoxelBlockCompressionQueue::lowTide() const { return imp_->low_tide; } void VoxelBlockCompressionQueue::setLowTide(uint64_t tide) { imp_->low_tide = tide; } uint64_t VoxelBlockCompressionQueue::estimatedAllocationSize() const { return imp_->estimated_allocated_size; } void VoxelBlockCompressionQueue::push(VoxelBlock *block) { if (imp_->running || imp_->test_mode) { block->flags_ |= VoxelBlock::kFManagedForCompression; ohm::push(*imp_, block); } } bool VoxelBlockCompressionQueue::testMode() const { return imp_->test_mode; } void VoxelBlockCompressionQueue::__tick(std::vector<uint8_t> &compression_buffer) { // Process any new items added to the compression queue by adding them to the block list. { VoxelBlock *voxels = nullptr; while (ohm::tryPop(*imp_, &voxels)) { imp_->blocks.emplace_back(CompressionEntry{ voxels, 0u }); } } // Estimate the current memory usage and release items marked for death. uint64_t memory_usage = 0; const uint64_t high_tide = imp_->high_tide; const uint64_t low_tide = imp_->low_tide; for (auto iter = imp_->blocks.begin(); iter != imp_->blocks.end();) { CompressionEntry &entry = *iter; // Check if marked for death. if (!(entry.voxels->flags_ & VoxelBlock::kFMarkedForDeath)) { // Still alive. Update th entry's allocation size. if (entry.voxels->flags_ & VoxelBlock::kFUncompressed) { entry.allocation_size = entry.voxels->uncompressed_byte_size_; } else { entry.allocation_size = entry.voxels->compressed_byte_size_; } memory_usage += entry.allocation_size; ++iter; } else { // Marked for death. Remove this entry; // Block no longer required. Remove it. // Marked for death. Clean it up. // Lock access guard to make sure the code that sets the flag has completed iter->voxels->access_guard_.lock(); // fprintf(stderr, "0x%" PRIXPTR ", VoxelBlockCompressionQueue\n", (uintptr_t)iter->voxels); delete iter->voxels; iter = imp_->blocks.erase(iter); } } // Check if we are over the high tide and release what we can. if (memory_usage >= high_tide) { // Sort all blocks by allocation size. // TODO(KS): consider including the queued for compression flag so we push items to be compressed to the front // of the sort results. // TODO(KS): try using a partial sort. std::sort(imp_->blocks.begin(), imp_->blocks.end(), [](const CompressionEntry &a, const CompressionEntry &b) { return a.allocation_size > b.allocation_size; }); auto iter = imp_->blocks.begin(); // Free until we reach the low tide. while (iter != imp_->blocks.end() && memory_usage >= low_tide) { // Check if marked for death. The status may have changed since we updated the allocation size. if (!(iter->voxels->flags_ & VoxelBlock::kFMarkedForDeath)) { // Not maked for death. Check lock flag and compress this item if we can if (!(iter->voxels->flags_ & VoxelBlock::kFLocked)) { // Block is not locked. // std::cout << "compress\n" << std::flush; // Try compress the current item. This could fail as the flag can have changed. On failure, the // compressed_size will be zero. We call compressWithTemporaryBuffer() to re-use the compression buffer // memory. size_t compressed_size = iter->voxels->compressWithTemporaryBuffer(compression_buffer); if (compressed_size) { // Compression succeeded. // Adjust memory_usage down in a way which guarantees no underflow. Paranoia. memory_usage = (memory_usage > iter->allocation_size) ? memory_usage - iter->allocation_size : 0u; memory_usage += compressed_size; } } ++iter; } else { // Block no longer required. Remove it. // Marked for death. Clean it up. // Lock access guard to make sure the code that sets the flag has completed iter->voxels->access_guard_.lock(); // fprintf(stderr, "0x%" PRIXPTR ", VoxelBlockCompressionQueue\n", (uintptr_t)iter->voxels); delete iter->voxels; // Adjust memory_usage down in a way which guarantees no underflow. Paranoia. memory_usage = (memory_usage > iter->allocation_size) ? memory_usage - iter->allocation_size : 0u; iter = imp_->blocks.erase(iter); } } } imp_->estimated_allocated_size = memory_usage; } void VoxelBlockCompressionQueue::joinCurrentThread() { // Mark thread for quit. if (imp_->running) { imp_->quit_flag = true; imp_->processing_thread.join(); // Clear the running and quit flags. imp_->running = false; imp_->quit_flag = false; } } void VoxelBlockCompressionQueue::run() { std::vector<uint8_t> compression_buffer; while (!imp_->quit_flag) { std::this_thread::sleep_for(std::chrono::milliseconds(kSleepIntervalMs)); __tick(compression_buffer); } } } // namespace ohm
27.855967
114
0.677205
[ "vector" ]
b77d555183f1d3945bf351157cb24c5b1e2eff79
6,471
cpp
C++
server/main.cpp
akinaru/ssl-cert-dashboard
8bcef5b0fd8cc2dc885c5cc38a374451397bc475
[ "MIT" ]
1
2019-12-08T14:19:29.000Z
2019-12-08T14:19:29.000Z
server/main.cpp
akinaru/ssl-cert-dashboard
8bcef5b0fd8cc2dc885c5cc38a374451397bc475
[ "MIT" ]
null
null
null
server/main.cpp
akinaru/ssl-cert-dashboard
8bcef5b0fd8cc2dc885c5cc38a374451397bc475
[ "MIT" ]
null
null
null
/** * The MIT License (MIT) * * Copyright (c) 2015 Bertrand Martel * * 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. */ /** main.cpp launch Ssl dashboard server @author Bertrand Martel @version 1.0 */ #include <QCoreApplication> #include <iostream> #include <QStringList> #include <QDebug> #include "string" #include <sys/param.h> #include "SslHandler.h" #include "httpserverimpl/httpserver.h" #include "ClientSocketHandler.h" #include "HashDigestListener.h" #include "DigestManager.h" #include "database.h" #include "utils/fileutils.h" #include "qjson/parser.h" using namespace std; struct CleanExit{ CleanExit() { signal(SIGINT, &CleanExit::exitQt); signal(SIGTERM, &CleanExit::exitQt); } static void exitQt(int sig) { QCoreApplication::exit(0); } }; int main(int argc,char *argv[]){ CleanExit cleanExit; QCoreApplication a(argc,argv); int port = 4343; string ip = "127.0.0.1"; bool useSSL = false; string publicCert = ""; string privateCert = ""; string caCerts = ""; string privateKeyPass=""; string digestRealm = "bertrandmartel_realm"; string webpath="~/ssl-dashboard/web"; string keyFile="~/ssl-dashboard/rand.txt"; string algoStr = "MD5"; digest_algorithm digestAlgo = ALGO_MD5; //ignore SIGPIPE signal (broken pipe issue) signal(SIGPIPE, SIG_IGN); QStringList args = a.arguments(); string config =""; if (args.size() >1){ config=args[1].toStdString(); QByteArray fileData = fileutils::readFromFile((char*)config.data()); if (fileData.size()>0){ QJson::Parser parser; bool ok; // json is a QString containing the data to convert QVariantMap result = parser.parse(fileData.data(), &ok).toMap(); if (ok){ port = result["port"].toInt(); ip = result["ip"].toString().toStdString(); useSSL = result["useSSL"].toBool(); publicCert=result["publicCert"].toString().toStdString(); privateCert=result["privateCert"].toString().toStdString(); caCerts=result["caCerts"].toString().toStdString(); privateKeyPass=result["privateKeyPass"].toString().toStdString(); digestRealm=result["digestRealm"].toString().toStdString(); webpath=result["webPath"].toString().toStdString(); keyFile=result["keyFile"].toString().toStdString(); algoStr = result["digestAlgo"].toString().toStdString(); if (strcmp(algoStr.data(),"MD5")==0) digestAlgo=ALGO_MD5; else if (strcmp(algoStr.data(),"SHA1")==0) digestAlgo=ALGO_SHA1; else cerr << "Error algo must be MD5 or SHA1 (default MD5)" << endl; } else{ cerr << "Json configuration is inconsistent" << endl; } } } cout << "--------------------------------" << endl; cout << "Current configuration :" << endl; cout << "Port : " << port << endl; cout << "IP : " << ip.data() << endl; cout << "use ssl : " << useSSL << endl; cout << "public cert file : " << publicCert.data() << endl; cout << "private cert file : " << privateCert.data() << endl; cout << "ca certs file : " << caCerts.data() << endl; cout << "private key pass : " << privateKeyPass.data() << endl; cout << "digest realm : " << digestRealm.data() << endl; cout << "web path : " << webpath.data() << endl; cout << "key file : " << keyFile.data() << endl; cout << "digest algorithm : " << algoStr.data() << endl; cout << "--------------------------------" << endl; Database database; Database* db_ptr=&database; database.set_debug(true); database.setDigestParams(digestRealm,digestAlgo); database.setKey(fileutils::readFromFile((char*)keyFile.data())); database.init_user(); HashDigestListener digest_listener(db_ptr); DigestManager digest_manager; digest_manager.set_digest_algorithm(digestAlgo); digest_manager.set_session_type(SESSION_COOKIE); digest_manager.set_digest_listener(&digest_listener); ClientSocketHandler clientHandler(db_ptr,&digest_manager,webpath,digestRealm); //instance of HTTP server HttpServer server; server.set_debug(false); if (useSSL){ //set secured HTTP server server.setSSL(true); cout << "setting server certs ..." << endl; //set public / private and certification authority list into http server object server.setPublicCert(SslHandler::retrieveCertFromFile((char*)publicCert.data())); server.setPrivateCert(SslHandler::retrieveKeyCertFile((char*)privateCert.data(),(char*)privateKeyPass.data())); server.setCaCert(SslHandler::retrieveveCaCertListFromFile((char*)caCerts.data())); } server.addClientEventListener(&clientHandler); if (!server.listen(QHostAddress(ip.data()),port)) { qDebug() << "An error occured while initializing hope proxy server... Maybe another instance is already running on "<< ip.data() << ":" << port << endl; return -1; } cout << "Starting HTTP server on "<< ip.data() << ":" << port << endl; return a.exec(); }
34.057895
160
0.622315
[ "object" ]
b7833cfe50d307482608058394fe87d924124e98
993
cpp
C++
Part-I-The-Basics/Chapter-06-Move-Semantics-and-enable_if/basics/specialmemtmpl1.cpp
RingZEROtlf/Cpp-Templates-Complete-Guide
e5de63f89019b8d688a7807f88cb0d5f7028b345
[ "MIT" ]
null
null
null
Part-I-The-Basics/Chapter-06-Move-Semantics-and-enable_if/basics/specialmemtmpl1.cpp
RingZEROtlf/Cpp-Templates-Complete-Guide
e5de63f89019b8d688a7807f88cb0d5f7028b345
[ "MIT" ]
null
null
null
Part-I-The-Basics/Chapter-06-Move-Semantics-and-enable_if/basics/specialmemtmpl1.cpp
RingZEROtlf/Cpp-Templates-Complete-Guide
e5de63f89019b8d688a7807f88cb0d5f7028b345
[ "MIT" ]
null
null
null
#include <utility> #include <string> #include <iostream> class Person { private: std::string name; public: // constructor for passed initial name: explicit Person(std::string const& n) : name(n) { std::cout << "copying string-CONSTR for '" << name << "'\n"; } explicit Person(std::string&& n) : name(std::move(n)) { std::cout << "moving string-CONSTR for '" << name << "'\n"; } // copy and move constructor Person(Person const& p) : name(p.name) { std::cout << "COPY-CONSTR Person '" << name << "'\n"; } Person(Person&& p) : name(std::move(p.name)) { std::cout << "MOVE-CONSTR Person '" << name << "'\n"; } }; int main() { std::string s = "sname"; Person p1(s); // init with string object => calls copying string-CONSTR Person p2("tmp"); // init with string literal => calls moving string-CONSTR Person p3(p1); // copy Person => calls COPY-CONSTR Person p4(std::move(p1)); // move Person => calls MOVE-CONSTR }
30.090909
85
0.592145
[ "object" ]
b787dbccdd81a2e13e7de35c93e0c4c07a4a56eb
838
cpp
C++
test/snippet/range/views/trim_phred42.cpp
marehr/nomchop
a88bfb6f5d4a291a71b6b3192eeac81fdc450d43
[ "CC-BY-4.0", "CC0-1.0" ]
1
2021-03-01T11:12:56.000Z
2021-03-01T11:12:56.000Z
test/snippet/range/views/trim_phred42.cpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
2
2017-05-17T07:16:19.000Z
2020-02-13T16:10:10.000Z
test/snippet/range/views/trim_phred42.cpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
#include <string> #include <vector> #include <seqan3/alphabet/quality/phred42.hpp> #include <seqan3/range/views/trim.hpp> #include <seqan3/range/views/to_char.hpp> int main() { std::vector<seqan3::phred42> vec{seqan3::phred42{40}, seqan3::phred42{40}, seqan3::phred42{30}, seqan3::phred42{20}, seqan3::phred42{10}}; // trim by phred_value auto v1 = vec | seqan3::views::trim(20u); // == ['I','I','?','5'] // trim by quality character auto v2 = vec | seqan3::views::trim(seqan3::phred42{40}); // == ['I','I'] // function syntax auto v3 = seqan3::views::trim(vec, 20u); // == ['I','I','?','5'] // combinability auto v4 = seqan3::views::trim(vec, 20u) | seqan3::views::to_char; // == "II?5" }
33.52
99
0.5358
[ "vector" ]
b78f2df5b79a8f76664550167cbc5c9efe6c26cd
661
cpp
C++
Challenge-2020-11/27_partition_equal_subset_sum.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2020-11/27_partition_equal_subset_sum.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2020-11/27_partition_equal_subset_sum.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
#include "../header.h" class Solution { public: bool canPartition(vector<int>& nums) { int sum = accumulate(nums.begin(), nums.end(), 0); if (sum % 2 != 0) { return false; } int target = sum / 2; vector<bool> dp (target + 1, false); dp[0] = true; for (auto x: nums) { for (int i = target; i >= 0; i--) { if (dp[i] && i + x <= target) { dp[i + x] = true; // i + x will only be used in next round } } if (dp[target]) { return true; } } return false; } };
26.44
78
0.399395
[ "vector" ]
b78fd61e7200b918a7fc654f07ade28a1541426d
8,196
cpp
C++
src/server/rmlui/source/Core/StyleSheetContainer.cpp
PureTryOut/NymphCast
ffb76861dbdcba954789a55c62272f5302a47689
[ "BSD-3-Clause" ]
null
null
null
src/server/rmlui/source/Core/StyleSheetContainer.cpp
PureTryOut/NymphCast
ffb76861dbdcba954789a55c62272f5302a47689
[ "BSD-3-Clause" ]
null
null
null
src/server/rmlui/source/Core/StyleSheetContainer.cpp
PureTryOut/NymphCast
ffb76861dbdcba954789a55c62272f5302a47689
[ "BSD-3-Clause" ]
null
null
null
/* * This source file is part of RmlUi, the HTML/CSS Interface Middleware * * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * Copyright (c) 2019 The RmlUi Team, and contributors * * 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 "../../include/RmlUi/Core/StyleSheetContainer.h" #include "../../include/RmlUi/Core/Context.h" #include "../../include/RmlUi/Core/PropertyDictionary.h" #include "../../include/RmlUi/Core/Profiling.h" #include "../../include/RmlUi/Core/StyleSheet.h" #include "ComputeProperty.h" #include "StyleSheetParser.h" #include "Utilities.h" namespace Rml { StyleSheetContainer::StyleSheetContainer() { } StyleSheetContainer::~StyleSheetContainer() { } bool StyleSheetContainer::LoadStyleSheetContainer(Stream* stream, int begin_line_number) { StyleSheetParser parser; bool result = parser.Parse(media_blocks, stream, begin_line_number); return result; } bool StyleSheetContainer::UpdateCompiledStyleSheet(const Context* context) { RMLUI_ZoneScoped; const float dp_ratio = context->GetDensityIndependentPixelRatio(); const Vector2i vp_dimensions_i(context->GetDimensions()); const Vector2f vp_dimensions(vp_dimensions_i); Vector<int> new_active_media_block_indices; const float font_size = DefaultComputedValues.font_size; for (int media_block_index = 0; media_block_index < (int)media_blocks.size(); media_block_index++) { const MediaBlock& media_block = media_blocks[media_block_index]; bool all_match = true; for (const auto& property : media_block.properties.GetProperties()) { const MediaQueryId id = static_cast<MediaQueryId>(property.first); Vector2i ratio; switch (id) { case MediaQueryId::Width: if (vp_dimensions.x != ComputeLength(&property.second, font_size, font_size, dp_ratio, vp_dimensions)) all_match = false; break; case MediaQueryId::MinWidth: if (vp_dimensions.x < ComputeLength(&property.second, font_size, font_size, dp_ratio, vp_dimensions)) all_match = false; break; case MediaQueryId::MaxWidth: if (vp_dimensions.x > ComputeLength(&property.second, font_size, font_size, dp_ratio, vp_dimensions)) all_match = false; break; case MediaQueryId::Height: if (vp_dimensions.y != ComputeLength(&property.second, font_size, font_size, dp_ratio, vp_dimensions)) all_match = false; break; case MediaQueryId::MinHeight: if (vp_dimensions.y < ComputeLength(&property.second, font_size, font_size, dp_ratio, vp_dimensions)) all_match = false; break; case MediaQueryId::MaxHeight: if (vp_dimensions.y > ComputeLength(&property.second, font_size, font_size, dp_ratio, vp_dimensions)) all_match = false; break; case MediaQueryId::AspectRatio: ratio = Vector2i(property.second.Get<Vector2f>()); if (vp_dimensions_i.x * ratio.y != vp_dimensions_i.y * ratio.x) all_match = false; break; case MediaQueryId::MinAspectRatio: ratio = Vector2i(property.second.Get<Vector2f>()); if (vp_dimensions_i.x * ratio.y < vp_dimensions_i.y * ratio.x) all_match = false; break; case MediaQueryId::MaxAspectRatio: ratio = Vector2i(property.second.Get<Vector2f>()); if (vp_dimensions_i.x * ratio.y > vp_dimensions_i.y * ratio.x) all_match = false; break; case MediaQueryId::Resolution: if (dp_ratio != property.second.Get<float>()) all_match = false; break; case MediaQueryId::MinResolution: if (dp_ratio < property.second.Get<float>()) all_match = false; break; case MediaQueryId::MaxResolution: if (dp_ratio > property.second.Get<float>()) all_match = false; break; case MediaQueryId::Orientation: // Landscape (x > y) = 0 // Portrait (x <= y) = 1 if ((vp_dimensions.x <= vp_dimensions.y) != property.second.Get<bool>()) all_match = false; break; case MediaQueryId::Theme: if (!context->IsThemeActive(property.second.Get<String>())) all_match = false; break; // Invalid properties case MediaQueryId::Invalid: case MediaQueryId::NumDefinedIds: break; } if (!all_match) break; } if (all_match) new_active_media_block_indices.push_back(media_block_index); } const bool style_sheet_changed = (new_active_media_block_indices != active_media_block_indices || !compiled_style_sheet); if (style_sheet_changed) { StyleSheet* first_sheet = nullptr; UniquePtr<StyleSheet> new_sheet; for (int index : new_active_media_block_indices) { MediaBlock& media_block = media_blocks[index]; if (!first_sheet) first_sheet = media_block.stylesheet.get(); else if (!new_sheet) new_sheet = first_sheet->CombineStyleSheet(*media_block.stylesheet); else new_sheet->MergeStyleSheet(*media_block.stylesheet); } if (!first_sheet) { new_sheet.reset(new StyleSheet); first_sheet = new_sheet.get(); } compiled_style_sheet = (new_sheet ? new_sheet.get() : first_sheet); combined_compiled_style_sheet = std::move(new_sheet); compiled_style_sheet->BuildNodeIndex(); } active_media_block_indices = std::move(new_active_media_block_indices); return style_sheet_changed; } StyleSheet* StyleSheetContainer::GetCompiledStyleSheet() { return compiled_style_sheet; } SharedPtr<StyleSheetContainer> StyleSheetContainer::CombineStyleSheetContainer(const StyleSheetContainer& container) const { RMLUI_ZoneScoped; SharedPtr<StyleSheetContainer> new_sheet = MakeShared<StyleSheetContainer>(); for (const MediaBlock& media_block : media_blocks) { new_sheet->media_blocks.emplace_back(media_block.properties, media_block.stylesheet); } new_sheet->MergeStyleSheetContainer(container); return new_sheet; } void StyleSheetContainer::MergeStyleSheetContainer(const StyleSheetContainer& other) { RMLUI_ZoneScoped; // Style sheet container must not be merged after it's been compiled. This will invalidate references to the compiled style sheet. RMLUI_ASSERT(!compiled_style_sheet); auto it_other_begin = other.media_blocks.begin(); #if 0 // If the last block here has the same media requirements as the first block in other, we can safely merge them // while retaining correct specificity of all properties. This is essentially an optimization to avoid more // style sheet merging later on. if (!media_blocks.empty() && !other.media_blocks.empty()) { MediaBlock& block_local = media_blocks.back(); const MediaBlock& block_other = other.media_blocks.front(); if (block_local.properties.GetProperties() == block_other.properties.GetProperties()) { // Now we can safely merge the two style sheets. block_local.stylesheet = block_local.stylesheet->CombineStyleSheet(*block_other.stylesheet); // And we need to skip the first media block in the 'other' style sheet, since we merged it just now. ++it_other_begin; } } #endif // Add all the other blocks into ours. for (auto it = it_other_begin; it != other.media_blocks.end(); ++it) { const MediaBlock& block_other = *it; media_blocks.emplace_back(block_other.properties, block_other.stylesheet); } } } // namespace Rml
33.317073
131
0.741093
[ "vector" ]
b793eb1ab46de1c17ac265b475ede70e3a6cc479
9,088
hpp
C++
packages/dev-tools/src/ek/editor/gui/HierarchyWindow_impl.hpp
highduck/ekx
928300bd2af88dfddd92cc4e1754b9e53969640f
[ "0BSD" ]
12
2021-04-10T18:39:19.000Z
2022-02-01T05:21:42.000Z
packages/dev-tools/src/ek/editor/gui/HierarchyWindow_impl.hpp
highduck/ekx
928300bd2af88dfddd92cc4e1754b9e53969640f
[ "0BSD" ]
109
2021-09-09T23:53:45.000Z
2022-03-31T23:21:28.000Z
packages/dev-tools/src/ek/editor/gui/HierarchyWindow_impl.hpp
highduck/ekx
928300bd2af88dfddd92cc4e1754b9e53969640f
[ "0BSD" ]
3
2021-05-20T03:23:10.000Z
2022-01-10T14:22:31.000Z
#pragma once #include "HierarchyWindow.hpp" #include <ek/editor/imgui/imgui.hpp> #include <ek/scenex/base/Node.hpp> #include <ek/scenex/2d/Display2D.hpp> #include <ek/scenex/2d/Transform2D.hpp> #include <ek/scenex/base/Script.hpp> #include <ek/scenex/base/Interactive.hpp> #include <ek/scenex/3d/Light3D.hpp> #include <ek/scenex/2d/MovieClip.hpp> #include <ek/scenex/2d/Button.hpp> #include <ek/scenex/3d/Transform3D.hpp> #include <ek/scenex/2d/Viewport.hpp> #include <ek/scenex/2d/Camera2D.hpp> namespace ek { ecs::EntityApi HierarchyWindow::getSiblingNext(ecs::EntityApi e) { const auto* node = e.tryGet<Node>(); return node ? node->sibling_next : nullptr; } const char* HierarchyWindow::getEntityIcon(ecs::EntityApi e) { if (e.has<Camera2D>()) return ICON_FA_VIDEO; if (e.has<Viewport>()) return ICON_FA_TV; if (e.has<ScriptHolder>()) return ICON_FA_CODE; if (e.has<Bounds2D>()) return ICON_FA_EXPAND; if (e.has<Button>()) return ICON_FA_HAND_POINTER; if (e.has<Interactive>()) return ICON_FA_FINGERPRINT; if (e.has<MovieClip>()) return ICON_FA_FILM; if (e.has<Display2D>()) { const auto& disp = e.get<Display2D>(); if (disp.is<Sprite2D>()) return ICON_FA_IMAGE; if (disp.is<NinePatch2D>()) return ICON_FA_COMPRESS; if (disp.is<Quad2D>()) return ICON_FA_VECTOR_SQUARE; if (disp.is<Text2D>()) return ICON_FA_FONT; if (disp.is<Arc2D>()) return ICON_FA_CIRCLE_NOTCH; return ICON_FA_PAINT_BRUSH; } if (ecs::the_world.hasComponent<Transform3D>() && e.has<Transform3D>()) return ICON_FA_DICE_D20; if (e.has<Transform2D>()) return ICON_FA_DICE_D6; if (e.has<Node>()) return ICON_FA_BOX; return ICON_FA_BORDER_STYLE; } const char* HierarchyWindow::getEntityTitle(ecs::EntityApi e) { if (e.has<NodeName>()) { return e.get<NodeName>().name.c_str(); } return "Entity"; } bool HierarchyWindow::isSelectedInHierarchy(ecs::EntityApi e) { const ecs::EntityRef ref{e}; auto it = std::find(selection.begin(), selection.end(), ref); return it != selection.end(); } const void* HierarchyWindow::getEntityID(ecs::EntityApi e) { return reinterpret_cast<const void*>(ecs::EntityRef{e}.passport); } bool HierarchyWindow::hasChildren(ecs::EntityApi e) { if (e.has<Node>()) { auto& node = e.get<Node>(); auto first = node.child_first; return first != nullptr && first.isAlive(); } return false; } bool HierarchyWindow::hoverIconButton(const char* str_id, const char* icon) { ImGui::TextUnformatted(icon); return ImGui::IsItemClicked(); } void HierarchyWindow::drawVisibleTouchControls(Node* node, bool parentedVisible, bool parentedTouchable) { if (!node) { return; } ImGui::SameLine(0, 0); ImGui::SetCursorPosX(10); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (parentedVisible || !node->visible()) ? 1.0f : 0.5f); { const char* icon = node->visible() ? ICON_FA_EYE : ICON_FA_EYE_SLASH; if (hoverIconButton("visible", icon)) { node->setVisible(!node->visible()); } } ImGui::PopStyleVar(); ImGui::SameLine(0, 0); ImGui::SetCursorPosX(30); ImGui::PushStyleVar(ImGuiStyleVar_Alpha, (parentedTouchable || !node->touchable()) ? 1.0f : 0.5f); { const char* icon = node->touchable() ? ICON_FA_HAND_POINTER : ICON_FA_STOP; if (hoverIconButton("touchable", icon)) { node->setTouchable(!node->touchable()); } } ImGui::PopStyleVar(); } void HierarchyWindow::drawEntityInTree(ecs::EntityApi e, bool parentedVisible, bool parentedTouchable) { if (!e.isAlive()) { ImGui::Text("INVALID ENTITY"); return; } ImGui::PushID(getEntityID(e)); // ImGui::BeginGroup(); ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_NavLeftJumpsBackHere; if (isSelectedInHierarchy(e)) { flags |= ImGuiTreeNodeFlags_Selected; } if (!hasChildren(e)) { flags |= ImGuiTreeNodeFlags_Leaf; } auto nodeVisible = parentedVisible; auto nodeTouchable = parentedTouchable; auto* node = e.tryGet<Node>(); if (node) { nodeVisible = nodeVisible && node->visible(); nodeTouchable = nodeTouchable && node->touchable(); } ImGui::PushStyleColor(ImGuiCol_Text, nodeVisible ? 0xFFFFFFFF : 0x77FFFFFF); if(openList.has(e.index)) { ImGui::SetNextItemOpen(true); } if(scrollToList.has(e.index)) { ImGui::SetScrollHereY(); scrollToList.remove(e.index); } bool opened = ImGui::TreeNodeEx("entity", flags, "%s %s", getEntityIcon(e), getEntityTitle(e)); if (!opened) { openList.remove(e.index); } ImGui::PopStyleColor(); if (ImGui::IsItemClicked()) { selection.clear(); selection.push_back(ecs::EntityRef{e}); } drawVisibleTouchControls(node, parentedVisible, parentedTouchable); if (opened) { if (node) { auto it = node->child_first; while (it) { drawEntityInTree(it, nodeVisible, nodeTouchable); it = getSiblingNext(it); } } ImGui::TreePop(); } // ImGui::EndGroup(); ImGui::PopID(); } void HierarchyWindow::drawEntityFiltered(ecs::EntityApi e, bool parentedVisible, bool parentedTouchable) { if (!e.isAlive()) { ImGui::Text("INVALID ENTITY"); return; } auto* node = e.tryGet<Node>(); auto* name = e.tryGet<NodeName>(); auto nodeVisible = parentedVisible; auto nodeTouchable = parentedTouchable; if (node) { nodeVisible = nodeVisible && node->visible(); nodeTouchable = nodeTouchable && node->touchable(); } if (name && filter.PassFilter(name->name.c_str())) { ImGui::PushID(static_cast<int>(ecs::EntityRef{e}.passport)); ImGui::BeginGroup(); ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_NavLeftJumpsBackHere; if (isSelectedInHierarchy(e)) { flags |= ImGuiTreeNodeFlags_Selected; } // display all filtered entities just like a list flags |= ImGuiTreeNodeFlags_Leaf; ImGui::PushStyleColor(ImGuiCol_Text, nodeVisible ? 0xFFFFFFFF : 0x77FFFFFF); const bool opened = ImGui::TreeNodeEx("hierarchy_node", flags, "%s%s", getEntityIcon(e), getEntityTitle(e)); ImGui::PopStyleColor(); if (ImGui::IsItemClicked()) { selection.clear(); selection.push_back(ecs::EntityRef{e}); } drawVisibleTouchControls(node, parentedVisible, parentedTouchable); if (opened) { ImGui::TreePop(); } ImGui::EndGroup(); ImGui::PopID(); } if (node) { auto it = node->child_first; while (it) { drawEntityFiltered(it, nodeVisible, nodeTouchable); it = getSiblingNext(it); } } } void HierarchyWindow::drawFilter() { filter.Draw(ICON_FA_SEARCH "##hierarchy_filter", 100.0f); if (filter.IsActive()) { ImGui::SameLine(); if (ImGui::Button(ICON_FA_TIMES_CIRCLE)) { filter.Clear(); } } } void HierarchyWindow::onDraw() { drawFilter(); if (!root.valid()) { ImGui::TextColored({1, 0, 0, 1}, "No roots"); } else { ImGui::Indent(40.0f); if (filter.IsActive()) { drawEntityFiltered(root.get(), true, true); } else { drawEntityInTree(root.get(), true, true); } // for(auto e3d: ecs::view<Transform3D>()) { // if(e3d.get<NodeName>().name == "scene 3d") { // drawEntityInTree(e3d, true, true); // } // } ImGui::Unindent(40.0f); } } // remove any invalid refs from selection void HierarchyWindow::validateSelection() { unsigned i = 0; while (i < selection.size()) { if (selection[i].valid()) { ++i; } else { selection.eraseAt(i); } } } void HierarchyWindow::select(ecs::EntityApi e) { selection.clear(); if (e) { selection.push_back(ecs::EntityRef{e}); } } void HierarchyWindow::focus(ecs::EntityApi e) { if(e) { // open parents in hierarchy auto parent = e.get<Node>().parent; while (parent) { openList.set(parent.index, ecs::EntityRef{parent}); parent = parent.get<Node>().parent; } scrollToList.set(e.index, ecs::EntityRef{e}); } } }
30.80678
116
0.607835
[ "3d" ]
b79bd7ea3fbbb2ce5dba18c33975260c9164e9b6
6,218
cpp
C++
src/mplfe/test/fe_type_manager_test.cpp
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
796
2019-08-30T16:20:33.000Z
2021-12-25T14:45:06.000Z
src/mplfe/test/fe_type_manager_test.cpp
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
16
2019-08-30T18:04:08.000Z
2021-09-19T05:02:58.000Z
src/mplfe/test/fe_type_manager_test.cpp
harmonyos-mirror/OpenArkCompiler-test
1755550ea22eb185cbef8cc5864fa273caebf95a
[ "MulanPSL-1.0" ]
326
2019-08-30T16:11:29.000Z
2021-11-26T12:31:17.000Z
/* * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include "fe_manager.h" #include "fe_type_manager.h" #include "redirect_buffer.h" namespace maple { class FETypeManagerTest : public testing::Test, public RedirectBuffer { public: FETypeManagerTest() = default; ~FETypeManagerTest() = default; }; TEST_F(FETypeManagerTest, GetClassOrInterfaceType) { MIRStructType *structType = FEManager::GetTypeManager().GetClassOrInterfaceType("Ljava_2Flang_2FObject_3B"); EXPECT_NE(structType, nullptr); if (structType != nullptr) { std::string mplName = structType->GetCompactMplTypeName(); EXPECT_EQ(mplName, "Ljava_2Flang_2FObject_3B"); } MIRStructType *structTypeUnknown = FEManager::GetTypeManager().GetClassOrInterfaceType("LUnknown"); EXPECT_EQ(structTypeUnknown, nullptr); } TEST_F(FETypeManagerTest, GetClassOrInterfaceTypeFlag) { FETypeFlag flag = FEManager::GetTypeManager().GetClassOrInterfaceTypeFlag("Ljava_2Flang_2FObject_3B"); EXPECT_EQ(flag, FETypeFlag::kSrcMpltSys); FETypeFlag flagUnknown = FEManager::GetTypeManager().GetClassOrInterfaceTypeFlag("LUnknown"); EXPECT_EQ(flagUnknown, FETypeFlag::kDefault); } TEST_F(FETypeManagerTest, CreateClassOrInterfaceType) { MIRStructType *structType1 = FEManager::GetTypeManager().CreateClassOrInterfaceType("LNewClass", false, FETypeFlag::kSrcInput); EXPECT_NE(structType1, nullptr); if (structType1 != nullptr) { std::string mplName = structType1->GetCompactMplTypeName(); EXPECT_EQ(mplName, "LNewClass"); EXPECT_EQ(structType1->GetKind(), kTypeClassIncomplete); } MIRStructType *structType2 = FEManager::GetTypeManager().CreateClassOrInterfaceType("LNewInterface", true, FETypeFlag::kSrcInput); EXPECT_NE(structType2, nullptr); if (structType2 != nullptr) { std::string mplName = structType2->GetCompactMplTypeName(); EXPECT_EQ(mplName, "LNewInterface"); EXPECT_EQ(structType2->GetKind(), kTypeInterfaceIncomplete); } } TEST_F(FETypeManagerTest, GetOrCreateClassOrInterfaceType) { bool isCreate = false; MIRStructType *structType1 = FEManager::GetTypeManager().GetOrCreateClassOrInterfaceType("Ljava_2Flang_2FObject_3B", false, FETypeFlag::kSrcUnknown, isCreate); EXPECT_EQ(isCreate, false); ASSERT_NE(structType1, nullptr); std::string mplName1 = structType1->GetCompactMplTypeName(); EXPECT_EQ(mplName1, "Ljava_2Flang_2FObject_3B"); EXPECT_EQ(structType1->GetKind(), kTypeClass); MIRStructType *structType2 = FEManager::GetTypeManager().GetOrCreateClassOrInterfaceType("LNewClass2", false, FETypeFlag::kSrcUnknown, isCreate); EXPECT_EQ(isCreate, true); ASSERT_NE(structType2, nullptr); std::string mplName2 = structType2->GetCompactMplTypeName(); EXPECT_EQ(mplName2, "LNewClass2"); EXPECT_EQ(structType2->GetKind(), kTypeClassIncomplete); } TEST_F(FETypeManagerTest, GetOrCreateClassOrInterfacePtrType) { bool isCreate = false; MIRType *ptrType = FEManager::GetTypeManager().GetOrCreateClassOrInterfacePtrType("Ljava_2Flang_2FObject_3B", false, FETypeFlag::kSrcUnknown, isCreate); ASSERT_NE(ptrType, nullptr); RedirectCout(); ptrType->Dump(0); EXPECT_EQ(GetBufferString(), "<* <$Ljava_2Flang_2FObject_3B>>"); RestoreCout(); } TEST_F(FETypeManagerTest, GetOrCreateTypeFromName) { // Prim Type MIRType *typePrim = FEManager::GetTypeManager().GetOrCreateTypeFromName("I", FETypeFlag::kSrcUnknown, false); ASSERT_NE(typePrim, nullptr); EXPECT_EQ(typePrim, GlobalTables::GetTypeTable().GetInt32()); // Object Type MIRType *typeObject = FEManager::GetTypeManager().GetOrCreateTypeFromName("Ljava_2Flang_2FObject_3B", FETypeFlag::kSrcUnknown, true); ASSERT_NE(typeObject, nullptr); RedirectCout(); typeObject->Dump(0); EXPECT_EQ(GetBufferString(), "<* <$Ljava_2Flang_2FObject_3B>>"); RestoreCout(); // Array Type MIRType *typeArray = FEManager::GetTypeManager().GetOrCreateTypeFromName("ALjava_2Flang_2FObject_3B", FETypeFlag::kSrcUnknown, true); ASSERT_NE(typeArray, nullptr); RedirectCout(); typeArray->Dump(0); EXPECT_EQ(GetBufferString(), "<* <[] <* <$Ljava_2Flang_2FObject_3B>>>>"); RestoreCout(); // Array Type2 MIRType *typeArray2 = FEManager::GetTypeManager().GetOrCreateTypeFromName("AALjava_2Flang_2FObject_3B", FETypeFlag::kSrcUnknown, true); ASSERT_NE(typeArray2, nullptr); RedirectCout(); typeArray2->Dump(0); EXPECT_EQ(GetBufferString(), "<* <[] <* <[] <* <$Ljava_2Flang_2FObject_3B>>>>>>"); RestoreCout(); } } // namespace maple
47.830769
118
0.618044
[ "object" ]
b7a450c5083716564196f4d2dd03577bfb592d0c
440
cpp
C++
202102/4/_867_TransposeMatrix.cpp
uaniheng/leetcode-cpp
d7b4c9ef43cca8ecb703da5a910d79af61eb3394
[ "Apache-2.0" ]
null
null
null
202102/4/_867_TransposeMatrix.cpp
uaniheng/leetcode-cpp
d7b4c9ef43cca8ecb703da5a910d79af61eb3394
[ "Apache-2.0" ]
null
null
null
202102/4/_867_TransposeMatrix.cpp
uaniheng/leetcode-cpp
d7b4c9ef43cca8ecb703da5a910d79af61eb3394
[ "Apache-2.0" ]
null
null
null
// // Created by gyc on 2021/2/25. // #include "../../common.h" class Solution { public: vector<vector<int>> transpose(vector<vector<int>>& matrix) { int row = matrix.size(), col = matrix[0].size(); auto res = vector(col, vector(row, 0)); for(int i = 0; i < row; ++i) { for(int j = 0; j < col; ++j) { res[j][i] = matrix[i][j]; } } return res; } };
20
64
0.461364
[ "vector" ]
b7af13b7a055f0f7659aa85342cf564e49c2234d
8,856
inl
C++
code/Math/Include/T3DIntrRayTriangle.inl
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
1
2021-11-16T15:11:52.000Z
2021-11-16T15:11:52.000Z
code/Math/Include/T3DIntrRayTriangle.inl
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
null
null
null
code/Math/Include/T3DIntrRayTriangle.inl
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
null
null
null
/******************************************************************************* * This file is part of Tiny3D (Tiny 3D Graphic Rendering Engine) * Copyright (C) 2015-2020 Answer Wong * For latest info, see https://github.com/answerear/Tiny3D * * This program 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ namespace Tiny3D { template <typename T> inline TIntrRayTriangle<T>::TIntrRayTriangle() : mRay(nullptr) , mTriangle(nullptr) { } template <typename T> inline TIntrRayTriangle<T>::TIntrRayTriangle( const TRay<T> *ray, const TTriangle<T> *triangle) : mRay(ray) , mTriangle(triangle) { } template <typename T> inline TIntrRayTriangle<T>::TIntrRayTriangle( const TRay<T> &ray, const TTriangle<T> &triangle) : mRay(&ray) , mTriangle(&triangle) { } template <typename T> bool TIntrRayTriangle<T>::test() { if (mRay == nullptr || mTriangle == nullptr) return false; // 这里分两步检测 // 1. 计算射线和包含该三角形的平面的交点 // 2. 通过计算交点的重心坐标,来判断它是否在三角形中 // 计算逆时针的边向量 const TTriangle<T> &triangle = *mTriangle; TVector3<T> e1 = triangle[1] - triangle[0]; TVector3<T> e2 = triangle[2] - triangle[1]; // 计算表面法向量 TVector3<T> n = e1.cross(e2); // 计算倾斜角,表示靠近三角形 “正面” 的程度 float dot = n.dot(mRay->getDirection()); // 检查射线平行于三角形或未指向三角形正面的情况 if (dot >= TReal<T>::ZERO) { // 射线平行于三角形或者射线跟三角形法线同向 return false; } // 计算平面方程的 d 值,在右边使用带 d 的平面方程 // Ax + By + Cz = d float d = n.dot(triangle[0]); // 计算和包含三角形的平面的参数交点 float t = d - n.dot(mRay->getOrigin()); if (t >= TReal<T>::ZERO) { // 射线起点在多边形的背面 return false; } // t是射线起点到平面的距离,dot是射线长度在平面法线上的投影 if (t < dot) { // 射线不够长...... return false; } // 现在计算射线和平面的交点 t /= dot; // 计算 3D 交点 TVector3<T> p = mRay->getOrigin() + mRay->getDirection() * t; // 找到主要轴,选择投影平面,这里取巧,选择3个轴绝对值最大的轴抛弃掉 T u0, u1, u2; T v0, v1, v2; if (TMath<T>::abs(n.x()) > TMath<T>::abs(n.y())) { if (TMath<T>::abs(n.x()) > TMath<T>::abs(n.z())) { u0 = p.y() - triangle[0].y(); u1 = triangle[1].y() - triangle[0].y(); u2 = triangle[2].y() - triangle[0].y(); v0 = p.z() - triangle[0].z(); v1 = triangle[1].z() - triangle[0].z(); v2 = triangle[2].z() - triangle[0].z(); } else { u0 = p.x() - triangle[0].x(); u1 = triangle[1].x() - triangle[0].x(); u2 = triangle[2].x() - triangle[0].x(); v0 = p.y() - triangle[0].y(); v1 = triangle[1].y() - triangle[0].y(); v2 = triangle[2].y() - triangle[0].y(); } } else { if (TMath<T>::abs(n.y()) > TMath<T>::abs(n.z())) { u0 = p.x() - triangle[0].x(); u1 = triangle[1].x() - triangle[0].x(); u2 = triangle[2].x() - triangle[0].x(); v0 = p.z() - triangle[0].z(); v1 = triangle[1].z() - triangle[0].z(); v2 = triangle[2].z() - triangle[0].z(); } else { u0 = p.x() - triangle[0].x(); u1 = triangle[1].x() - triangle[0].x(); u2 = triangle[2].x() - triangle[0].x(); v0 = p.y() - triangle[0].y(); v1 = triangle[1].y() - triangle[0].y(); v2 = triangle[2].y() - triangle[0].y(); } } T temp = u1 * v2 - v1 * u2; if (temp == TReal<T>::ZERO) { return false; } temp = TReal<T>::ONE / temp; // 计算重心坐标,每一步都检查边界条件 T alpha = (u0 * v2 - v0 * u2) * temp; if (alpha < TReal<T>::ZERO) { return false; } T beta = (u1 * v0 - v1 * u0) * temp; if (beta < TReal<T>::ZERO) { return false; } T gamma = TReal<T>::ONE - alpha - beta; if (gamma < TReal<T>::ZERO) { return false; } return true; } template <typename T> bool TIntrRayTriangle<T>::test(TVector3<T> &intersection) { if (mRay == nullptr || mTriangle == nullptr) return false; // 这里分两步检测 // 1. 计算射线和包含该三角形的平面的交点 // 2. 通过计算交点的重心坐标,来判断它是否在三角形中 // 计算逆时针的变向量 const TTriangle<T> &triangle = *mTriangle; TVector3<T> e1 = triangle[1] - triangle[0]; TVector3<T> e2 = triangle[2] - triangle[1]; // 计算表面法向量 TVector3<T> n = e1.cross(e2); // 计算倾斜角,表示靠近三角形 “正面” 的程度 float dot = n.dot(mRay->getDirection()); // 检查射线平行于三角形或未指向三角形正面的情况 if (dot >= TReal<T>::ZERO) { // 射线平行于三角形或者射线跟三角形法线同向 return false; } // 计算平面方程的 d 值,在右边使用带 d 的平面方程 // Ax + By + Cz = d float d = n.dot(triangle[0]); // 计算和包含三角形的平面的参数交点 float t = d - n.dot(mRay->getOrigin()); if (t >= TReal<T>::ZERO) { // 射线起点在多边形的背面 return false; } // t是射线起点到平面的距离,dot是射线长度在平面法线上的投影 if (t < dot) { // 射线不够长...... return false; } // 现在计算射线和平面的交点 t /= dot; // 计算 3D 交点 TVector3<T> p = mRay->getOrigin() + mRay->getDirection() * t; // 找到主要轴,选择投影平面,这里取巧,选择3个轴绝对值最大的轴抛弃掉 T u0, u1, u2; T v0, v1, v2; if (TMath<T>::abs(n.x()) > TMath<T>::abs(n.y())) { if (TMath<T>::abs(n.x()) > TMath<T>::abs(n.z())) { u0 = p.y() - triangle[0].y(); u1 = triangle[1].y() - triangle[0].y(); u2 = triangle[2].y() - triangle[0].y(); v0 = p.z() - triangle[0].z(); v1 = triangle[1].z() - triangle[0].z(); v2 = triangle[2].z() - triangle[0].z(); } else { u0 = p.x() - triangle[0].x(); u1 = triangle[1].x() - triangle[0].x(); u2 = triangle[2].x() - triangle[0].x(); v0 = p.y() - triangle[0].y(); v1 = triangle[1].y() - triangle[0].y(); v2 = triangle[2].y() - triangle[0].y(); } } else { if (TMath<T>::abs(n.y()) > TMath<T>::abs(n.z)) { u0 = p.x() - triangle[0].x(); u1 = triangle[1].x() - triangle[0].x(); u2 = triangle[2].x() - triangle[0].x(); v0 = p.z() - triangle[0].z(); v1 = triangle[1].z() - triangle[0].z(); v2 = triangle[2].z() - triangle[0].z(); } else { u0 = p.x() - triangle[0].x(); u1 = triangle[1].x() - triangle[0].x(); u2 = triangle[2].x() - triangle[0].x(); v0 = p.y() - triangle[0].y(); v1 = triangle[1].y() - triangle[0].y(); v2 = triangle[2].y() - triangle[0].y(); } } T temp = u1 * v2 - v1 * u2; if (temp == TReal<T>::ZERO) { return false; } temp = TReal<T>::ONE / temp; // 计算重心坐标,每一步都检查边界条件 T alpha = (u0 * v2 - v0 * u2) * temp; if (alpha < TReal<T>::ZERO) { return false; } T beta = (u1 * v0 - v1 * u0) * temp; if (beta < TReal<T>::ZERO) { return false; } T gamma = TReal<T>::ONE - alpha - beta; if (gamma < TReal<T>::ZERO) { return false; } intersection = p; return true; } }
27.333333
81
0.432588
[ "3d" ]
5d9c79cbc9b151271f324e8164f8947bc35a67df
3,644
hpp
C++
include/util.hpp
sxyu/nivalis
3b05e3105ef640f6d24670d2ecff23ec6ab1d2d9
[ "Apache-2.0" ]
11
2020-05-17T04:13:52.000Z
2022-02-07T06:38:48.000Z
include/util.hpp
sxyu/nivalis
3b05e3105ef640f6d24670d2ecff23ec6ab1d2d9
[ "Apache-2.0" ]
null
null
null
include/util.hpp
sxyu/nivalis
3b05e3105ef640f6d24670d2ecff23ec6ab1d2d9
[ "Apache-2.0" ]
2
2021-03-17T09:57:36.000Z
2021-05-20T02:25:51.000Z
#pragma once #ifndef _UTIL_H_4EB09B11_F909_45C4_AD5D_8AA7A6644106 #define _UTIL_H_4EB09B11_F909_45C4_AD5D_8AA7A6644106 #include <string> #include <string_view> #include <vector> #include <ostream> #include <istream> namespace nivalis { namespace util { constexpr bool is_numeric(char c) { return (c >= '0' && c <= '9') || c == '.'; } // true if is literal char (a-zA-Z0-9_$'#&$) constexpr bool is_identifier(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\'' || c == '`' || c == '@' || is_numeric(c); } // true if can be first char of a variable name constexpr bool is_varname_first(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '\''; } // true if is comparison operator character constexpr bool is_comp_operator(char c) { return c == '>' || c == '=' || c == '<'; } // true if is logical operator character constexpr bool is_logic_operator(char c) { return c == '&' || c == '|'; } // true if is arithmetic operator character constexpr bool is_arith_operator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^'; } // true if is operator character constexpr bool is_operator(char c) { return is_comp_operator(c) || is_logic_operator(c) || is_arith_operator(c); } // true if is control character constexpr bool is_control(char c) { return c == '\\' || c == ':' || c == ',' || c == '@'; } // true if is open bracket constexpr bool is_open_bracket(char c) { return c == '(' || c == '[' || c == '{'; } // true if is close bracket constexpr bool is_close_bracket(char c) { return c == ')' || c == ']' || c == '}'; } // true if is bracket constexpr bool is_bracket(char c) { return is_open_bracket(c) || is_close_bracket(c); } // checks if string is valid variable name bool is_varname(std::string_view expr); // checks if string is a nonnegative integer (only 0-9) bool is_whole_number(std::string_view expr); // returns position of = (or </> if allow_ineq) in string, or -1 else // where = must: // 1. not be at index 0 or expr.size()-1 // 2. at top bracket level wrt ([{ // 3. (if enforce_no_adj_comparison) // not be followed/preceded by any comparison operator or ! size_t find_equality(std::string_view expr, bool allow_ineq = false, bool enforce_no_adj_comparison = true); // string trimming/strip void ltrim(std::string& s); void rtrim(std::string& s); void trim(std::string& s); // Put double in uint32_t vector void push_dbl(std::vector<uint32_t>& v, double value); // Read 2 uint32_t as a double double as_double(const uint32_t* ast); // Squared distance template <class T> T sqr_dist(T ax, T ay, T bx, T by) { return (ax-bx)*(ax-bx) + (ay-by)*(ay-by); } template<class T> /** Write binary to ostream */ inline void write_bin(std::ostream& os, T val) { os.write(reinterpret_cast<char*>(&val), sizeof(T)); } template<class T> /** Read binary from istream */ inline void read_bin(std::istream& is, T& val) { is.read(reinterpret_cast<char*>(&val), sizeof(T)); } template<class Resizable> /** Read a size_t from istream and resize v (vector/string) to it */ inline void resize_from_read_bin(std::istream& is, Resizable& v) { size_t sz; read_bin(is, sz); v.resize(sz); } // String replace (copy intentional) std::string str_replace(std::string_view src, std::string from, std::string_view to); } // namespace util } // namespace nivalis #endif // ifndef _UTIL_H_4EB09B11_F909_45C4_AD5D_8AA7A6644106
28.030769
85
0.618277
[ "vector" ]
5d9ec2e9bff6013977c572c1f19c72500ecb448c
14,260
cpp
C++
src/main.cpp
mmicko/RetroCommander
4e4090b77008e1e82ed1761b040b472200c7c454
[ "BSD-3-Clause" ]
1
2015-06-12T17:16:37.000Z
2015-06-12T17:16:37.000Z
src/main.cpp
mmicko/RetroCommander
4e4090b77008e1e82ed1761b040b472200c7c454
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
mmicko/RetroCommander
4e4090b77008e1e82ed1761b040b472200c7c454
[ "BSD-3-Clause" ]
1
2021-07-18T05:06:43.000Z
2021-07-18T05:06:43.000Z
/* * Copyright 2015 Miodrag Milanovic. All rights reserved. * License: http://www.opensource.org/licenses/BSD-3-Clause */ #include <string> #include <stdio.h> #include <stdlib.h> #include "common.h" #include <bgfx/bgfx.h> #include <bx/uint32_t.h> #include "imgui/imgui.h" #include "cmd.h" #include "input.h" #include <dirent.h> #include <vector> #include <sys/stat.h> #include <time.h> #include <direct.h> void displayMainMenu() { ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.00f, 0.56f, 0.56f, 1.0f)); ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0.00f, 0.25f, 0.25f, 1.00f)); ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(0.00f, 0.25f, 0.25f, 1.00f)); ImGui::PushStyleColor(ImGuiCol_HeaderActive, ImVec4(0.00f, 0.25f, 0.25f, 1.00f)); if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("Left")) { if (ImGui::MenuItem("Brief", "CTRL+1")) {} if (ImGui::MenuItem("Medium", "CTRL+2")) {} if (ImGui::MenuItem("Two columns", "CTRL+3")) {} if (ImGui::MenuItem("Full (name)", "CTRL+4")) {} if (ImGui::MenuItem("Full (size, time)", "CTRL+5")) {} if (ImGui::MenuItem("Full (access)", "CTRL+6")) {} ImGui::Separator(); if (ImGui::BeginMenu("Sort mode")) { ImGui::MenuItem("Name"); ImGui::MenuItem("Extension"); ImGui::MenuItem("Modif. Time"); ImGui::MenuItem("Size"); ImGui::MenuItem("Unsorted"); ImGui::EndMenu(); } if (ImGui::MenuItem("Change source")) {} ImGui::EndMenu(); } if (ImGui::BeginMenu("Files")) { if (ImGui::MenuItem("User menu", "F2")) {} if (ImGui::MenuItem("View", "F3")) {} if (ImGui::MenuItem("Edit", "F4")) {} if (ImGui::MenuItem("Copy", "F5")) {} if (ImGui::MenuItem("Rename or move", "F6")) {} if (ImGui::MenuItem("Make directory", "F7")) {} if (ImGui::MenuItem("Delete", "F8")) {} ImGui::Separator(); if (ImGui::MenuItem("File attributes", "CTRL+A")) {} if (ImGui::MenuItem("Apply command", "CTRL+G")) {} ImGui::Separator(); if (ImGui::MenuItem("Select group")) {} if (ImGui::MenuItem("Unselect group")) {} if (ImGui::MenuItem("Invert selection")) {} ImGui::EndMenu(); } if (ImGui::BeginMenu("Commands")) { if (ImGui::MenuItem("Find file", "ALT+F7")) {} if (ImGui::MenuItem("History", "ALT+F8")) {} if (ImGui::MenuItem("Maximize window", "ALT+F9")) {} ImGui::Separator(); if (ImGui::MenuItem("Panel on/off", "CTRL+O")) {} if (ImGui::MenuItem("Equal panels", "CTRL+=")) {} ImGui::EndMenu(); } if (ImGui::BeginMenu("Options")) { if (ImGui::MenuItem("Settings")) {} ImGui::EndMenu(); } if (ImGui::BeginMenu("Right")) { if (ImGui::MenuItem("Brief", "CTRL+1")) {} if (ImGui::MenuItem("Medium", "CTRL+2")) {} if (ImGui::MenuItem("Two columns", "CTRL+3")) {} if (ImGui::MenuItem("Full (name)", "CTRL+4")) {} if (ImGui::MenuItem("Full (size, time)", "CTRL+5")) {} if (ImGui::MenuItem("Full (access)", "CTRL+6")) {} ImGui::Separator(); if (ImGui::BeginMenu("Sort mode")) { ImGui::MenuItem("Name"); ImGui::MenuItem("Extension"); ImGui::MenuItem("Modif. Time"); ImGui::MenuItem("Size"); ImGui::MenuItem("Unsorted"); ImGui::EndMenu(); } if (ImGui::MenuItem("Change source")) {} ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); ImGui::PopStyleColor(); } static const InputBinding s_bindings[] = { { entry::Key::F10, entry::Modifier::None, 1, NULL, "exit" }, { entry::Key::F9, entry::Modifier::None, 1, NULL, "menu" }, INPUT_BINDING_END }; int cmdMenu(CmdContext* /*_context*/, void* /*_userData*/, int /*_argc*/, char const* const* /*_argv*/) { return 0; } struct file_descriptor { std::string name; std::string path; bool is_dir; bool is_reg; size_t size; std::string datetime; // TODO: separate "view data" (selected) from "underlying data" (files) bool is_selected; }; int strreplace(std::string &str, const std::string& search, const std::string& replace) { int searchlen = search.length(); int replacelen = replace.length(); int matches = 0; for (int curindex = str.find(search, 0); curindex != -1; curindex = str.find(search, curindex + replacelen)) { matches++; str.erase(curindex, searchlen).insert(curindex, replace); } return matches; } std::vector<file_descriptor> files; std::string fullpath; void readFiles(const char *path) { files.clear(); DIR* directory = opendir(path); if (directory != NULL) { struct dirent* dirent; struct stat stat_info; fullpath = std::string(path) + "\\"; while ((dirent = readdir(directory)) != NULL){ file_descriptor file; file.size = 0; file.is_dir = false; file.is_reg = false; file.name = std::string(dirent->d_name); file.path = fullpath + file.name; int s = stat(file.path.c_str(), &stat_info); if (s != -1) { if (S_ISREG(stat_info.st_mode)){ file.is_reg = true; } if (S_ISDIR(stat_info.st_mode)){ file.is_dir = true; } file.size = stat_info.st_size; char datetime[100]; const struct tm* time = localtime(&stat_info.st_mtime); strftime(datetime, 100, "%c", time); file.datetime = std::string(datetime); } file.is_selected = false; files.push_back(file); } } closedir(directory); } void displayPanel() { ImVec2 box0 = ImGui::GetWindowContentRegionMax(); box0.y = 15; box0.x -= 5; float loc[4]; ImGui::BeginChild("Sub0", box0, false); ImGui::Columns(4); ImGui::Text("Name"); loc[0] = ImGui::GetColumnOffset(); ImGui::NextColumn(); ImGui::Text("Ext"); loc[1] = ImGui::GetColumnOffset(); ImGui::NextColumn(); ImGui::Text("Size"); loc[2] = ImGui::GetColumnOffset(); ImGui::NextColumn(); ImGui::Text("Date"); loc[3] = ImGui::GetColumnOffset(); ImGui::NextColumn(); ImGui::Columns(1); ImGui::EndChild(); ImGui::Separator(); ImVec2 box = ImGui::GetWindowContentRegionMax(); box.y -= 60 + 35; box.x -= 5; ImGui::BeginChild("Sub1", box, false); ImGui::Columns(4); ImGui::SetColumnOffset(0,loc[0]); ImGui::SetColumnOffset(1,loc[1]); ImGui::SetColumnOffset(2,loc[2]); ImGui::SetColumnOffset(3,loc[3]); std::string open_dir; for (auto it = files.begin(); it != files.end(); ++it) { file_descriptor* fd = &(*it); char buf[100]; sprintf(buf, "%s", fd->name.c_str()); bool clicked = false;// ImGui::SelectableAllColumns(buf, fd->is_selected); bool hovered = ImGui::IsItemHovered(); if (clicked && ImGui::GetIO().KeyCtrl) { fd->is_selected ^= 1; } else if (hovered && ImGui::IsMouseDoubleClicked(0)) { if ((*it).is_dir) { char full[_MAX_PATH]; open_dir = fullpath + fd->name; _fullpath(full, open_dir.c_str(), _MAX_PATH); open_dir = std::string(full); } } else if (clicked) { for (std::vector<file_descriptor>::iterator it2 = files.begin(); it2 != files.end(); ++it2) (*it2).is_selected = false; fd->is_selected = true; /*if ((*it).is_dir) { fullpath += fd->name.c_str(); readFiles(fullpath.c_str()); }*/ //break; } ImGui::Text(buf); ImGui::NextColumn(); ImGui::Text(""); ImGui::NextColumn(); if ((*it).is_dir) { ImGui::Text("<DIR>"); ImGui::NextColumn(); } else { ImGui::Text("%d", (*it).size); ImGui::NextColumn(); } ImGui::Text("%s", (*it).datetime.c_str()); ImGui::NextColumn(); } ImGui::EndChild(); ImVec2 box2 = ImGui::GetWindowContentRegionMax(); box2.y = 50; box2.x -= 5; ImGui::BeginChild("Sub3", box2, false); ImGui::Columns(4); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Ext"); ImGui::NextColumn(); ImGui::Text("Size"); ImGui::NextColumn(); ImGui::Text("Date"); ImGui::NextColumn(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Ext"); ImGui::NextColumn(); ImGui::Text("Size"); ImGui::NextColumn(); ImGui::Text("Date"); ImGui::NextColumn(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Ext"); ImGui::NextColumn(); ImGui::Text("Size"); ImGui::NextColumn(); ImGui::Text("Date"); ImGui::NextColumn(); ImGui::Columns(1); ImGui::EndChild(); // process open directory after we are done iterating our files for the frame if (!open_dir.empty()) readFiles(open_dir.c_str()); } int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); imguiCreate(); entry::MouseState mouseState; // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); ImGuiStyle& style = ImGui::GetStyle(); // this struct has the colors style.WindowRounding = 0.0f; style.FrameRounding = 0.0f; style.Colors[ImGuiCol_Text] = ImVec4(1.0f, 1.00f, 1.00f, 1.00f); style.Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); style.Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.80f, 1.00f); style.Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); style.Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f); style.Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); style.Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input style.Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f); style.Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f); style.Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f); style.Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); style.Colors[ImGuiCol_MenuBarBg] = ImVec4(0.00f, 0.56f, 0.56f, 1.0f); style.Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.40f, 0.40f, 0.80f, 0.15f); style.Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); style.Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); style.Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); style.Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); style.Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); style.Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); style.Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); style.Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f); style.Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f); style.Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); style.Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); style.Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); style.Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); style.Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); style.Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f); style.Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f); style.Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); style.Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f); style.Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); style.Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); style.Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); style.Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); style.Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); style.Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); style.Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); style.Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); style.Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); style.Colors[ImGuiCol_TooltipBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); inputRemoveBindings("bindings"); inputAddBindings("bindings", s_bindings); cmdAdd("menu", cmdMenu); char cwd[1024]; getcwd(cwd, sizeof(cwd)); readFiles(cwd); while (!entry::processEvents(width, height, debug, reset, &mouseState)) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); imguiBeginFrame(mouseState.m_mx , mouseState.m_my , (mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0) | (mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0) , mouseState.m_mz , width , height ); displayMainMenu(); ImGui::SetNextWindowPos(ImVec2(0, 19)); ImGui::SetNextWindowSize(ImVec2(width / 2, height - 19)); if (ImGui::Begin(fullpath.c_str(), NULL, ImVec2(width / 2, height - 19), 1.0f, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar)) displayPanel(); ImGui::End(); ImGui::SetNextWindowPos(ImVec2(width / 2, 19)); ImGui::SetNextWindowSize(ImVec2(width / 2, height - 19)); if (ImGui::Begin("Right Panel", NULL, ImVec2(width / 2, height - 19), 1.0f, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar)) displayPanel(); ImGui::End(); // imgui test code //ImGui::ShowTestWindow(NULL); imguiEndFrame(); //bgfx::submit(0, NULL, 0); bgfx::frame(); } // Cleanup. imguiDestroy(); // Shutdown bgfx. bgfx::shutdown(); return 0; }
33.474178
231
0.622931
[ "vector" ]
5da17645372b912aee783726c58033a2e0e59253
4,598
cpp
C++
lz4.cpp
zsuzuki/test_cpp
05cfb4c53cfb245ae873e7ca06d991bdb6a9f64b
[ "MIT" ]
null
null
null
lz4.cpp
zsuzuki/test_cpp
05cfb4c53cfb245ae873e7ca06d991bdb6a9f64b
[ "MIT" ]
null
null
null
lz4.cpp
zsuzuki/test_cpp
05cfb4c53cfb245ae873e7ca06d991bdb6a9f64b
[ "MIT" ]
null
null
null
#include <array> #include <atomic> #include <chrono> #include <cstdint> #include <fstream> #include <future> #include <iostream> #include <lz4.h> #include <thread> #include <vector> namespace { constexpr size_t BLOCK_BYTES = 8 * 1024; using BLOCK = std::array<char, LZ4_COMPRESSBOUND(BLOCK_BYTES)>; using atmint = std::atomic_int; struct WriteInfo { char* buff_; int size_; std::mutex lock_; WriteInfo() = default; WriteInfo(const WriteInfo& o) { *this = o; } WriteInfo& operator=(const WriteInfo& o) { buff_ = o.buff_; size_ = o.size_; return *this; } }; void test_write(std::ofstream& ofst, WriteInfo& wi) { std::lock_guard g(wi.lock_); ofst.write((const char*)&wi.size_, sizeof(wi.size_)); ofst.write(wi.buff_, wi.size_); } void test_compress(std::ofstream& ofst, std::ifstream& ifst) { LZ4_stream_t lz4Stream; std::vector<BLOCK> inpBuf; std::vector<BLOCK> outBuf; inpBuf.resize(2); outBuf.resize(40); int inpBufIndex = 0; int outBufIndex = 0; atmint inPage = -1; atmint outPage = 0; std::vector<WriteInfo> wrlist; wrlist.resize(40); auto ntime = std::chrono::steady_clock::now(); LZ4_initStream(&lz4Stream, sizeof(lz4Stream)); auto f = std::async(std::launch::async, [&]() { while (inPage.load() != -2) { while (outPage.load() > inPage.load()) ; int page = outPage.load() % outBuf.size(); auto& winfo = wrlist[page]; test_write(ofst, winfo); outPage++; } std::cout << "done" << std::endl; }); for (;;) { int pn = inpBufIndex % 2; char* const inpPtr = inpBuf[pn].data(); ifst.read(inpPtr, BLOCK_BYTES); const int inpBytes = ifst.gcount(); if (0 == inpBytes) break; int opage = outBufIndex % outBuf.size(); auto& winfo = wrlist[opage]; auto& cmpBuf = outBuf[opage]; const int cmpBytes = LZ4_compress_fast_continue(&lz4Stream, inpPtr, cmpBuf.data(), inpBytes, cmpBuf.size(), 1); if (cmpBytes <= 0) break; { std::lock_guard g(winfo.lock_); winfo.size_ = cmpBytes; winfo.buff_ = cmpBuf.data(); inPage = outBufIndex; } outBufIndex++; inpBufIndex++; while ((inPage.load() - outPage.load()) > 5) ; } while (inPage.load() != outPage.load()) ; inPage = -2; f.wait(); ofst << 0; auto etime = std::chrono::steady_clock::now(); auto elapsed_time = std::chrono::duration_cast<std::chrono::milliseconds>(etime - ntime); std::cout << "Elapsed time: " << elapsed_time.count() << std::endl; } void test_decompress(std::ofstream& ofst, std::ifstream& ifst) { LZ4_streamDecode_t lz4StreamDecode_body; LZ4_streamDecode_t* lz4StreamDecode = &lz4StreamDecode_body; std::vector<BLOCK> decBuf; decBuf.resize(4); int decBufIndex = 0; LZ4_setStreamDecode(lz4StreamDecode, NULL, 0); for (;;) { char cmpBuf[LZ4_COMPRESSBOUND(BLOCK_BYTES)]; int cmpBytes = 0; { ifst.read((char*)&cmpBytes, sizeof(cmpBytes)); const size_t readCount0 = ifst.gcount(); if (readCount0 < 1 || cmpBytes <= 0) { break; } ifst.read(cmpBuf, cmpBytes); const size_t readCount1 = ifst.gcount(); if (readCount1 != (size_t)cmpBytes) { break; } } { char* const decPtr = decBuf[decBufIndex % decBuf.size()].data(); const int decBytes = LZ4_decompress_safe_continue(lz4StreamDecode, cmpBuf, decPtr, cmpBytes, BLOCK_BYTES); if (decBytes <= 0) { break; } ofst.write(decPtr, decBytes); } decBufIndex++; } std::cout << "done" << std::endl; } } // namespace // // // int main(int argc, char** argv) { auto help = []() { std::cerr << "lz4: [d] input output\n" "\td\tdecompress" << std::endl; }; if (argc < 3) { help(); return 1; } try { std::string arg = argv[1]; if (arg == "d") { // decompress if (argc < 4) { std::cout << "need output file" << std::endl; help(); return 1; } std::ifstream ifst(argv[2], std::ios::binary); std::ofstream ofst(argv[3], std::ios::binary); test_decompress(ofst, ifst); } else { // compress std::ifstream ifst(argv[1], std::ios::binary); std::ofstream ofst(argv[2], std::ios::binary); test_compress(ofst, ifst); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
22.105769
115
0.57699
[ "vector" ]
5db56ff82aac6180f5876d36defc3cba020d2be9
9,761
cpp
C++
computer-networks/labs-src/lab3/broadcast.cpp
vampy/university
9496cb63594dcf1cc2cec8650b8eee603f85fdab
[ "MIT" ]
6
2015-06-22T19:43:13.000Z
2019-07-15T18:08:41.000Z
computer-networks/labs-src/lab3/broadcast.cpp
vampy/university
9496cb63594dcf1cc2cec8650b8eee603f85fdab
[ "MIT" ]
null
null
null
computer-networks/labs-src/lab3/broadcast.cpp
vampy/university
9496cb63594dcf1cc2cec8650b8eee603f85fdab
[ "MIT" ]
1
2015-09-26T09:01:54.000Z
2015-09-26T09:01:54.000Z
#include "../os.hpp" #include "../udp.hpp" #include <thread> #include <chrono> #include <mutex> #include <atomic> #include <vector> #include <cstring> #include <ncurses.h> // Executable is kinda huge, because of all the libraries, TODO optimize /* send to broadcast address multiple listens on that broadcast address keep a list of clients posix threads one send broadcast thread - sleep(3) - send(time query) another send thread - sleep(10) - send(date query) another receive thread another main program: print the active list of peers struct Peer { struct sockaddr_in (IP si Port) int counter = 0; (increment when send timequery, deincrement when sending data and when the counter is 3 delete the peer } specify uses establish */ using namespace std; const uint16_t PORT = 7777; const uint16_t MAX_MESSAGE = 33; string NBCAST; atomic<int32_t> threads_count; atomic<bool> exit_program; #define WAIT_FOR_THREADS false // TODO fix this #define USE_NCURSES true #define SLEEP_THREAD(_amount) \ if (exit_program) break; \ this_thread::sleep_for(_amount); \ if (exit_program) break; struct Peer { sockaddr_in address; string time; // use time for malformed data string date; atomic<int32_t> counter; Peer(sockaddr_in *address) { counter = 1; time = ""; date = ""; memcpy(&(this->address), address, sizeof(sockaddr_in)); } }; class Peers { public: vector<Peer*> peers; vector<Peer*> wrong_peers; mutex mtx; int32_t found_position = -1; ~Peers() { for (uint32_t i = 0; i < peers.size(); i++) { Peer *peer = peers.at(i); DELETE(peer); } for (uint32_t i = 0; i < wrong_peers.size(); i++) { Peer *peer = wrong_peers.at(i); DELETE(peer); } } bool exists(sockaddr_in *address) { mtx.lock(); for (uint32_t i = 0; i < peers.size(); i++) { Peer *peer = peers.at(i); if (memcmp(address, &(peer->address), sizeof(sockaddr_in)) == 0) { found_position = i; mtx.unlock(); return true; } } mtx.unlock(); return false; } Peer *getFoundPeer() { assert(found_position != -1); return peers.at(found_position); } void add(Peer *peer) { mtx.lock(); peers.push_back(peer); mtx.unlock(); } void incrementCounters() { mtx.lock(); vector<int> remove_positions; // keep track of all positions we need to remove for (uint32_t i = 0; i < peers.size(); i++) { Peer *peer = peers.at(i); peer->counter++; if (peer->counter > 3) { remove_positions.push_back(i); } } for (int pos: remove_positions) { peers.erase(peers.begin() + pos); } mtx.unlock(); } void addWrongPeer(Peer *peer) { mtx.lock(); wrong_peers.push_back(peer); mtx.unlock(); } }; void int_handle(int signal) { if (USE_NCURSES) endwin(); exit_program = true; cout << "CTRL+C pressed" << endl; cout << "Waiting for threads to finish" << endl; if (WAIT_FOR_THREADS) while (threads_count > 2); // wait for threads // will continue into main else exit(0); } void handle_send_time(SafeSocketUDP *socket_send, Peers *peers) { threads_count++; if (!USE_NCURSES) cout << "Starting thread: send time" << endl; auto sleep_time = chrono::seconds(3); string message = "TIMEQUERY"; while (true) { SLEEP_THREAD(sleep_time) if (!USE_NCURSES) cout << "Sending: TIMEQUERY\0 (string)" << endl; socket_send->sendString(message); peers->incrementCounters(); } threads_count--; } void handle_send_date(SafeSocketUDP *socket_send) { threads_count++; if (!USE_NCURSES) cout << "Starting thread: send date" << endl; auto sleep_time = chrono::seconds(10); string message = "DATEQUERY"; while (true) { SLEEP_THREAD(sleep_time) if (!USE_NCURSES) cout << "Sending: DATEQUERY\0 (string)" << endl; socket_send->sendString(message); } threads_count--; } void handle_receive(Peers *peers) { threads_count++; if (!USE_NCURSES) cout << "Starting thread: receive" << endl; auto socket_receive = SafeSocketUDP(); socket_receive.open() ->setOptionReuseAddress() ->setAddress(PORT) // listen to local port 7777 ->bind(); char message[MAX_MESSAGE]; while (true) { if (exit_program) break; socket_receive.receive<char*>(message, MAX_MESSAGE); if (!USE_NCURSES) cout << "message = " << message << ", From = " << socket_receive.getFromIPString() << ":" << socket_receive.getFromPort() << endl; socket_receive.setAddressAsFromAddress(); bool exists = peers->exists(socket_receive.getFromAddressIPv4()), valid = false; if (strncmp("TIMEQUERY", message, 9) == 0) // received timequery { // SLEEP_THREAD(chrono::seconds(rand() % 5)); // have different times valid = true; string time = "TIME " + Time::getTime(); if (!USE_NCURSES) cout << "type TIMEQUERY: " << time << endl; socket_receive.sendString(time); } else if (strncmp("DATEQUERY", message, 9) == 0) // received datequery { valid = true; if (!USE_NCURSES) cout << "type DATEQUERY" << endl; string date = "DATE " + Time::getDate(); socket_receive.sendString(date); } else if (strncmp("TIME ", message, 5) == 0) // received time { valid = true; if (!USE_NCURSES) cout << "data TIME" << endl; if (exists) // update time { Peer *peer = peers->getFoundPeer(); peer->time = message; peer->counter--; // got response from peer } } else if (strncmp("DATE ", message, 5) == 0) // received date { valid = true; if (!USE_NCURSES) cout << "data DATE" << endl; if (exists) // update date { Peer *peer = peers->getFoundPeer(); peer->date = message; } } else { if (!USE_NCURSES) cout << "Invalid message data: " << message << endl; // log malformed data Peer *peer = new Peer(socket_receive.getFromAddressIPv4()); peer->time = message; peers->addWrongPeer(peer); } if (!exists && valid) // ADD peer { if (!USE_NCURSES) cout << "<<<<<<<<<<<<<<< ADDING PEER >>>>>>>>>>>" << endl; peers->add(new Peer(socket_receive.getFromAddressIPv4())); } if (!USE_NCURSES) cout << endl << endl; socket_receive.setAddress(PORT); } threads_count--; } void handle_main(Peers *peers) { threads_count++; if (!USE_NCURSES) { cout << "Starting thread: main" << endl; } #if !USE_NCURSES #define printw printf #endif chrono::milliseconds sleep_time; if (USE_NCURSES) { initscr(); sleep_time = chrono::milliseconds(50); } else { sleep_time = chrono::milliseconds(1000); } while (true) { SLEEP_THREAD(sleep_time) if (USE_NCURSES) clear(); printw("------------------------------------------------------------------------\nPeers:\n"); peers->mtx.lock(); for (Peer *peer : peers->peers) { printw("\t%s:%d\t\t%s %s, counter = %d\n\n", SafeSocket::getIPString(&(peer->address)).c_str(), SafeSocket::getPort(&(peer->address)), peer->time.c_str(), peer->date.c_str(), (int32_t)peer->counter); } peers->mtx.unlock(); printw("Malformed Data:\n"); for (Peer *peer : peers->wrong_peers) { printw("\t%s:%d - %s\n", SafeSocket::getIPString(&(peer->address)).c_str(), SafeSocket::getPort(&(peer->address)), peer->time.c_str()); } if (USE_NCURSES) refresh(); } if (USE_NCURSES) { endwin(); } threads_count--; } int main(int argc, char *argv[]) { // TODO set NBCAST argument from command line if (argc >= 2) // set from command line { NBCAST = argv[1]; } else // use default { NBCAST = "192.168.1.255"; } cout << "NBCAST = " << NBCAST << endl; Peers *peers = new Peers(); threads_count = 0; exit_program = false; signal(SIGINT, int_handle); SafeSocketUDP *socket_send = new SafeSocketUDP(); socket_send->open() ->setOptionReuseAddress() ->setOptionBroadcast() ->setAddress(PORT) // listen to local port 7777 ->bind() ->setAddress(NBCAST.c_str(), PORT); // send to broadcast address auto thread_send_time = thread(handle_send_time, socket_send, peers), thread_send_date = thread(handle_send_date, socket_send), thread_receive = thread(handle_receive, peers), thread_main = thread(handle_main, peers); thread_send_time.join(); thread_send_date.join(); thread_receive.join(); thread_main.join(); DELETE(socket_send); DELETE(peers); return 0; }
25.960106
120
0.543489
[ "vector" ]
5db791c805b58466c2036b5935e1d3a336399a83
3,481
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoCacheHint.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoCacheHint.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoCacheHint.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ /*! \class SoCacheHint SoCacheHint.h Inventor/nodes/SoCacheHint.h \brief The SoCacheHint class is a node containing hints about how to cache geometry. \ingroup nodes The SoCacheHint node is used to set up clues to the rendering subsystem about how Coin should cache vertex data. Please note that this is an experimental class. The API might change a lot before/if it's included in any official Coin release. <b>FILE FORMAT/DEFAULTS:</b> \code CacheHint { memValue 0.5 gfxValue 0.5 } \endcode */ /*! \var SoSFFloat SoCacheHint::memValue Sets the value for main memory usage. Should be a number between 0 and 1. A higher value will use more memory for caching. Default value is 0.5 */ /*! \var SoSFFloat SoCacheHint::gfxValue Sets the value for gfx memory usage. Should be a number between 0 and 1. A higher value will use more memory for caching. Default value is 0.5 */ #include <Inventor/nodes/SoCacheHint.h> #include <Inventor/actions/SoCallbackAction.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/actions/SoGetBoundingBoxAction.h> #include <Inventor/actions/SoPickAction.h> #include <Inventor/elements/SoCacheHintElement.h> #include "nodes/SoSubNodeP.h" // ************************************************************************* SO_NODE_SOURCE(SoCacheHint); /*! Constructor. */ SoCacheHint::SoCacheHint(void) { SO_NODE_INTERNAL_CONSTRUCTOR(SoCacheHint); SO_NODE_ADD_FIELD(memValue, (0.5f)); SO_NODE_ADD_FIELD(gfxValue, (0.5f)); } /*! Destructor. */ SoCacheHint::~SoCacheHint() { } // doc in super void SoCacheHint::initClass(void) { SO_NODE_INTERNAL_INIT_CLASS(SoCacheHint, SO_FROM_COIN_2_4); SO_ENABLE(SoGLRenderAction, SoCacheHintElement); } void SoCacheHint::doAction(SoAction * action) { SoState * state = action->getState(); SoCacheHintElement::set(state, this, this->memValue.getValue(), this->gfxValue.getValue()); } void SoCacheHint::GLRender(SoGLRenderAction * action) { SoCacheHint::doAction(action); } void SoCacheHint::callback(SoCallbackAction * action) { // do nothing SoNode::callback(action); } void SoCacheHint::pick(SoPickAction * action) { // do nothing SoNode::pick(action); } void SoCacheHint::getBoundingBox(SoGetBoundingBoxAction * action) { // do nothing SoNode::getBoundingBox(action); }
25.408759
86
0.675955
[ "geometry", "3d" ]
5dbaf6b92b59826ab47a1bb7a33b162417645efc
1,266
hpp
C++
src/axom/klee/tests/KleeTestUtils.hpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
86
2019-04-12T20:39:37.000Z
2022-01-28T17:06:08.000Z
src/axom/klee/tests/KleeTestUtils.hpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
597
2019-04-25T22:36:16.000Z
2022-03-31T20:21:54.000Z
src/axom/klee/tests/KleeTestUtils.hpp
bmhan12/axom
fbee125aec6357340f35b6fd5d0d4a62a3c80733
[ "BSD-3-Clause" ]
21
2019-06-27T15:53:08.000Z
2021-09-30T20:17:41.000Z
// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #ifndef AXOM_KLEETESTUTILS_HPP #define AXOM_KLEETESTUTILS_HPP #include <array> #include "axom/core/numerics/Matrix.hpp" #include "axom/klee/GeometryOperators.hpp" #include "axom/primal/geometry/Point.hpp" #include "axom/primal/geometry/Vector.hpp" #include "gmock/gmock.h" namespace axom { namespace klee { namespace test { /** * Create a 3D affine transformation matrix * * \param values the values of the matrix, in row-major order * \return the affine transformation matrix represented by the rows */ numerics::Matrix<double> affine(const std::array<std::array<double, 4>, 3> &values); class MockOperator : public GeometryOperator { public: using GeometryOperator::GeometryOperator; MOCK_METHOD(TransformableGeometryProperties, getEndProperties, (), (const)); MOCK_METHOD(void, accept, (GeometryOperatorVisitor &), (const)); TransformableGeometryProperties getBaseEndProperties() const { return GeometryOperator::getEndProperties(); } }; } // namespace test } // namespace klee } // namespace axom #endif //AXOM_KLEETESTUTILS_HPP
25.836735
84
0.759084
[ "geometry", "vector", "3d" ]
5dbd4fc793421d3f5009b60e2945b0e73c645cd4
2,135
cpp
C++
Love-Babbar-450-In-CPPTest/08_greedy/01_activity_selection_problem.cpp
harshanu11/Love-Babbar-450-In-CSharp
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
[ "MIT" ]
null
null
null
Love-Babbar-450-In-CPPTest/08_greedy/01_activity_selection_problem.cpp
harshanu11/Love-Babbar-450-In-CSharp
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
[ "MIT" ]
null
null
null
Love-Babbar-450-In-CPPTest/08_greedy/01_activity_selection_problem.cpp
harshanu11/Love-Babbar-450-In-CSharp
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
[ "MIT" ]
null
null
null
/* link: https://practice.geeksforgeeks.org/problems/n-meetings-in-one-room-1587115620/1 custom sort function to sort the finishing time. why static ? in some online judge platform we have to keep it static so it wont change in lifetime of the program. */ #include "CppUnitTest.h" #include <iostream> #include <algorithm> #include <vector> #include <map> #include <unordered_set> #include <set> #include <unordered_map> #include <queue> #include <stack> using namespace std; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace LoveBabbar450InCPPTest { TEST_CLASS(Greedy) { public: TEST_METHOD(ActivitySelectionTest) { // Starting time int s[] = { 1, 3, 0, 5, 8, 5 }; // Finish time int f[] = { 2, 4, 6, 7, 9, 9 }; // Number of meetings. int n = sizeof(s) / sizeof(s[0]); // Function call maxMeetings(s, f, n); } // ----------------------------------------------------------------------------------------------------------------------- // bool static compare(pair<int, int> meeting1, pair<int, int> meeting2) { if (meeting1.second == meeting2.second) return meeting1.first < meeting2.first; return meeting1.second < meeting2.second; } int maxMeetings(int start[], int end[], int n) { // using vector pair as we want to sort acc. to the finishing time vector<pair<int, int>> timeTable(n); for (int i = 0; i < n; i++) { timeTable[i] = { start[i], end[i] }; } sort(timeTable.begin(), timeTable.end(), compare); int temp = INT_MIN; int meetings = 0; for (pair<int, int> p : timeTable) { // whenever we have starting time larger than prev. finishing time add meeting to room if (p.first > temp) { temp = p.second; meetings++; } } return meetings; } }; }
28.466667
133
0.512881
[ "vector" ]
5dc4e91ebd16b7b02475147e83055158927e75b4
5,147
hpp
C++
SU2-Quantum/SU2_CFD/include/output/filewriter/CSurfaceFVMDataSorter.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/include/output/filewriter/CSurfaceFVMDataSorter.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/SU2_CFD/include/output/filewriter/CSurfaceFVMDataSorter.hpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file CSurfaceFVMDataSorter.hpp * \brief Headers for the surface FVM data sorter class. * \author T. Albring * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "CParallelDataSorter.hpp" #include "CFVMDataSorter.hpp" class CSurfaceFVMDataSorter final: public CParallelDataSorter{ CFVMDataSorter* volumeSorter; //!< Pointer to the volume sorter instance map<unsigned long,unsigned long> Renumber2Global; //! Structure to map the local sorted point ID to the global point ID public: /*! * \brief Construct a file writer using field names and the data sorter. * \param[in] config - Pointer to the current config structure * \param[in] geometry - Pointer to the current geometry * \param[in] valVolumeSorter - The datasorter containing the volume data */ CSurfaceFVMDataSorter(CConfig *config, CGeometry* geometry, CFVMDataSorter* valVolumeSorter); /*! * \brief Destructor */ ~CSurfaceFVMDataSorter() override; /*! * \brief Sort the output data for each grid node into a linear partitioning across all processors. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. */ void SortOutputData() override; /*! * \brief Sort the connectivities on the surface into data structures used for output file writing. * All markers in MARKER_PLOTTING will be sorted. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. * \param[in] val_sort - boolean controlling whether surface <TRUE> or volume connectivity <FALSE> should be sorted. */ void SortConnectivity(CConfig *config, CGeometry *geometry, bool val_sort) override; /*! * \brief Sort the connectivities (volume and surface) into data structures used for output file writing. * Only markers in the markerList argument will be sorted. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. * \param[in] markerList - List of markers to sort. */ void SortConnectivity(CConfig *config, CGeometry *geometry, const vector<string> &markerList) override; /*! * \brief Get the global index of a point. * \param[in] iPoint - the local renumbered point ID. * \return Global index of a specific point. */ unsigned long GetGlobalIndex(unsigned long iPoint) const override{ if (iPoint > nPoints) SU2_MPI::Error(string("Local renumbered iPoint ID ") + to_string(iPoint) + string(" is larger than max number of nodes ") + to_string(nPoints), CURRENT_FUNCTION); return Renumber2Global.at(iPoint); } /*! * \brief Get the beginning global renumbered node ID of the linear partition owned by a specific processor. * \param[in] rank - the processor rank. * \return The beginning global renumbered node ID. */ unsigned long GetNodeBegin(unsigned short rank) const override { return nPoint_Recv[rank]; } /*! * \brief Get the Processor ID a Point belongs to. * \param[in] iPoint - global renumbered ID of the point * \return The rank/processor number. */ unsigned short FindProcessor(unsigned long iPoint) const override { for (unsigned short iRank = 1; iRank < size; iRank++){ if (nPoint_Recv[iRank] > static_cast<int>(iPoint)){ return iRank - 1; } } return size-1; } /*! * \brief Get the cumulated number of points * \input rank - the processor rank. * \return The cumulated number of points up to certain processor rank. */ unsigned long GetnPointCumulative(unsigned short rank) const override { return GetNodeBegin(rank); } private: /*! * \brief Sort the connectivity for a single surface element type into a linear partitioning across all processors. * \param[in] config - Definition of the particular problem. * \param[in] geometry - Geometrical definition of the problem. * \param[in] Elem_Type - VTK index of the element type being merged. * \param[in] markerList - List of markers to sort */ void SortSurfaceConnectivity(CConfig *config, CGeometry *geometry, unsigned short Elem_Type, const vector<string> &markerList); };
38.125926
121
0.70818
[ "geometry", "vector" ]
5dcb52d8c3a51d4af7d29c0186bfc447902549b4
4,518
cpp
C++
code/my_vector.cpp
XXY911/Skill-Tree
3478d8d10e288c9d929499ccd6dc9b024cea0991
[ "MIT" ]
11
2018-06-04T03:08:42.000Z
2021-06-18T07:56:19.000Z
code/my_vector.cpp
ccechod/Skill-Tree
d5d480ef24251e054c4915d14685c75074b88ac6
[ "MIT" ]
null
null
null
code/my_vector.cpp
ccechod/Skill-Tree
d5d480ef24251e054c4915d14685c75074b88ac6
[ "MIT" ]
5
2018-12-21T03:21:20.000Z
2019-12-17T08:59:34.000Z
#include <iostream> #include <assert.h> #define DOUBLE_SIZE using namespace std; template <typename T> class Vector { private: const int ADD_SIZE = 64; T *array; unsigned int vsize; unsigned int vcapacity; T *allocator(unsigned int size); void destory(T *array); public: Vector():array(0), vsize(0), vcapacity(0){} Vector(const T& t, unsigned int n); Vector(const Vector<T>& other); Vector<T>& operator =(Vector<T>& other); T &operator[](unsigned int pos); unsigned int size(); unsigned int capacity(); bool empty(); void clear(); void push_back(const T& t); void insert_after(int pos, const T& t); void push_front(const T& t); void insert_before(int pos, const T& t); void erase(unsigned int pos); void print(); ~Vector() { clear(); } }; template <typename T> Vector<T>::Vector(const T& t, unsigned int n):array(0), vsize(0), vcapacity(0) { while(n--) { push_back(t); } } template <typename T> Vector<T>::Vector(const Vector<T>& other) { array = other.array; vsize = other.vsize; vcapacity = other.vcapacity; } template <typename T> unsigned int Vector<T>::size() { return vsize; } template <typename T> unsigned int Vector<T>::capacity() { return vcapacity; } template <typename T> bool Vector<T>::empty() { return (vsize == 0); } template <typename T> void Vector<T>::clear() { destory(array); array = 0; vsize = 0; vcapacity = 0; } template <typename T> void Vector<T>::push_back(const T& t) { insert_after(vsize - 1, t); } template <typename T> void Vector<T>::insert_after(int pos, const T& t) { insert_before(pos + 1, t); } template <typename T> void Vector<T>::push_front(const T& t) { insert_before(0, t); } template <typename T> void Vector<T>::insert_before(int pos, const T& t) { if(vsize == vcapacity) { T *old_array = array; #ifdef DOUBLE_SIZE if(vcapacity == 0) vcapacity = 1; vcapacity = vcapacity << 1; #else vcapacity += ADD_SIZE; #endif array = allocator(vcapacity); for (unsigned int i = 0; i < vsize; ++i) array[i] = old_array[i]; destory(old_array); } for(int i = (int)vsize++; i > pos; --i) array[i] = array[i - 1]; array[pos] = t; } template <typename T> void Vector<T>::erase(unsigned int pos) { if(pos < vsize) { --vsize; for(unsigned int i = pos; i < vsize; ++i) array[i] = array[i + 1]; } } template <typename T> void Vector<T>::print() { for(unsigned int i = 0; i < size(); ++i) { cout << array[i] << " "; } cout << endl; cout << "Real time size = " << size() << endl; cout << "The capacity = " << capacity() << endl << endl; } template <typename T>T* Vector<T>::allocator(unsigned int size){ return new T[size]; } template <typename T> void Vector<T>::destory(T *array) { if(array) delete[] array; } template <typename T> Vector<T>& Vector<T>::operator =(Vector<T>& other) { /* 1. 判断是否为同一个对象 * 2. 清空本身变量、释放申请的内存 * 3. 重新申请内存 * 4. 逐字节复制(深拷贝) */ if(this == &other) return *this; clear(); vsize = other.size(); vcapacity = other.capacity(); array = new T[vcapacity]; for(unsigned int i = 0; i < vsize; ++i) { array[i] = other[i]; } return *this; } template <typename T> T& Vector<T>::operator[](unsigned int pos) { assert(pos < vsize); return array[pos]; } int main() { Vector<int> my_vector; // 插入元素 my_vector.push_back(1); my_vector.push_back(2); my_vector.push_back(3); my_vector.push_front(0); if(my_vector.size() == 4) my_vector.print(); // 删除元素(i为下标) my_vector.erase(1); if((!my_vector.empty()) && my_vector.capacity() == 64) my_vector.print(); // 清空 my_vector.clear(); if(my_vector.empty()) cout << "Vector is empty !" << endl << endl; // 测试动态扩展 for(int i = 0; i < 100; i++) my_vector.push_back(i); my_vector.print(); // 测试拷贝构造函数(浅拷贝) Vector<int> my_vector_2(my_vector); /* * my_vector.clear(); * 调用此句会出错,my_vector指向的内存被释放 * my_vector_2中array指针为野指针 */ my_vector_2.print(); // 测试=重载运算符 Vector<int> my_vector_1(0, 10); my_vector_1 = my_vector; my_vector_1.print(); // 测试[]重载运算符 int n; cin >> n; cout << "The " << n << "th element = " << my_vector[n] << endl << endl; return 0; }
25.525424
102
0.578796
[ "vector" ]
5dcd36901edb59bc15a817f19d1935a4a38f8e40
727
cpp
C++
src/function/interpret.cpp
ujtakk/fixednets
b7681947852a2bacd78290a34fc4c48e492ce2d5
[ "MIT" ]
null
null
null
src/function/interpret.cpp
ujtakk/fixednets
b7681947852a2bacd78290a34fc4c48e492ce2d5
[ "MIT" ]
null
null
null
src/function/interpret.cpp
ujtakk/fixednets
b7681947852a2bacd78290a34fc4c48e492ce2d5
[ "MIT" ]
null
null
null
#ifdef _INTERPRET_HPP_ #include <numeric> template <typename T> int classify(Mat1D<T> probs) { const int len = probs.size(); int number = -1; T temp = std::numeric_limits<T>::min(); for (int i = 0; i < len; ++i) { if (temp < probs[i]) { temp = probs[i]; number = i; } } return number; } template <typename T> std::vector<int> classify_top(Mat1D<T> probs, int range) { const int len = probs.size(); std::vector<int> number(range, -1); std::vector<int> index(len); iota(index.begin(), index.end(), 0); sort(index.begin(), index.end(), [&](int a, int b) { return probs[a] > probs[b]; }); for (int i = 0; i < range; ++i) number[i] = index[i]; return number; } #endif
18.175
56
0.581843
[ "vector" ]
5dd3e36a45eac0e429158d1c65f04bef52222205
9,856
cpp
C++
unit_tests/zero_page_mode_ROR.cpp
vcato/qt-quick-6502-emulator
6202e546efddc612f229da078238f829dd756e12
[ "Unlicense" ]
null
null
null
unit_tests/zero_page_mode_ROR.cpp
vcato/qt-quick-6502-emulator
6202e546efddc612f229da078238f829dd756e12
[ "Unlicense" ]
3
2019-09-14T02:46:26.000Z
2020-12-22T01:07:08.000Z
unit_tests/zero_page_mode_ROR.cpp
vcato/qt-quick-6502-emulator
6202e546efddc612f229da078238f829dd756e12
[ "Unlicense" ]
null
null
null
#include "addressing_mode_helpers.hpp" struct ROR_ZeroPage_Expectations { NZCFlags flags; uint8_t operand; // Data to be operated upon in Zero Page }; using RORZeroPage = ROR<ZeroPage, ROR_ZeroPage_Expectations, 5>; using RORZeroPageMode = ParameterizedInstructionExecutorTestFixture<RORZeroPage>; static void StoreTestValueAtEffectiveAddress(InstructionExecutorTestFixture &fixture, const RORZeroPage &instruction_param) { fixture.fakeMemory[instruction_param.address.zero_page_address] = instruction_param.requirements.initial.operand; } static void SetupAffectedOrUsedRegisters(InstructionExecutorTestFixture &fixture, const RORZeroPage &instruction_param) { fixture.r.SetFlag(FLAGS6502::N, instruction_param.requirements.initial.flags.n_value.expected_value); fixture.r.SetFlag(FLAGS6502::Z, instruction_param.requirements.initial.flags.z_value.expected_value); fixture.r.SetFlag(FLAGS6502::C, instruction_param.requirements.initial.flags.c_value.expected_value); } template<> void LoadInstructionIntoMemoryAndSetRegistersToInitialState( InstructionExecutorTestFixture &fixture, const RORZeroPage &instruction_param) { SetupRAMForInstructionsThatHaveAnEffectiveAddress(fixture, instruction_param); SetupAffectedOrUsedRegisters(fixture, instruction_param); } template<> void RegistersAreInExpectedState(const Registers &registers, const ROR_ZeroPage_Expectations &expectations) { EXPECT_THAT(registers.GetFlag(FLAGS6502::N), Eq(expectations.flags.n_value.expected_value)); EXPECT_THAT(registers.GetFlag(FLAGS6502::Z), Eq(expectations.flags.z_value.expected_value)); EXPECT_THAT(registers.GetFlag(FLAGS6502::C), Eq(expectations.flags.c_value.expected_value)); } template<> void MemoryContainsInstruction(const InstructionExecutorTestFixture &fixture, const Instruction<AbstractInstruction_e::ROR, ZeroPage> &instruction) { EXPECT_THAT(fixture.fakeMemory.at( fixture.executor.registers().program_counter ), Eq( OpcodeFor(AbstractInstruction_e::ROR, AddressMode_e::ZeroPage) )); EXPECT_THAT(fixture.fakeMemory.at( fixture.executor.registers().program_counter + 1), Eq(instruction.address.zero_page_address)); } template<> void MemoryContainsExpectedComputation(const InstructionExecutorTestFixture &fixture, const RORZeroPage &instruction) { EXPECT_THAT(fixture.fakeMemory.at( instruction.address.zero_page_address ), Eq(instruction.requirements.initial.operand)); } template<> void MemoryContainsExpectedResult(const InstructionExecutorTestFixture &fixture, const RORZeroPage &instruction) { EXPECT_THAT(fixture.fakeMemory.at( instruction.address.zero_page_address ), Eq(instruction.requirements.final.operand)); } static const std::vector<RORZeroPage> RORZeroPageModeTestValues { RORZeroPage{ // Beginning of a page ZeroPage().address(0x8000).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { }, .operand = 0 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = true }, .c_value = { .expected_value = false } }, .operand = 0 }} }, RORZeroPage{ // Middle of a page ZeroPage().address(0x8080).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = true }, .c_value = { .expected_value = true } }, .operand = 0 }, .final = { .flags = { .n_value = { .expected_value = true }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b10000000 }} }, RORZeroPage{ // End of a page ZeroPage().address(0x80FE).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00000001 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = true }, .c_value = { .expected_value = true } }, .operand = 0 }} }, RORZeroPage{ // Crossing a page boundary ZeroPage().address(0x80FF).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = true } }, .operand = 0b00000001 }, .final = { .flags = { .n_value = { .expected_value = true }, .z_value = { .expected_value = false }, .c_value = { .expected_value = true } }, .operand = 0b10000000 }} }, // Check the bit shift through each bit RORZeroPage{ ZeroPage().address(0x8000).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = true }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b10000000 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b01000000 }} }, RORZeroPage{ ZeroPage().address(0x8000).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b01000000 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00100000 }} }, RORZeroPage{ ZeroPage().address(0x8000).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00100000 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00010000 }} }, RORZeroPage{ ZeroPage().address(0x8000).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00010000 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00001000 }} }, RORZeroPage{ ZeroPage().address(0x8000).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00001000 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00000100 }} }, RORZeroPage{ ZeroPage().address(0x8000).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00000100 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00000010 }} }, RORZeroPage{ ZeroPage().address(0x8000).zp_address(6), RORZeroPage::Requirements{ .initial = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00000010 }, .final = { .flags = { .n_value = { .expected_value = false }, .z_value = { .expected_value = false }, .c_value = { .expected_value = false } }, .operand = 0b00000001 }} } }; TEST_P(RORZeroPageMode, TypicalInstructionExecution) { TypicalInstructionExecution(*this, GetParam()); } INSTANTIATE_TEST_SUITE_P(RotateRightZeroPageAtVariousAddresses, RORZeroPageMode, testing::ValuesIn(RORZeroPageModeTestValues) );
36.639405
157
0.558847
[ "vector" ]
5de22c9be2131feec5c720303cd06ba11c44ef00
2,239
cc
C++
plugins/test_cppapi/test_cppapi.cc
zhangzhongkui/http-over-http
18e27573e3338ee797648c44d7e01114e1d3321c
[ "Apache-2.0" ]
null
null
null
plugins/test_cppapi/test_cppapi.cc
zhangzhongkui/http-over-http
18e27573e3338ee797648c44d7e01114e1d3321c
[ "Apache-2.0" ]
null
null
null
plugins/test_cppapi/test_cppapi.cc
zhangzhongkui/http-over-http
18e27573e3338ee797648c44d7e01114e1d3321c
[ "Apache-2.0" ]
null
null
null
/* * 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 <sstream> #include <vector> #include <ts/ts.h> #include <ts/TextView.h> // TSReleaseAssert() doesn't seem to produce any logging output for a debug build, so do both kinds of assert. // #define ASS(EXPR) \ { \ TSAssert(EXPR); \ TSReleaseAssert(EXPR); \ } std::vector<void (*)()> testList; struct ATest { ATest(void (*testFuncPtr)()) { testList.push_back(testFuncPtr); } }; // Put a test function, whose name is the actual parameter for TEST_FUNC, into testList, the list of test functions. // #define TEST(TEST_FUNC) ATest t(TEST_FUNC); #define TNS_(LN) TestNamespaceName##LN // Generate a unique name for a separate namespace for each test. // #define TNS namespace TNS_(__LINE__) // TextView test. This is not testing the actual TextView code, just that it works to call functions in TextView.cc in the core // from a plugin. // TNS { void f() { ts::TextView tv("abcdefg"); std::ostringstream oss; oss << tv; ASS(ts::memcmp(ts::TextView(oss.str()), tv) == 0) } TEST(f) } // end TNS namespace // Run all the tests. // void TSPluginInit(int, const char **) { TSPluginRegistrationInfo info; info.plugin_name = "test_cppapi"; info.vendor_name = "Apache Software Foundation"; info.support_email = "dev@trafficserver.apache.org"; ASS(TSPluginRegister(&info) == TS_SUCCESS) for (auto fp : testList) { fp(); } }
25.735632
127
0.69272
[ "vector" ]
5de7e3c4881aba8b7f01b8401ff5ee308c547f57
22,307
hxx
C++
include/itkPhaseCorrelationOptimizer.hxx
jhlegarreta/ITKMontage
c5f9214ab8993dec0ba2fe0a95eb614cd6558bfa
[ "Apache-2.0" ]
15
2018-01-16T14:42:06.000Z
2022-03-24T13:24:42.000Z
include/itkPhaseCorrelationOptimizer.hxx
jhlegarreta/ITKMontage
c5f9214ab8993dec0ba2fe0a95eb614cd6558bfa
[ "Apache-2.0" ]
114
2018-01-09T23:06:13.000Z
2022-03-07T19:35:39.000Z
include/itkPhaseCorrelationOptimizer.hxx
jhlegarreta/ITKMontage
c5f9214ab8993dec0ba2fe0a95eb614cd6558bfa
[ "Apache-2.0" ]
13
2018-02-05T20:06:08.000Z
2021-12-13T14:53:52.000Z
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkPhaseCorrelationOptimizer_hxx #define itkPhaseCorrelationOptimizer_hxx #include "itkPhaseCorrelationOptimizer.h" #include "itkImageRegionConstIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkCompensatedSummation.h" #include <cmath> #include <type_traits> //#ifndef NDEBUG #include "itkImageFileWriter.h" namespace { template <typename TImage> void WriteDebug(const TImage * out, const char * filename) { using WriterType = itk::ImageFileWriter<TImage>; typename WriterType::Pointer w = WriterType::New(); w->SetInput(out); w->SetFileName(filename); try { w->Update(); } catch (itk::ExceptionObject & error) { std::cerr << error << std::endl; } } } // namespace //#else // namespace //{ // template <typename TImage> // void // WriteDebug(TImage *, const char *) //{} //} // namespace //#endif namespace itk { template <typename TRealPixelType, unsigned int VImageDimension> PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::PhaseCorrelationOptimizer() { this->SetNumberOfRequiredInputs(3); this->SetOffsetCount(4); this->m_AdjustedInput = ImageType::New(); this->m_PadFilter->SetSizeGreatestPrimeFactor(this->m_FFTFilter->GetSizeGreatestPrimeFactor()); this->m_CyclicShiftFilter->SetInput(this->m_PadFilter->GetOutput()); this->m_FFTFilter->SetInput(this->m_CyclicShiftFilter->GetOutput()); } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::SetOffsetCount(unsigned count) { if (m_Offsets.size() != count) { this->SetNumberOfRequiredOutputs(count); for (unsigned i = m_Offsets.size(); i < count; i++) { OffsetOutputPointer offsetDecorator = static_cast<OffsetOutputType *>(this->MakeOutput(i).GetPointer()); this->ProcessObject::SetNthOutput(i, offsetDecorator.GetPointer()); } m_Offsets.resize(count); this->Modified(); } } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Offsets:"; for (unsigned i = 0; i < m_Offsets.size(); i++) { os << " " << m_Offsets[i]; } os << indent << "PeakInterpolationMethod: " << m_PeakInterpolationMethod << std::endl; os << indent << "MaxCalculator: " << m_MaxCalculator << std::endl; os << indent << "MergePeaks: " << m_MergePeaks << std::endl; os << indent << "ZeroSuppression: " << m_ZeroSuppression << std::endl; os << indent << "PixelDistanceTolerance: " << m_PixelDistanceTolerance << std::endl; } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::SetPeakInterpolationMethod( const PeakInterpolationMethodEnum peakInterpolationMethod) { if (this->m_PeakInterpolationMethod != peakInterpolationMethod) { this->m_PeakInterpolationMethod = peakInterpolationMethod; this->Modified(); } } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::GenerateData() { if (!m_Updating) { this->Update(); } else { OffsetType empty; empty.Fill(0); try { this->ComputeOffset(); } catch (ExceptionObject & err) { itkDebugMacro("exception called while computing offset - passing"); this->SetOffsetCount(1); m_Offsets[0] = empty; // pass exception to caller throw err; } } for (unsigned i = 0; i < m_Offsets.size(); i++) { // write the result to the output auto * output = static_cast<OffsetOutputType *>(this->ProcessObject::GetOutput(0)); output->Set(m_Offsets[i]); } } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::SetFixedImage( const ImageBase<ImageType::ImageDimension> * image) { itkDebugMacro("setting fixed image to " << image); if (this->GetInput(0) != image) { this->ProcessObject::SetNthInput(0, const_cast<ImageBase<ImageType::ImageDimension> *>(image)); this->Modified(); } } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::SetMovingImage( const ImageBase<ImageType::ImageDimension> * image) { itkDebugMacro("setting moving image to " << image); if (this->GetInput(1) != image) { this->ProcessObject::SetNthInput(1, const_cast<ImageBase<ImageType::ImageDimension> *>(image)); this->Modified(); } } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::SetRealInput(const ImageType * image) { itkDebugMacro("setting real input image to " << image); if (this->GetInput(2) != image) { this->ProcessObject::SetNthInput(2, const_cast<ImageType *>(image)); this->Modified(); } } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::SetComplexInput(const ComplexImageType * image) { itkDebugMacro("setting real input image to " << image); if (this->GetInput(3) != image) { this->ProcessObject::SetNthInput(3, const_cast<ComplexImageType *>(image)); this->Modified(); } } template <typename TRealPixelType, unsigned int VImageDimension> void PhaseCorrelationOptimizer<TRealPixelType, VImageDimension>::ComputeOffset() { const ImageType * fixed = static_cast<ImageType *>(this->GetInput(0)); const ImageType * moving = static_cast<ImageType *>(this->GetInput(1)); const ImageType * input = static_cast<ImageType *>(this->GetInput(2)); const typename ImageType::SpacingType spacing = fixed->GetSpacing(); const typename ImageType::PointType fixedOrigin = fixed->GetOrigin(); const typename ImageType::PointType movingOrigin = moving->GetOrigin(); const typename ImageType::RegionType wholeImage = input->GetLargestPossibleRegion(); const typename ImageType::SizeType size = wholeImage.GetSize(); const typename ImageType::IndexType oIndex = wholeImage.GetIndex(); // ----- Start sample peak correlation optimization ----- // OffsetType offset; offset.Fill(0); // create the image which will be biased towards the expected solution // other pixels get their value reduced by multiplication with // e^(-f*(d/s)^2), where f is distancePenaltyFactor, // d is pixel's distance, and s is approximate image size m_AdjustedInput->CopyInformation(input); m_AdjustedInput->SetRegions(input->GetBufferedRegion()); m_AdjustedInput->Allocate(false); typename ImageType::IndexType adjustedSize; typename ImageType::IndexType directExpectedIndex; typename ImageType::IndexType mirrorExpectedIndex; double imageSize2 = 0.0; // image size, squared for (unsigned d = 0; d < ImageDimension; d++) { adjustedSize[d] = size[d] + oIndex[d]; imageSize2 += adjustedSize[d] * adjustedSize[d]; directExpectedIndex[d] = (movingOrigin[d] - fixedOrigin[d]) / spacing[d] + oIndex[d]; mirrorExpectedIndex[d] = (movingOrigin[d] - fixedOrigin[d]) / spacing[d] + adjustedSize[d]; } double distancePenaltyFactor = 0.0; if (m_PixelDistanceTolerance == 0) // up to about half image size { distancePenaltyFactor = -10.0 / imageSize2; } else // up to about five times the provided tolerance { distancePenaltyFactor = std::log(0.9) / (m_PixelDistanceTolerance * m_PixelDistanceTolerance); } MultiThreaderBase * mt = this->GetMultiThreader(); mt->ParallelizeImageRegion<ImageDimension>( wholeImage, [&](const typename ImageType::RegionType & region) { ImageRegionConstIterator<ImageType> iIt(input, region); ImageRegionIteratorWithIndex<ImageType> oIt(m_AdjustedInput, region); IndexValueType zeroDist2 = 100 * m_PixelDistanceTolerance * m_PixelDistanceTolerance; // round down to zero further from this for (; !oIt.IsAtEnd(); ++iIt, ++oIt) { typename ImageType::IndexType ind = oIt.GetIndex(); IndexValueType dist = 0; for (unsigned d = 0; d < ImageDimension; d++) { IndexValueType distDirect = (directExpectedIndex[d] - ind[d]) * (directExpectedIndex[d] - ind[d]); IndexValueType distMirror = (mirrorExpectedIndex[d] - ind[d]) * (mirrorExpectedIndex[d] - ind[d]); if (distDirect <= distMirror) { dist += distDirect; } else { dist += distMirror; } } typename ImageType::PixelType pixel; if (m_PixelDistanceTolerance > 0 && dist > zeroDist2) { pixel = 0; } else // evaluate the expensive exponential function { pixel = iIt.Get() * std::exp(distancePenaltyFactor * dist); #ifndef NDEBUG pixel *= 1000; // make the intensities in this image more humane (close to 1.0) // it is really hard to count zeroes after decimal point when comparing pixel intensities // since this images is used to find maxima, absolute values are irrelevant #endif } oIt.Set(pixel); } }, nullptr); // WriteDebug(m_AdjustedInput.GetPointer(), "m_AdjustedInput.nrrd"); if (m_ZeroSuppression > 0.0) // suppress trivial zero solution { constexpr IndexValueType znSize = 4; // zero neighborhood size, in city-block distance mt->ParallelizeImageRegion<ImageDimension>( wholeImage, [&](const typename ImageType::RegionType & region) { ImageRegionIteratorWithIndex<ImageType> oIt(m_AdjustedInput, region); for (; !oIt.IsAtEnd(); ++oIt) { bool pixelValid = false; typename ImageType::PixelType pixel; typename ImageType::IndexType ind = oIt.GetIndex(); IndexValueType dist = 0; for (unsigned d = 0; d < ImageDimension; d++) { IndexValueType distD = ind[d] - oIndex[d]; if (distD > IndexValueType(size[d] / 2)) // wrap around { distD = size[d] - distD; } dist += distD; } if (dist < znSize) // neighborhood of [0,0,...,0] - in case zero peak is blurred { pixelValid = true; } else { for (unsigned d = 0; d < ImageDimension; d++) // lines/sheets of zero m_MaxIndices { if (ind[d] == oIndex[d]) // one of the m_MaxIndices is "zero" { pixelValid = true; } } } if (pixelValid) // either neighborhood or lines/sheets says update the pixel { pixel = oIt.Get(); // avoid the initial steep rise of function x/(1+x) by shifting it by 10 pixel *= (dist + 10) / (m_ZeroSuppression + dist + 10); oIt.Set(pixel); } } }, nullptr); // WriteDebug(m_AdjustedInput.GetPointer(), "m_AdjustedInputZS.nrrd"); } m_MaxCalculator->SetImage(m_AdjustedInput); if (m_MergePeaks) { m_MaxCalculator->SetN(std::ceil(this->m_Offsets.size() / 2) * (static_cast<unsigned>(std::pow(3, ImageDimension)) - 1)); } else { m_MaxCalculator->SetN(this->m_Offsets.size()); } try { m_MaxCalculator->ComputeMaxima(); } catch (ExceptionObject & err) { itkDebugMacro("exception caught during execution of max calculator - passing "); throw err; } this->m_Confidences = m_MaxCalculator->GetMaxima(); this->m_MaxIndices = m_MaxCalculator->GetIndicesOfMaxima(); itkAssertOrThrowMacro(this->m_Confidences.size() == m_MaxIndices.size(), "Maxima and their m_MaxIndices must have the same number of elements"); std::greater<RealPixelType> compGreater; const auto zeroBound = std::upper_bound(this->m_Confidences.begin(), this->m_Confidences.end(), 0.0, compGreater); if (zeroBound != this->m_Confidences.end()) // there are some non-positive values in here { unsigned i = zeroBound - this->m_Confidences.begin(); this->m_Confidences.resize(i); m_MaxIndices.resize(i); } if (m_MergePeaks > 0) // eliminate m_MaxIndices belonging to the same blurry peak { unsigned i = 1; while (i < m_MaxIndices.size()) { unsigned k = 0; while (k < i) { // calculate maximum distance along any dimension SizeValueType dist = 0; for (unsigned d = 0; d < ImageDimension; d++) { SizeValueType d1 = std::abs(m_MaxIndices[i][d] - m_MaxIndices[k][d]); if (d1 > size[d] / 2) // wrap around { d1 = size[d] - d1; } dist = std::max(dist, d1); } if (dist <= m_MergePeaks) { break; } ++k; } if (k < i) // k is nearby { this->m_Confidences[k] += this->m_Confidences[i]; // join amplitudes this->m_Confidences.erase(this->m_Confidences.begin() + i); m_MaxIndices.erase(m_MaxIndices.begin() + i); } else // examine next index { ++i; } } // now we need to re-sort the values std::vector<unsigned> sIndices; sIndices.reserve(this->m_Confidences.size()); for (i = 0; i < this->m_Confidences.size(); i++) { sIndices.push_back(i); } std::sort(sIndices.begin(), sIndices.end(), [this](unsigned a, unsigned b) { return this->m_Confidences[a] > this->m_Confidences[b]; }); // now apply sorted order typename MaxCalculatorType::ValueVector tMaxs(this->m_Confidences.size()); typename MaxCalculatorType::IndexVector tIndices(this->m_Confidences.size()); for (i = 0; i < this->m_Confidences.size(); i++) { tMaxs[i] = this->m_Confidences[sIndices[i]]; tIndices[i] = m_MaxIndices[sIndices[i]]; } this->m_Confidences.swap(tMaxs); m_MaxIndices.swap(tIndices); } if (this->m_Offsets.size() > this->m_Confidences.size()) { this->SetOffsetCount(this->m_Confidences.size()); } else { this->m_Confidences.resize(this->m_Offsets.size()); m_MaxIndices.resize(this->m_Offsets.size()); } // double confidenceFactor = 1.0 / this->m_Confidences[0]; for (unsigned m = 0; m < this->m_Confidences.size(); m++) { using ContinuousIndexType = ContinuousIndex<OffsetScalarType, ImageDimension>; ContinuousIndexType maxIndex = m_MaxIndices[m]; for (unsigned i = 0; i < ImageDimension; ++i) { const OffsetScalarType directOffset = (movingOrigin[i] - fixedOrigin[i]) - 1 * spacing[i] * (maxIndex[i] - oIndex[i]); const OffsetScalarType mirrorOffset = (movingOrigin[i] - fixedOrigin[i]) - 1 * spacing[i] * (maxIndex[i] - adjustedSize[i]); if (std::abs(directOffset) <= std::abs(mirrorOffset)) { offset[i] = directOffset; } else { offset[i] = mirrorOffset; } } // this->m_Confidences[m] *= confidenceFactor; // normalize - highest confidence will be 1.0 #ifdef NDEBUG this->m_Confidences[m] *= 1000.0; // make the intensities more humane (close to 1.0) #endif this->m_Offsets[m] = offset; } // ----- End sample peak correlation optimization ----- // const auto maxIndices = this->m_MaxIndices; if (this->m_PeakInterpolationMethod != PeakInterpolationMethodEnum::None) // interpolate the peak { for (size_t offsetIndex = 0; offsetIndex < this->m_Offsets.size(); ++offsetIndex) { using ContinuousIndexType = ContinuousIndex<OffsetScalarType, ImageDimension>; ContinuousIndexType maxIndex = maxIndices[offsetIndex]; typename ImageType::IndexType tempIndex = maxIndices[offsetIndex]; typename ImageType::PixelType y0; typename ImageType::PixelType y1 = input->GetPixel(tempIndex); typename ImageType::PixelType y2; for (unsigned i = 0; i < ImageDimension; i++) { tempIndex[i] = maxIndex[i] - 1; if (!wholeImage.IsInside(tempIndex)) { tempIndex[i] = maxIndex[i]; continue; } y0 = input->GetPixel(tempIndex); tempIndex[i] = maxIndex[i] + 1; if (!wholeImage.IsInside(tempIndex)) { tempIndex[i] = maxIndex[i]; continue; } y2 = input->GetPixel(tempIndex); tempIndex[i] = maxIndex[i]; OffsetScalarType omega, theta, ratio; switch (this->m_PeakInterpolationMethod) { case PeakInterpolationMethodEnum::Parabolic: case PeakInterpolationMethodEnum::WeightedMeanPhase: maxIndex[i] += (y0 - y2) / (2 * (y0 - 2 * y1 + y2)); break; case PeakInterpolationMethodEnum::Cosine: ratio = (y0 + y2) / (2 * y1); if (offsetIndex > 0) // clip to -0.999... to 0.999... range { ratio = std::min(ratio, 1.0 - std::numeric_limits<OffsetScalarType>::epsilon()); ratio = std::max(ratio, -1.0 + std::numeric_limits<OffsetScalarType>::epsilon()); } omega = std::acos(ratio); theta = std::atan((y0 - y2) / (2 * y1 * std::sin(omega))); maxIndex[i] -= ::itk::Math::one_over_pi * theta / omega; break; default: itkAssertInDebugAndIgnoreInReleaseMacro("Unsupported interpolation method"); break; } // switch PeakInterpolationMethod const OffsetScalarType directOffset = (movingOrigin[i] - fixedOrigin[i]) - 1 * spacing[i] * (maxIndex[i] - oIndex[i]); const OffsetScalarType mirrorOffset = (movingOrigin[i] - fixedOrigin[i]) - 1 * spacing[i] * (maxIndex[i] - adjustedSize[i]); if (std::abs(directOffset) <= std::abs(mirrorOffset)) { this->m_Offsets[offsetIndex][i] = directOffset; } else { this->m_Offsets[offsetIndex][i] = mirrorOffset; } // TODO: remove // std::cout << "MAX Phase GENERATED: " << this->m_Offsets[offsetIndex] << std::endl; } // for ImageDimension } // for offsetIndex if (this->m_PeakInterpolationMethod == PeakInterpolationMethodEnum::WeightedMeanPhase) { for (unsigned int peak = 0; peak < this->m_PhaseInterpolated && peak < this->m_Offsets.size(); ++peak) { this->m_PadFilter->SetInput(this->m_AdjustedInput); typename CyclicShiftFilterType::OffsetType shiftFilterOffset; for (unsigned int dim = 0; dim < ImageDimension; ++dim) { shiftFilterOffset[dim] = -maxIndices[peak][dim]; } this->m_CyclicShiftFilter->SetShift(shiftFilterOffset); this->m_FFTFilter->Update(); const typename FFTFilterType::OutputImageType * correlationFFT = this->m_FFTFilter->GetOutput(); using ContinuousIndexType = ContinuousIndex<OffsetScalarType, ImageDimension>; ContinuousIndexType maxIndex = maxIndices[peak]; if (this->m_PeakInterpolationMethod == PeakInterpolationMethodEnum::WeightedMeanPhase) { using SumType = CompensatedSummation<double>; SumType powerSum; SumType weightedPhase; typename FFTFilterType::OutputImageType::IndexType index; for (unsigned int dim = 0; dim < ImageDimension; ++dim) { powerSum.ResetToZero(); weightedPhase.ResetToZero(); index.Fill(0); const SizeValueType maxFreqIndex = correlationFFT->GetLargestPossibleRegion().GetSize()[dim] / 2; for (SizeValueType freqIndex = 1; freqIndex < maxFreqIndex; ++freqIndex) { index[dim] = freqIndex; const typename FFTFilterType::OutputPixelType correlation = correlationFFT->GetPixel(index); const double phase = std::arg(correlation); const double power = correlation.imag() * correlation.imag() + correlation.real() * correlation.real(); weightedPhase += phase / Math::pi * power; powerSum += power; } const double deltaToF = -1 * weightedPhase.GetSum() / powerSum.GetSum(); maxIndex[dim] += deltaToF; } //} else if(this->m_PeakInterpolationMethod == PeakInterpolationMethodEnum::PhaseFrequencySlope) { //// todo: compute the linear regression of the phase, use //// slope, add to maxIndex } for (unsigned i = 0; i < ImageDimension; ++i) { const OffsetScalarType directOffset = (movingOrigin[i] - fixedOrigin[i]) - 1 * spacing[i] * (maxIndex[i] - oIndex[i]); const OffsetScalarType mirrorOffset = (movingOrigin[i] - fixedOrigin[i]) - 1 * spacing[i] * (maxIndex[i] - adjustedSize[i]); if (std::abs(directOffset) <= std::abs(mirrorOffset)) { this->m_Offsets[peak][i] = directOffset; } else { this->m_Offsets[peak][i] = mirrorOffset; } } } } // frequency domain interpolation } // interpolate the peak } } // end namespace itk #endif
34.477589
117
0.629175
[ "vector" ]
5de95638fe338a31e9ede8e9aa03a4b36696e603
2,145
hpp
C++
source/device/opencl/ocl_cpp_helper.hpp
L-Net-1992/Tengine
c2e8ff2af88393c883b29304dc43b31f63e6f3e4
[ "Apache-2.0" ]
1
2018-08-30T08:52:09.000Z
2018-08-30T08:52:09.000Z
source/device/opencl/ocl_cpp_helper.hpp
gaojinwei01/Tengine
6799ddbe998c0ac8960243e40b5aa3b15908177e
[ "Apache-2.0" ]
null
null
null
source/device/opencl/ocl_cpp_helper.hpp
gaojinwei01/Tengine
6799ddbe998c0ac8960243e40b5aa3b15908177e
[ "Apache-2.0" ]
null
null
null
/* * 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) 2021, OPEN AI LAB * Author: hbshi@openailab.com */ #ifndef TENGINE_LITE_SOURCE_DEVICE_OPENCL_OCL_CPP_HELPER_HPP_ #define TENGINE_LITE_SOURCE_DEVICE_OPENCL_OCL_CPP_HELPER_HPP_ extern "C" { #include "api/c_api.h" #include "device/device.h" #include "graph/tensor.h" #include "graph/node.h" #include "graph/graph.h" #include "graph/subgraph.h" #include "executer/executer.h" #include "optimizer/split.h" #include "module/module.h" #include "utility/vector.h" #include "utility/log.h" } #include <map> #include <set> #include <algorithm> #include <iomanip> #include <iostream> #include <tuple> #include <vector> #include <cstdlib> #include <string> #include <cstdio> #include <fstream> #include <memory> #include "cache/cache.hpp" #define UP_DIV(x, y) (((x) + (y) - (1)) / (y)) #define ROUND_UP(x, y) (((x) + (y) - (1)) / (y) * (y)) #define ALIGN_UP4(x) ROUND_UP((x), 4) #define ALIGN_UP8(x) ROUND_UP((x), 8) #define CL_TARGET_OPENCL_VERSION 200 #define CL_HPP_TARGET_OPENCL_VERSION 110 #define CL_HPP_MINIMUM_OPENCL_VERSION 110 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wignored-attributes" #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include "device/opencl/include/CL/cl2.hpp" #pragma GCC diagnostic pop #endif //TENGINE_LITE_SOURCE_DEVICE_OPENCL_OCL_CPP_HELPER_HPP_
30.211268
63
0.745921
[ "vector" ]
5defa5ed86bd90634a280a842cd55c0ba2e537ab
737
cpp
C++
pantaray/cpp/scene.cpp
ichko/pantaray
8cb25c2c790ff99fb5c32acf5b03a88d7ead2b34
[ "MIT" ]
2
2017-03-09T22:31:26.000Z
2017-05-02T06:29:22.000Z
pantaray/cpp/scene.cpp
ichko/pantaray
8cb25c2c790ff99fb5c32acf5b03a88d7ead2b34
[ "MIT" ]
null
null
null
pantaray/cpp/scene.cpp
ichko/pantaray
8cb25c2c790ff99fb5c32acf5b03a88d7ead2b34
[ "MIT" ]
1
2018-07-22T18:22:36.000Z
2018-07-22T18:22:36.000Z
#include "../hpp/scene.hpp" namespace PantaRay { bool Scene::Intersect(const Ray& ray, Intersection& intersection) { auto closest_intersection = Intersection(); closest_intersection.distance = Constants::inf; Mesh* closest_mesh = nullptr; for (auto& object : GetObjects()) { auto intersection = Intersection(); if (object.geometry->Intersect(ray, intersection) && intersection.distance < closest_intersection.distance) { closest_intersection = intersection; closest_mesh = &object; } } intersection = closest_intersection; intersection.mesh = closest_mesh; return true; } }
27.296296
72
0.605156
[ "mesh", "geometry", "object" ]
5dfd22be98e37828f6584e4c00628d2e0c85f29b
5,921
hpp
C++
C++/DimensionalDataStructures/Homework4/Homework4/QuadTree.hpp
znickle24/ZanderProjects
674d72d2cba888d0605d9bc8230ecee724ec09b1
[ "MIT" ]
null
null
null
C++/DimensionalDataStructures/Homework4/Homework4/QuadTree.hpp
znickle24/ZanderProjects
674d72d2cba888d0605d9bc8230ecee724ec09b1
[ "MIT" ]
null
null
null
C++/DimensionalDataStructures/Homework4/Homework4/QuadTree.hpp
znickle24/ZanderProjects
674d72d2cba888d0605d9bc8230ecee724ec09b1
[ "MIT" ]
null
null
null
// // QuadTree.hpp // Homework4 // // Created by Zander Nickle on 6/20/18. // Copyright © 2018 Zander Nickle. All rights reserved. // #ifndef QuadTree_h #define QuadTree_h #include "Point.hpp" #include <memory> #include <vector> #include <queue> #include <algorithm> template<int Dimension> class QuadTree { public: QuadTree(const std::vector<Point<2> >& points, int maxPointsPerNode) { box = getBounds(points); std::vector<Point<2>> pointCopy = points; maxPoints = maxPointsPerNode; root = std::unique_ptr<Node>(new Node(pointCopy, maxPoints, box)); } void rangeQuery(std::vector<Point<2>> & vec, Point<2> point, int r) { rangeQueryRecurse(vec, point, root, r); } void KNN(std::vector<Point<Dimension>> & knn, Point<Dimension> p, int k) { // knn.push_back(p); KNNRecurse(knn, root, p, k); } private: struct Node{ float xmid, ymid; AABB<2> nwBox, neBox, swBox, seBox; bool isLeaf = false; //once we find out we are at a leaf, add the proper points to this vector std::vector<Point<2>> pointList; //access outside of Node struct as node->children[Node::NW]; std::unique_ptr<Node> NW; std::unique_ptr<Node> NE; std::unique_ptr<Node> SW; std::unique_ptr<Node> SE; std::vector<Point<2>> NorthWest; std::vector<Point<2>> NorthEast; std::vector<Point<2>> SouthWest; std::vector<Point<2>> SouthEast; Node(std::vector<Point<2>> &points, int &maxPoints, AABB<2> box) { if (points.size() <= maxPoints) { isLeaf = true; pointList = points; return; } xmid = ((box.maxs[0] + box.mins[0])/2); ymid = ((box.maxs[1] + box.mins[1])/2); //find each quadrant and set them in the array of children starting with the NW and ending with the SE //base case is when the quadrant is a leaf, meaning it has fewer than MaxPoints # of points in the quadrant each max should be used exactly twice and each min should be used exactly twice to meet the critera for (Point p: points) { if (p[0] < xmid) { //go west if (p[1] > ymid) { //go north NorthWest.push_back(p); } else { SouthWest.push_back(p); } } if (p[0] > xmid) { //go east if (p[1] > ymid){ // go north NorthEast.push_back(p); } else { SouthEast.push_back(p); } } } nwBox.maxs[0] = xmid; nwBox.mins[1] = ymid; neBox.mins[0] = xmid; neBox.mins[1] = ymid; swBox.maxs[0] = xmid; swBox.maxs[1] = ymid; seBox.mins[0] = xmid; seBox.maxs[1] = ymid; NW = std::unique_ptr<Node>(new Node(NorthWest, maxPoints, nwBox)); NE = std::unique_ptr<Node>(new Node(NorthEast, maxPoints, neBox)); SW = std::unique_ptr<Node>(new Node(SouthWest, maxPoints, swBox)); SE = std::unique_ptr<Node>(new Node(SouthEast, maxPoints, seBox)); } }; void rangeQueryRecurse(std::vector<Point<2>> &vec, Point<2> point, std::unique_ptr<Node> &node, int r) { //once at a leaf node, just need to check each of the points and see if they should be added to the vector passed in. if (node->isLeaf) { for (Point p: node->pointList) { if (distance(p, point) <= r) { vec.push_back(p); } } return; } //each node has 4 member variables that are the 4 quadrants. Need to see if the point is within that box and if it's possible for any point in that box to be within range. If so, recurse down that quadrant. if (node->NorthWest.size() > 0){ AABB<2> nwBox = getBounds(node->NorthWest); if (distance(nwBox.closestInBox(point), point) <= r){ rangeQueryRecurse(vec, point, node->NW, r); } } if (node->NorthEast.size() > 0) { AABB<2> neBox = getBounds(node->NorthEast); if (distance(neBox.closestInBox(point), point) <= r) { rangeQueryRecurse(vec, point, node->NE, r); } } if (node->SouthWest.size() > 0) { AABB<2> swBox = getBounds(node->SouthWest); if (distance(swBox.closestInBox(point), point) <= r) { rangeQueryRecurse(vec, point, node->SW, r); } } if (node-> SouthEast.size() > 0) { AABB<2> seBox = getBounds(node->SouthEast); if (distance(seBox.closestInBox(point), point) <= r) { rangeQueryRecurse(vec, point, node->SE, r); } } } void KNNRecurse(std::vector<Point<2>> &knn,const std::unique_ptr<Node> &n, Point<2> p, int k) { if (n->isLeaf) { for (Point<2> point: n->pointList) { if (knn.size() < k) { knn.push_back(point); std::push_heap(knn.begin(), knn.end(), DistanceComparator<2>{p}); } else if (distance(point, p) < distance(knn.front(), p)){ std::pop_heap(knn.begin(), knn.end(), DistanceComparator<2>{p}); knn.pop_back(); knn.push_back(point); std::push_heap(knn.begin(), knn.end(), DistanceComparator<2>{p}); } } } if (n->NW) { AABB<2> nwBox = n->nwBox; if(knn.size() < k || distance(nwBox.closestInBox(p), p) < distance(knn.front(), p)) { KNNRecurse(knn, n->NW, p, k); } } if (n->NE) { AABB<2> neBox = n->neBox; if(knn.size() < k || distance(neBox.closestInBox(p), p) < distance(knn.front(), p)) { KNNRecurse(knn, n->NE, p, k); } } if (n->SW) { AABB<2> swBox = n->swBox; if(knn.size() < k || distance(swBox.closestInBox(p), p) < distance(knn.front(), p)) { KNNRecurse(knn, n->SW, p, k); } } if (n->SE) { AABB<2> seBox = n->seBox; if(knn.size() < k || distance(seBox.closestInBox(p), p) < distance(knn.front(), p)) { KNNRecurse(knn, n->SE, p, k); } } } std::unique_ptr<Node> root; AABB<2> box; int maxPoints; }; #endif /* QuadTree_h */
32.532967
213
0.577267
[ "vector" ]
5dff4350bfc8cd28f6cf2081c6f0f8a7a760bfc2
2,445
cpp
C++
72_construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp
litaotju/lintcode
d614bfd33d5a772325f62f83edbc56e07bbdab6c
[ "MIT" ]
2
2016-07-30T01:25:06.000Z
2017-10-07T12:30:24.000Z
72_construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp
litaotju/lintcode
d614bfd33d5a772325f62f83edbc56e07bbdab6c
[ "MIT" ]
null
null
null
72_construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp
litaotju/lintcode
d614bfd33d5a772325f62f83edbc56e07bbdab6c
[ "MIT" ]
null
null
null
/* @Copyright:LintCode @Author: taoleetju @Problem: http://www.lintcode.com/problem/construct-binary-tree-from-inorder-and-postorder-traversal @Language: C++ @Datetime: 16-06-13 14:18 */ /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { /** *@param inorder : A list of integers that inorder traversal of a tree *@param postorder : A list of integers that postorder traversal of a tree *@return : Root of a tree */ typedef vector<int>::iterator NodeIter; public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // write your code here if(inorder.empty()|| postorder.empty()|| inorder.size()!= postorder.size()) return NULL; return buildTree(inorder, inorder.begin(), inorder.end()-1, postorder, postorder.begin() , postorder.end()-1); } private: TreeNode *buildTree(vector<int> & inorder, NodeIter inFront, NodeIter inEnd, vector<int> & postorder, NodeIter postFront, NodeIter postEnd ) { if(inFront > inEnd || postFront > postEnd ) return NULL; //根节点一定在 postorder的末尾 TreeNode *root = new TreeNode(*postEnd); //根节点在inorder中的位置 NodeIter rootIndexInorder = find(inFront, inEnd+1, *postEnd); //assert rootIndexInorder != inEnd+1 一定能找到 //右子树的长度 int lengthR = inEnd - rootIndexInorder; //右子树的长度 int lengthL = rootIndexInorder - inFront; //右子树为空 if(rootIndexInorder == inEnd){ root->right = NULL; //右子树非空时 }else{ root ->right = buildTree(inorder, rootIndexInorder+1, inEnd, postorder, postEnd-lengthR, postEnd-1 ); } //左子树为空 if(rootIndexInorder == inFront){ root->left = NULL; } //左子树不空 else{ root->left = buildTree(inorder, inFront, rootIndexInorder-1, postorder, postFront, postFront + lengthL -1 ); } return root; } };
30.185185
101
0.528016
[ "vector" ]
b90596a7ff9ac7daabc66215a518b48561ffa7c8
6,641
cpp
C++
src/Debug/Camera.cpp
Kanma/Athena-Graphics
7e531c404ee55ca8f1ca39e94b55c3d505a2901f
[ "MIT" ]
1
2016-10-30T07:34:29.000Z
2016-10-30T07:34:29.000Z
src/Debug/Camera.cpp
Kanma/Athena-Graphics
7e531c404ee55ca8f1ca39e94b55c3d505a2901f
[ "MIT" ]
null
null
null
src/Debug/Camera.cpp
Kanma/Athena-Graphics
7e531c404ee55ca8f1ca39e94b55c3d505a2901f
[ "MIT" ]
null
null
null
/** @file Camera.cpp @author Philip Abbet Implementation of the class 'Athena::Graphics::Debug::Camera' */ #include <Athena-Graphics/Debug/Camera.h> #include <Athena-Graphics/MeshBuilder.h> #include <Athena-Core/Log/LogManager.h> #include <Ogre/OgreMaterialManager.h> #include <Ogre/OgreSceneManager.h> #include <Ogre/OgreMeshManager.h> #include <Ogre/OgreEntity.h> using namespace Athena; using namespace Athena::Entities; using namespace Athena::Graphics; using namespace Athena::Graphics::Debug; using namespace Athena::Math; using namespace Athena::Utils; using namespace Athena::Log; using namespace std; using Ogre::MeshManager; using Ogre::MeshPtr; using Ogre::RenderOperation; /************************************** CONSTANTS **************************************/ /// Context used for logging static const char* __CONTEXT__ = "Debug/Camera"; ///< Name of the type of component const std::string Camera::TYPE = "Athena/Debug/Camera"; /***************************** CONSTRUCTION / DESTRUCTION ******************************/ Camera::Camera(const std::string& strName, ComponentsList* pList) : DebugComponent(strName, pList), m_pEntity(0) { } //----------------------------------------------------------------------- Camera::~Camera() { hide(); } //----------------------------------------------------------------------- Camera* Camera::create(const std::string& strName, ComponentsList* pList) { return new Camera(strName, pList); } //----------------------------------------------------------------------- Camera* Camera::cast(Component* pComponent) { return dynamic_cast<Camera*>(pComponent); } /*************************************** METHODS ***************************************/ void Camera::show() { // Declarations const Real cos30 = MathUtils::Cos(Degree(30)); const Real cos60 = MathUtils::Cos(Degree(60)); const Real sin30 = MathUtils::Sin(Degree(30)); const Real sin60 = MathUtils::Sin(Degree(60)); if (!m_pEntity) { MeshPtr mesh = MeshManager::getSingletonPtr()->getByName("AthenaCamera.mesh"); if (mesh.isNull()) { MeshBuilder builder("AthenaCamera.mesh"); builder.beginSharedVertices(); // Box - Front part builder.position(Vector3(0.15f, 0.3f, 0.3f)); // 0 builder.position(Vector3(-0.15f, 0.3f, 0.3f)); builder.position(Vector3(-0.15f, -0.3f, 0.3f)); builder.position(Vector3(0.15f, -0.3f, 0.3f)); // Box - Back part builder.position(Vector3(0.15f, 0.3f, 1.0f)); builder.position(Vector3(-0.15f, 0.3f, 1.0f)); // 5 builder.position(Vector3(-0.15f, -0.3f, 1.0f)); builder.position(Vector3(0.15f, -0.3f, 1.0f)); // Objective - Part fixed on the box front part builder.position(Vector3(0.1f, 0.1f, 0.3f)); builder.position(Vector3(-0.1f, 0.1f, 0.3f)); builder.position(Vector3(-0.1f, -0.1f, 0.3f)); // 10 builder.position(Vector3(0.1f, -0.1f, 0.3f)); // Objective - Middle part builder.position(Vector3(0.1f, 0.1f, 0.15f)); builder.position(Vector3(-0.1f, 0.1f, 0.15f)); builder.position(Vector3(-0.1f, -0.1f, 0.15f)); builder.position(Vector3(0.1f, -0.1f, 0.15f)); // 15 // Objective - Biggest part builder.position(Vector3(0.1f, 0.25f, 0.0f)); builder.position(Vector3(-0.1f, 0.25f, 0.0f)); builder.position(Vector3(-0.1f, -0.25f, 0.0f)); builder.position(Vector3(0.1f, -0.25f, 0.0f)); // 19 builder.endSharedVertices(); builder.begin("Solid", "Materials/DebugObject/Solid", RenderOperation::OT_TRIANGLE_LIST, true); builder.quad(3, 2, 1, 0); builder.quad(4, 5, 6, 7); builder.quad(0, 4, 7, 3); builder.quad(0, 1, 5, 4); builder.quad(1, 2, 6, 5); builder.quad(2, 3, 7, 6); builder.quad(12, 8, 11, 15); builder.quad(12, 13, 9, 8); builder.quad(13, 14, 10, 9); builder.quad(14, 15, 11, 10); builder.quad(16, 12, 15, 19); builder.quad(16, 17, 13, 12); builder.quad(17, 18, 14, 13); builder.quad(18, 19, 15, 14); builder.quad(19, 18, 17, 16); builder.end(); builder.begin("Wireframe", "Materials/DebugObject/Wireframe", RenderOperation::OT_LINE_LIST, true); builder.line(0, 1); builder.line(1, 2); builder.line(2, 3); builder.line(3, 0); builder.line(4, 5); builder.line(5, 6); builder.line(6, 7); builder.line(7, 4); builder.line(0, 4); builder.line(1, 5); builder.line(2, 6); builder.line(3, 7); builder.line(8, 9); builder.line(9, 10); builder.line(10, 11); builder.line(11, 8); builder.line(12, 13); builder.line(13, 14); builder.line(14, 15); builder.line(15, 12); builder.line(16, 17); builder.line(17, 18); builder.line(18, 19); builder.line(19, 16); builder.line(8, 12); builder.line(9, 13); builder.line(10, 14); builder.line(11, 15); builder.line(12, 16); builder.line(13, 17); builder.line(14, 18); builder.line(15, 19); builder.end(); mesh = builder.getMesh(); } const string strBaseName = m_pList->getEntity()->getName() + ".Debug[" + getName() + "]"; m_pEntity = getSceneManager()->createEntity(strBaseName + ".Mesh", mesh->getName()); m_pSceneNode->attachObject(m_pEntity); } } //----------------------------------------------------------------------- void Camera::hide() { if (m_pEntity) { m_pSceneNode->detachObject(m_pEntity); getSceneManager()->destroyEntity(m_pEntity); m_pEntity = 0; } } /***************************** MANAGEMENT OF THE PROPERTIES ****************************/ Utils::PropertiesList* Camera::getProperties() const { // Call the base class implementation PropertiesList* pProperties = DebugComponent::getProperties(); // Create the category belonging to this type pProperties->selectCategory(TYPE, false); // Returns the list return pProperties; }
29.914414
111
0.518747
[ "mesh", "solid" ]
b90664010d094970f28c67e825e76a1c4b8a528f
4,566
hpp
C++
examples/write_structures_to_xml/stubs.hpp
incoder1/libio
fbfd83fe31ca59a69670e5269f5847b2b4c6c553
[ "BSL-1.0" ]
14
2018-06-12T15:42:43.000Z
2022-02-28T16:19:20.000Z
examples/write_structures_to_xml/stubs.hpp
incoder1/libio
fbfd83fe31ca59a69670e5269f5847b2b4c6c553
[ "BSL-1.0" ]
null
null
null
examples/write_structures_to_xml/stubs.hpp
incoder1/libio
fbfd83fe31ca59a69670e5269f5847b2b4c6c553
[ "BSL-1.0" ]
null
null
null
#ifndef STUBS_HPP_INCLUDED #define STUBS_HPP_INCLUDED #include <xml_types.hpp> #ifdef HAS_PRAGMA_ONCE #pragma once #endif // HAS_PRAGMA_ONCE class config { public: typedef std::chrono::time_point<std::chrono::system_clock> date_t; config() noexcept: id_(0), enabled_(false), time_created_(), name_() {} config(uint8_t id, bool enabled, date_t&& tc, std::string&& name) noexcept: id_(id), enabled_(enabled), time_created_( std::forward< date_t > (tc) ), name_(std::forward<std::string>(name)) {} inline uint8_t id() const noexcept { return id_; } inline bool enabled() const noexcept { return enabled_; } inline const date_t& time_created() const noexcept { return time_created_; } inline const date_t& date_created() const noexcept { return time_created_; } inline const std::string& name() const noexcept { return name_; } typedef io::xml::complex_type<config, std::tuple<io::xml::byte_attribute,io::xml::bool_attribute>, std::tuple<io::xml::date_element,io::xml::string_element> > xml_type; xml_type to_xml_type() const { // attributes io::xml::byte_attribute id("id", id_); io::xml::bool_attribute en("enabled", enabled_); // elements io::xml::date_element tm("date-created", time_created_); io::xml::string_element s("name", name_ ); return xml_type("configuration", std::make_tuple(id,en), std::make_tuple(tm,s) ); } static config from_xml_type(const xml_type& xt) { // attributes uint8_t id = std::get<0>( xt.attributes() ).value(); bool enabled = std::get<1>( xt.attributes() ).value(); // elements std::chrono::time_point<std::chrono::system_clock> tm = std::get<0>( xt.elements() ).value(); std::string msg( std::get<1>( xt.elements() ).value() ); return config(id, enabled, std::move(tm) , std::move(msg) ); } private: uint8_t id_; bool enabled_; std::chrono::time_point<std::chrono::system_clock> time_created_; std::string name_; }; struct primary_conf { public: explicit primary_conf(uint8_t id) noexcept: id_(id) {} inline uint8_t id() const noexcept { return id_; } typedef io::xml::complex_type< primary_conf, std::tuple<io::xml::byte_attribute>, std::tuple<> > xml_type; xml_type to_xml_type() const { return xml_type( "primary-configuration", std::make_tuple( io::xml::byte_attribute("id",id_) ), std::tuple<>() ); } static primary_conf from_xml_type(const xml_type* xt) { return primary_conf( std::get<0>(xt->attributes()).value() ); } private: uint8_t id_; }; class app_settings { private: // element's list typedef io::xml::list_type< config::xml_type > config_list; app_settings(primary_conf&& primary, std::vector<config>&& confs) noexcept: primary_conf_(std::forward<primary_conf>(primary)), confs_(std::forward< std::vector<config> >(confs)) {} public: static constexpr const char* XSI = "http://www.w3.org/2001/XMLSchema-instance"; static constexpr const char* SCHEMA = "app-config.xsd"; app_settings(primary_conf&& primary): primary_conf_(std::move(primary)), confs_() {} primary_conf primary() const noexcept { return primary_conf_; } void add_conf(config&& conf) { confs_.emplace_back( std::forward<config>(conf) ); } std::vector<config>::const_iterator first_config() const noexcept { return confs_.cbegin(); } std::vector<config>::const_iterator end_config() const noexcept { return confs_.cend(); } typedef io::xml::complex_type< app_settings, std::tuple< io::xml::string_attribute, io::xml::string_attribute>, std::tuple< primary_conf::xml_type, config_list> > xml_type; xml_type to_xml_type() const { io::xml::string_attribute xsi("xmlns:xsi", XSI ); io::xml::string_attribute sh("xsi:noNamespaceSchemaLocation", SCHEMA); config_list confs("configurations"); confs.add_elements("configuration", confs_.cbegin(), confs_.cend() ); return xml_type("application-settings", std::make_tuple(xsi,sh), std::make_tuple( primary_conf_.to_xml_type(), std::move(confs) ) ); } static app_settings from_xml_type(const xml_type& xt) { // elements primary_conf::xml_type r = std::get<0>( xt.elements() ); primary_conf rt = primary_conf::from_xml_type( &r ); // get and unmap container config_list confs( std::get<1>(xt.elements()) ); std::vector<config> vconf; confs.unmap( vconf ); return app_settings( std::move(rt), std::move(vconf) ); } private: primary_conf primary_conf_; std::vector<config> confs_; }; #endif // STUBS_HPP_INCLUDED
24.031579
95
0.688349
[ "vector" ]
b906aa8ccf715dff64a3b1494ce3a8017e6b4c98
2,179
cpp
C++
src/bucket_collection.cpp
strikles/poker-mcts
6bd1443a7b497cf64fafd4b25e8d3bb64219e18c
[ "MIT" ]
9
2019-08-22T06:25:12.000Z
2021-02-17T16:27:27.000Z
src/bucket_collection.cpp
strikles/poker-mcts
6bd1443a7b497cf64fafd4b25e8d3bb64219e18c
[ "MIT" ]
null
null
null
src/bucket_collection.cpp
strikles/poker-mcts
6bd1443a7b497cf64fafd4b25e8d3bb64219e18c
[ "MIT" ]
4
2019-09-04T14:20:05.000Z
2022-02-09T06:32:14.000Z
#include <algorithm> #include "bucket_collection.hpp" namespace freedom { BucketCollection::BucketCollection(const unsigned &nb_buckets) : buckets(nb_buckets) {} BucketCollection::BucketCollection(const vector<Bucket> &buckets_) : buckets(buckets_) {} BucketCollection::Bucket &BucketCollection::operator[](unsigned int i) { return buckets[i]; } const BucketCollection::Bucket &BucketCollection:: operator[](unsigned int i) const { return buckets[i]; } int BucketCollection::get_bucket_index_including_nb_hands( const unsigned &nb_hands, const unsigned &bucket_offset) const { unsigned sum = 0; for (int i = bucket_offset; i < buckets.size(); ++i) { sum += buckets[i].size(); if (sum >= nb_hands) return i; } // the number of demanded hands is greater than the // number of hands in the buckets. return lowest bucket return buckets.size() - 1; } vector<BucketHand> BucketCollection::hand_bucket_range(const unsigned &lower_bound, const unsigned &upper_bound) const { vector<BucketHand> range; for (unsigned i = upper_bound; i <= lower_bound; ++i) { range.insert(range.end(), buckets[i].begin(), buckets[i].end()); } return range; } BucketCollection BucketCollection::bucket_range(const unsigned &lower_bound, const unsigned &upper_bound) const { BucketCollection range(0); for (int i = upper_bound; i <= lower_bound; ++i) { range.buckets.push_back(buckets[i]); } return range; } unsigned BucketCollection::nb_hands() const { int sum = 0; for (unsigned i = 0; i < buckets.size(); ++i) sum += buckets[i].size(); return sum; } BucketCollection BucketCollection::remove_empty_buckets() const { vector<Bucket> newc; for (unsigned i = 0; i < buckets.size(); ++i) if (!buckets[i].empty()) newc.push_back(buckets[i]); return BucketCollection(newc); } unsigned BucketCollection::nb_buckets() const { return buckets.size(); } void BucketCollection::reverse() { std::reverse(buckets.begin(), buckets.end()); } vector<BucketHand> BucketCollection::hands() const { return hand_bucket_range(0, nb_buckets() - 1); } }
27.582278
72
0.685636
[ "vector" ]
b914dc745e4d515eba13b6396cb1542e916a230e
2,147
cpp
C++
camera/CameraParameters.cpp
SmombieRom/klte-common
3d72aada6042701d4ba144cf57a09d7b7f128c82
[ "FTL" ]
null
null
null
camera/CameraParameters.cpp
SmombieRom/klte-common
3d72aada6042701d4ba144cf57a09d7b7f128c82
[ "FTL" ]
null
null
null
camera/CameraParameters.cpp
SmombieRom/klte-common
3d72aada6042701d4ba144cf57a09d7b7f128c82
[ "FTL" ]
null
null
null
/* * Copyright (C) 2017 The LineageOS Project * * 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 "CameraParameters.h" namespace android { const char CameraParameters::AUDIO_ZOOM_OFF[] = "audio-zoom"; const char CameraParameters::AUDIO_ZOOM_ON[] = "audio-zoom"; const char CameraParameters::BEAUTY_SHOT_OFF[] = "beauty-shot"; const char CameraParameters::BEAUTY_SHOT_ON[] = "beauty-shot"; const char CameraParameters::BURST_SHOT_OFF[] = "burst-shot"; const char CameraParameters::BURST_SHOT_ON[] = "burst-shot"; const char CameraParameters::KEY_AUDIO_ZOOM[] = "audio-zoom"; const char CameraParameters::KEY_AUDIO_ZOOM_SUPPORTED[] = "audio-zoom-supported"; const char CameraParameters::KEY_BEAUTY_SHOT[] = "beauty-shot"; const char CameraParameters::KEY_BEAUTY_SHOT_SUPPORTED[] = "beauty-shot-supported"; const char CameraParameters::KEY_BURST_SHOT[] = "burst-shot"; const char CameraParameters::KEY_BURST_SHOT_SUPPORTED[] = "burst-shot-supported"; const char CameraParameters::KEY_FOCUS_MODE_OBJECT_TRACKING[] = "object-tracking"; const char CameraParameters::KEY_FOCUS_MODE_OBJECT_TRACKING_SUPPORTED[] = "object-tracking-supported"; const char CameraParameters::KEY_LGE_CAMERA[] = "lge-camera"; const char CameraParameters::KEY_VIDEO_WDR[] = "video-wdr"; const char CameraParameters::KEY_VIDEO_WDR_SUPPORTED[] = "video-wdr-supported"; const char CameraParameters::VIDEO_WDR_OFF[] = "video-wdr"; const char CameraParameters::VIDEO_WDR_ON[] = "video-wdr"; const char CameraParameters::OBJECT_TRACKING_ON[] = "object-tracking"; const char CameraParameters::OBJECT_TRACKING_OFF[] = "object-tracking"; }; // namespace android
48.795455
102
0.775501
[ "object" ]
2c71ab4e55e23d669dabdbabafc66f64be2baba1
13,605
cc
C++
src/Bloch/BlochMx.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
4
2021-03-15T10:02:13.000Z
2022-01-16T11:06:28.000Z
src/Bloch/BlochMx.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
1
2022-01-27T15:35:03.000Z
2022-01-27T15:35:03.000Z
src/Bloch/BlochMx.cc
pygamma-mrs/gamma
c83a7c242c481d2ecdfd49ba394fea3d5816bccb
[ "BSD-3-Clause" ]
null
null
null
/* BlochMx.cc ****************************************************-*-c++-*- ** ** ** G A M M A ** ** ** ** Bloch Matrix Implementation ** ** ** ** Copyright (c) 2002 ** ** Dr. Scott A. Smith ** ** National High Magnetic Field Laboratory ** ** 1800 E. Paul Dirac Drive ** ** Box 4005 ** ** Tallahassee, FL 32306 ** ** ** ** $Header: $ ** ** *************************************************************************/ /************************************************************************* ** ** ** Description ** ** ** ** The class BlochMx defines a Bloch matrix. Such arrays are used to ** ** evolve an Bloch magnetization vector in time as described by the ** ** phenomenological Bloch equations. A magnetization vector is embodied ** ** in class MagVec in the GAMMA Bloch module. As such vectors involve ** ** N individual sub-vectors, and each of these sub-vectors has three ** ** magnetization components, Bloch matrices are similarly blocked in ** ** 3x3 sub-blocks. Cross terms, i.e. elements outside of the blocks, ** ** unless there is exchange between vectors (chemical, diffusion,...). ** ** ** ** The magnetization vector has ONLY 1 type of evolution implicitly ** ** defined, that dictated by the phenomenological Bloch equations. ** ** ** ** -Gt ** ** |M(t)> = e |M(0)- M > + |M > ** ** inf inf ** ** ** ** where the evolution matrix G is the Bloch matrix defined herein and ** ** the initinite time vector must be specified appropriately as needed. ** ** Bloch matrices are simply GAMMA matrices, but they are restricted ** ** to be square and of dimension 3N x 2N where N is the number of sub- ** ** vectors (magnetization). Bloch matrices include added functionality ** ** above class matrix that allows them to interact in a Bloch specific ** ** manner with other GAMMA classes while maintaining the appropriate ** ** interal structures. ** ** ** *************************************************************************/ #ifndef BlochMxx_cc_ // Is file already included? # define BlochMxx_cc_ 1 // If no, then remember it # if defined(GAMPRAGMA) // Using the GNU compiler? # pragma implementation // This is the implementation # endif #include <Bloch/BlochMx.h> // Includes the interface #include <Basics/Gutils.h> // Include GAMMA errors/queries #include <Basics/StringCut.h> // Include Gdec function // ---------------------------------------------------------------------------- // --------------------------- PRIVATE FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // i Bloch Matrix Error Handling // ____________________________________________________________________________ // Input G : Bloch matrix (this) // eidx : Error index // noret : Flag for linefeed (0=linefeed) // Output void : An error message is output /* The following error messages use the defaults set in the Gutils package Case Error Message (0) Program Aborting..... (3) Can't Construct From Parameter Set (4) Cannot Construct From Input File (5) Cannot Write To Parameter File (6) Cannot Write To Output FileStream (7) Cannot Produce Any Output default Unknown Error */ // Input sys : Spin system (this) // eidx : Error index // pname : Additional error message // noret : Flag for linefeed (0=linefeed) // Output none : Error message output /* The following error messages use the defaults set in the Gutils package Case Error Message (1) Problems With File PNAME (2) Cannot Read Parameter PNAME default Unknown Error - PNAME */ // Input G : Bloch matrix (this) // eidx : Error index // pname : Additional error message // Output none : Error message output // Program execution stopped void BlochMx::BMxerror(int eidx, int noret) const { std::string hdr("Bloch Matrix"); std::string msg; switch (eidx) { case 10: msg = std::string("Rectangular Array Discovered"); // (10) GAMMAerror(hdr,msg,noret); break; case 11: msg = std::string("These Arrays Must Be Square"); // (11) GAMMAerror(hdr,msg,noret); break; case 12: msg = std::string("Array Dimensioning Problem"); // (12) GAMMAerror(hdr,msg,noret); break; case 13: msg = std::string("Array Not 3N x 3N with N=0,1,2,..."); // (13) GAMMAerror(hdr,msg,noret); break; case 14: msg = std::string("Problems During Assigment From Matrix");// (14) GAMMAerror(hdr,msg,noret); break; default: GAMMAerror(hdr, eidx, noret); break; // (-1) } } void BlochMx::BMxerror(int eidx, const std::string& pname, int noret) const { std::string hdr("Bloch Matrix"); std::string msg; switch(eidx) { case 101: // (101) msg = std::string("Can't Find Parameters For ") + pname; GAMMAerror(hdr, msg, noret); break; case 102: // (102) msg = std::string("Can't Find ") + pname + std::string(" In Parameter Set"); GAMMAerror(hdr, msg, noret); break; default: GAMMAerror(hdr, eidx, pname, noret); break;// Unknown Error (-1) } } volatile void BlochMx::BMxfatal(int eidx) const { BMxerror(eidx, 1); // Normal non-fatal error if(eidx) BMxerror(0); // Program aborting error GAMMAfatal(); // Clean exit from program } volatile void BlochMx::BMxfatal(int eidx, const std::string& pname) const { BMxerror(eidx, pname, 1); // Normal non-fatal error if(eidx) BMxerror(0); // Program aborting error GAMMAfatal(); // Clean exit from program } // ---------------------------------------------------------------------------- // ---------------------------- PUBLIC FUNCTIONS ------------------------------ // ---------------------------------------------------------------------------- // ____________________________________________________________________________ // A BLOCH MATRIX CONSTRUCTION, DESTRUCTION // ____________________________________________________________________________ BlochMx::BlochMx() : matrix() {} BlochMx::BlochMx(const BlochMx& G) : matrix(G) {} BlochMx::BlochMx(const matrix& G) : matrix(G) { if(!is_square()) { BMxerror(10,1); // Rectangular array BMxerror(11,1); // Must be square BMxfatal(9); // Error during construction } double ddim = rows(); while (ddim > 0) ddim -= 3; if(ddim) { BMxerror(12,1); // Array dimension problem BMxerror(12,1); // Must be 3Nx3N, N non-neg int BMxfatal(9); // Error during construction } } BlochMx::~BlochMx() {} // Matrix does the work BlochMx& BlochMx::operator=(const BlochMx& G) { if(this == &G) return *this; // Nothing if self assign matrix::operator=((matrix)G); // Copy array return *this; } BlochMx& BlochMx::operator=(const matrix& G) { matrix::operator=((matrix)G); // Copy array if(!is_square()) { BMxerror(10,1); // Rectangular array BMxerror(11,1); // Must be square BMxfatal(14); // Error during assignment } double ddim = rows(); while (ddim > 0) ddim -= 3; if(ddim) { BMxerror(12,1); // Array dimension problem BMxerror(12,1); // Must be 3Nx3N, N non-neg int BMxfatal(14); // Error during assignment } return *this; } // ____________________________________________________________________________ // B BLOCH MATRIX - BLOCH MATRIX INTERACTIONS // ____________________________________________________________________________ /* These functions allow for simple mathematical operations between two Bloch matices. This includes addition, subtraction, multiplication. There is one unary function as well, negation. Operator Arguments Result Operator Arguments Result -------- --------- ----------------- -------- --------- ------------------- - G Returns -G -= G,G1 G1 subt. from G + G,G1 Returns G+G1 * G1,G2 Returns G1*G2 += G,G1 G1 added to G *= G,G1 G mult into G1 - G1,G2 Returns G1-G2 */ BlochMx BlochMx::operator- () const { return BlochMx(matrix::operator- ()); } BlochMx BlochMx::operator+ (const BlochMx& G1) const { BlochMx G(*this); G += G1; return G;} void BlochMx::operator+= (const BlochMx& G1) { matrix::operator+= (G1); } BlochMx BlochMx::operator- (const BlochMx &G1) const { BlochMx G(*this); G -= G1; return G;} void BlochMx::operator-= (const BlochMx& G1) { matrix::operator-= (G1); } BlochMx BlochMx::operator* (const BlochMx& G1) const { BlochMx G(*this); G *= G1; return G;} void BlochMx::operator*= (const BlochMx& G1) { matrix::operator*= (G1); } void BlochMx::operator&= (const BlochMx& G1) { BlochMx G(G1); G*=(*this); *this = G; } // ____________________________________________________________________________ // B BLOCH MATRIX - SCALAR INTERACTIONS // ____________________________________________________________________________ /* These functions allow for two mathematical operations between a scalar & a Bloch matrix. Operator Arguments Result Operator Arguments Result -------- --------- ----------------- -------- --------- ------------------- * z,G Returns z*G *= G,z G multiplied by z * G,z Returns z*G *= G,d G multiplied by d * d,G Returns d*G / G,z Returns (1/z)*G * G,d Returns G*d / G,d Returns (1/d)*G /= G,d G mult. by (1/d) /= G,z G mult. by (1/z) */ BlochMx BlochMx::operator* (const complex& z) const { BlochMx G(*this); G *= z; return G;} BlochMx BlochMx::operator* (double r) const { BlochMx G(*this); G *= r; return G;} BlochMx operator* (const complex& z, const BlochMx &G1) { BlochMx G(G1); G *= z; return G;} BlochMx operator* (double r, const BlochMx &G1) { BlochMx G(G1); G *= r; return G;} void BlochMx::operator*= (const complex& z) { matrix::operator*= (z); } void BlochMx::operator*= (double r) { matrix::operator*= (r); } BlochMx BlochMx::operator/ (const complex& z) const { return (*this)*(1/z); } BlochMx BlochMx::operator/ (double r) const { return (*this)*(1/r); } void BlochMx::operator/= (const complex& z) { (*this) *= (1/z); } void BlochMx::operator/= (double r) { (*this) *= (1/r); } // ____________________________________________________________________________ // C BLOCH MATRIX - MAGNETIZATION VECTOR INTERACTIONS // ____________________________________________________________________________ /* BlochMx exp(const BlochMx& G, double t) { BlochMx G(G1); // Make a copy of input G int hs = G.HS(); // This is full spin Hilbert space matrix mxd, mxev; // Used in matrix diagonalizaion G.blow_up(); // Generate full space array diag(G.mx, mxd, mxev); // Diagonalize it (into mxd & mxev) for(int i=0; i<hs; i++) // Exponentiate the diagonals mxd.put(exp(mxd.get(i,i)),i,i); G.mx = mxev * mxd * adjoint(mxev); // Reform in original basis G.DelSubArrays(); // Delete any sub-space arrays return G; // Were all done } */ // ____________________________________________________________________________ // B Bloch Matrix Access // ____________________________________________________________________________ int BlochMx::NComps() const { return rows()/3; } #endif // BlochMx.cc
42.515625
82
0.511944
[ "vector" ]
2c73872c576c68ff22a8c9659f7918bdeb198091
3,215
hpp
C++
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/bulk_write.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
null
null
null
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/bulk_write.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
null
null
null
source/external/mongo-cxx-driver/include/mongocxx/v_noabi/mongocxx/options/bulk_write.hpp
VincentPT/vschk
f8f40a7666d80224a9a24c097a4d52f5507d03de
[ "MIT" ]
1
2021-06-18T05:00:10.000Z
2021-06-18T05:00:10.000Z
// Copyright 2014 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <bsoncxx/stdx/optional.hpp> #include <mongocxx/write_concern.hpp> #include <mongocxx/config/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace options { /// /// Class representing the optional arguments to a MongoDB bulk write /// class MONGOCXX_API bulk_write { public: /// /// Constructs a new bulk_write object. By default, bulk writes are considered ordered /// as this is the only safe choice. If you want an unordered update, you must call /// ordered(false) to switch to unordered mode. /// bulk_write(); /// /// Sets whether the writes must be executed in order by the server. /// /// The server-side default is @c true. /// /// @param ordered /// If @c true all write operations will be executed serially in the order they were appended, /// and the entire bulk operation will abort on the first error. If @c false operations will /// be executed in arbitrary order (possibly in parallel on the server) and any errors will be /// reported after attempting all operations. /// bulk_write& ordered(bool ordered); /// /// Gets the current value of the ordered option. /// /// @return The value of the ordered option. /// bool ordered() const; /// /// Sets the write_concern for this operation. /// /// @param wc /// The new write_concern. /// /// @see https://docs.mongodb.com/master/core/write-concern/ /// bulk_write& write_concern(class write_concern wc); /// /// The current write_concern for this operation. /// /// @return /// The current write_concern. /// /// @see https://docs.mongodb.com/master/core/write-concern/ /// const stdx::optional<class write_concern>& write_concern() const; /// /// Set whether or not to bypass document validation for this operation. /// /// @param bypass_document_validation /// Whether or not to bypass document validation. /// bulk_write& bypass_document_validation(bool bypass_document_validation); /// /// The current setting for bypassing document validation for this operation. /// /// @return /// The current document validation bypass setting. /// const stdx::optional<bool> bypass_document_validation() const; private: bool _ordered; stdx::optional<class write_concern> _write_concern; stdx::optional<bool> _bypass_document_validation; }; } // namespace options MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/postlude.hpp>
30.619048
100
0.682426
[ "object" ]
2c7bf961f9b369667fb8e011a3379f48d34107dc
1,270
cpp
C++
contests/uri/uri-1031.cpp
leomaurodesenv/contest-codes
f7ae7e9d8c67e43dea7ac7dd71afce20d804f518
[ "MIT" ]
null
null
null
contests/uri/uri-1031.cpp
leomaurodesenv/contest-codes
f7ae7e9d8c67e43dea7ac7dd71afce20d804f518
[ "MIT" ]
null
null
null
contests/uri/uri-1031.cpp
leomaurodesenv/contest-codes
f7ae7e9d8c67e43dea7ac7dd71afce20d804f518
[ "MIT" ]
null
null
null
/* * Problema: Crise de Energia * https://www.urionlinejudge.com.br/judge/pt/problems/view/1031 */ #include <iostream> #include <iomanip> #include <cstdio> #include <cstdlib> #include <string> #include <sstream> #include <iomanip> #include <locale> #include <bitset> #include <map> #include <vector> #include <queue> #include <stack> #include <algorithm> #include <cmath> #define INF 0x3F3F3F3F #define PI 3.14159265358979323846 #define EPS 1e-10 #define matrix_i(tipo, lin, col, inic)vector< vector< tipo > > (lin, vector< tipo > (col, inic)) #define matrix_d(tipo)vector< vector< tipo > > #define fore(var, inicio, final) for(int var=inicio;var<final;var++) #define forec(var, inicio, final, cond) for(int var=inicio;var<final;cond) #define forit(it, var) for( it = var.begin(); it != var.end(); it++ ) using namespace std; typedef unsigned long long int llu; typedef long long int lli; /* i<=n para i<n */ int flavious(int n, int k){ int r = 0; for(int i = 1; i < n; i++){ r = (r + k) % i; } return r; } int main(void){ int n, k, r; while(true){ cin>>n; if(n == 0) break; k = 1; do{ r = flavious(n, k); k++; } while(r != 11); cout<<k-1<<endl; } return 0; }
20.483871
96
0.610236
[ "vector" ]
2c800e543706d27031ea5924f328c9a6e9fd9f84
1,659
cc
C++
sim/scenarios/drop-rate/drop-rate-error-model.cc
WesleyRosenblum/quic-network-simulator
b1d8ddf018d89e08ab88d7a229820870e5cb5256
[ "Apache-2.0" ]
null
null
null
sim/scenarios/drop-rate/drop-rate-error-model.cc
WesleyRosenblum/quic-network-simulator
b1d8ddf018d89e08ab88d7a229820870e5cb5256
[ "Apache-2.0" ]
null
null
null
sim/scenarios/drop-rate/drop-rate-error-model.cc
WesleyRosenblum/quic-network-simulator
b1d8ddf018d89e08ab88d7a229820870e5cb5256
[ "Apache-2.0" ]
null
null
null
#include "../helper/tcp-packet.h" #include "../helper/quic-packet.h" #include "drop-rate-error-model.h" using namespace std; NS_OBJECT_ENSURE_REGISTERED(DropRateErrorModel); TypeId DropRateErrorModel::GetTypeId(void) { static TypeId tid = TypeId("DropRateErrorModel") .SetParent<ErrorModel>() .AddConstructor<DropRateErrorModel>() ; return tid; } DropRateErrorModel::DropRateErrorModel() : rate(0), distr(0, 99) { std::random_device rd; rng = new std::mt19937(rd()); } void DropRateErrorModel::DoReset(void) { } bool DropRateErrorModel::DoCorrupt(Ptr<Packet> p) { if(IsUDPPacket(p)) { QuicPacket qp = QuicPacket(p); if (distr(*rng) >= rate) { cout << "Forwarding packet (" << qp.GetUdpPayload().size() << " bytes) from " << qp.GetIpv4Header().GetSource() << endl; qp.ReassemblePacket(); return false; } cout << "Dropping packet (" << qp.GetUdpPayload().size() << " bytes) from " << qp.GetIpv4Header().GetSource() << endl; return true; } else if(IsTCPPacket(p)) { TcpPacket qp = TcpPacket(p); if (distr(*rng) >= rate) { cout << "Forwarding packet (" << qp.GetTcpPayload().size() << " bytes) from " << qp.GetIpv4Header().GetSource() << endl; qp.ReassemblePacket(); return false; } cout << "Dropping packet (" << qp.GetTcpPayload().size() << " bytes) from " << qp.GetIpv4Header().GetSource() << endl; return true; } else { return false; } } void DropRateErrorModel::SetDropRate(int rate_in) { rate = rate_in; }
28.603448
132
0.59132
[ "model" ]
2c8337a533243828012c472294d71fbe17f2f791
3,823
cpp
C++
solutions/17-dynamic-allocation/sources/user-tasks-step17.cpp
pierremolinaro/real-time-kernel-pi-pico
581360dd1135e17fe0c4ddabbe74052a366de7d6
[ "MIT" ]
3
2021-05-05T19:40:01.000Z
2021-05-08T06:40:35.000Z
solutions/17-dynamic-allocation/sources/user-tasks-step17.cpp
pierremolinaro/real-time-kernel-pi-pico
581360dd1135e17fe0c4ddabbe74052a366de7d6
[ "MIT" ]
null
null
null
solutions/17-dynamic-allocation/sources/user-tasks-step17.cpp
pierremolinaro/real-time-kernel-pi-pico
581360dd1135e17fe0c4ddabbe74052a366de7d6
[ "MIT" ]
null
null
null
#include "all-headers.h" //-------------------------------------------------------------------------------------------------- static const uint32_t BUFFER_SIZE = 200 ; //-------------------------------------------------------------------------------------------------- class Buffer { //--- Default constructor public: Buffer (void) : mBuffer (), mCount (0), mReadIndex (0), mMutex (1), mReadSemaphore (0), mWriteSemaphore (BUFFER_SIZE) { } //--- append public: void append (USER_MODE_ const uint8_t * inObject) { mWriteSemaphore.P (MODE) ; mMutex.P (MODE) ; const uint32_t writeIndex = (mCount + mReadIndex) % BUFFER_SIZE ; mBuffer [writeIndex] = inObject ; mCount += 1 ; mMutex.V (MODE) ; mReadSemaphore.V (MODE) ; } //--- remove public: const uint8_t * remove (USER_MODE) { mReadSemaphore.P (MODE) ; mMutex.P (MODE) ; const uint8_t * result = mBuffer [mReadIndex] ; mCount -= 1 ; mReadIndex = (mReadIndex + 1) % BUFFER_SIZE ; mMutex.V (MODE) ; mWriteSemaphore.V (MODE) ; return result ; } //--- Private properties private: const uint8_t * mBuffer [BUFFER_SIZE] ; private: volatile uint32_t mCount = 0 ; private: volatile uint32_t mReadIndex = 0 ; private: Semaphore mMutex ; private: Semaphore mReadSemaphore ; private: Semaphore mWriteSemaphore ; //--- No copy private: Buffer (const Buffer &) = delete ; private: Buffer & operator = (const Buffer &) = delete ; } ; //-------------------------------------------------------------------------------------------------- static volatile uint32_t gProducerCount = 0 ; static Buffer gBuffer ; //-------------------------------------------------------------------------------------------------- static void producerTask (USER_MODE) { uint32_t bufferSize = 1 ; while (1) { if (digitalRead (P4_PUSH_BUTTON)) { const uint8_t * object = new uint8_t [bufferSize] ; gBuffer.append (MODE_ object) ; gProducerCount += 1 ; bufferSize += 1 ; if (bufferSize == 50) { bufferSize = 1 ; } }else{ waitDuring (MODE_ 1) ; } } } //-------------------------------------------------------------------------------------------------- static volatile uint32_t gConsumerCount = 0 ; //-------------------------------------------------------------------------------------------------- static void consumerTask (USER_MODE) { while (1) { const uint8_t * object = gBuffer.remove (MODE) ; delete [] object ; gConsumerCount += 1 ; } } //-------------------------------------------------------------------------------------------------- static void displayTask (USER_MODE) { while (1) { waitDuring (MODE_ 1000) ; gotoXY (MODE_ 0, 0) ; printUnsigned (MODE_ gProducerCount) ; gotoXY (MODE_ 0, 1) ; printUnsigned (MODE_ gConsumerCount) ; gotoXY (MODE_ 0, 2) ; printUnsigned (MODE_ usedRAMByteCount ()) ; gotoXY (MODE_ 0, 3) ; printUnsigned (MODE_ freeRAMByteCount ()) ; } } //-------------------------------------------------------------------------------------------------- static uint64_t gStack0 [64] ; static uint64_t gStack1 [64] ; static uint64_t gStack2 [64] ; //-------------------------------------------------------------------------------------------------- static void initTasks (INIT_MODE) { kernel_createTask (MODE_ gStack0, sizeof (gStack0), displayTask) ; kernel_createTask (MODE_ gStack1, sizeof (gStack1), producerTask) ; kernel_createTask (MODE_ gStack2, sizeof (gStack2), consumerTask) ; } //-------------------------------------------------------------------------------------------------- MACRO_INIT_ROUTINE (initTasks) ; //--------------------------------------------------------------------------------------------------
29.635659
100
0.459587
[ "object" ]
2c9275337219456efd62d000938905bd588e9f38
6,269
hpp
C++
legion/engine/physics/mesh_splitter_utils/half_edge_finder.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
legion/engine/physics/mesh_splitter_utils/half_edge_finder.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
legion/engine/physics/mesh_splitter_utils/half_edge_finder.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
#pragma once #include <physics/mesh_splitter_utils/mesh_splitter_typedefs.hpp> namespace legion::physics { /** @struct HalfEdgeFinder * @brief Responsible for creating a half-edge data structure for a mesh */ struct HalfEdgeFinder { meshHalfEdgePtr currentPtr; /** @brief Given a mesh and its associated transform, * populates the meshHalfEdges queue with the created meshHalfEdgePtrs */ void FindHalfEdge (mesh& mesh, const math::mat4& transform, std::queue<meshHalfEdgePtr>& meshHalfEdges) { VertexIndexToHalfEdgePtr indexToEdgeMap; //[1] find the unique vertices of a mesh. We are currently keeping a list of found //vertices and comparing them to our current vertices // holds the "pointer" to the unique indices inside mesh->Indices std::vector<int> uniqueIndex; // stores the unique vertices of the mesh std::vector<math::vec3> uniquePositions; int uniqueIndexCount = -1; auto& vertices = mesh.vertices; auto& indices = mesh.indices; for (int i = 0; i < vertices.size(); ++i) { math::vec3 position = vertices.at(i); bool isVectorSeen = false; //have we found this vector before? for (int j = 0; j < uniquePositions.size(); j++) { math::vec3 transformedPos = transform * math::vec4(position, 1); math::vec3 uniqueTransformedPos = transform * math::vec4(uniquePositions[j], 1); float dist = math::distance(uniqueTransformedPos, transformedPos); if (math::epsilonEqual<float>(dist, 0.0f, math::epsilon<float>())) { //we have seen this vector before uniqueIndex.push_back(j); isVectorSeen = true; break; } } if (!isVectorSeen) { //we have not seen this position before,add it uniqueIndexCount++; uniqueIndex.push_back(uniqueIndexCount); uniquePositions.push_back(position); } } //[2] use the unique vertices of a mesh to generate half-edge data structure for (int i = 0; i < indices.size(); i += 3) { int firstVertIndex = indices.at(i); int secondVertIndex = indices.at(i + 1); int thirdVertIndex = indices.at(i + 2); int uniqueFirstIndex = uniqueIndex.at(firstVertIndex); int uniqueSecondIndex = uniqueIndex.at(secondVertIndex); int uniqueThirdIndex = uniqueIndex.at(thirdVertIndex); //-----------------instantiate first half edge---------------------// //MeshHalfEdge firstEdge = std::make auto firstEdge = InstantiateEdge(firstVertIndex , edgeVertexIndexPair(uniqueFirstIndex, uniqueSecondIndex), mesh, meshHalfEdges, indexToEdgeMap); //-----------------instantiate second half edge---------------------// auto secondEdge = InstantiateEdge(secondVertIndex , edgeVertexIndexPair(uniqueSecondIndex, uniqueThirdIndex), mesh, meshHalfEdges, indexToEdgeMap); //-----------------instantiate third half edge---------------------// auto thirdEdge = InstantiateEdge(thirdVertIndex , edgeVertexIndexPair(uniqueThirdIndex, uniqueFirstIndex), mesh, meshHalfEdges, indexToEdgeMap); firstEdge->nextEdge = secondEdge; secondEdge->nextEdge = thirdEdge; thirdEdge->nextEdge = firstEdge; } //[3] connect each edge with its pair based on index log::debug("Created {} edges ", meshHalfEdges.size()); for (auto indexEdgePair : indexToEdgeMap) { int u = indexEdgePair.first.first; int v = indexEdgePair.first.second; //for a Halfedge paired with vertices with an index of (u,v), //its pair would be a HalfEdge paired with vertices with an index of (v,u) auto iter = indexToEdgeMap.find(edgeVertexIndexPair(v, u)); if (iter != indexToEdgeMap.end()) { auto edgePair = iter->second; auto otherEdge = indexEdgePair.second; edgePair->pairingEdge = otherEdge; otherEdge->pairingEdge = edgePair; } } currentPtr = meshHalfEdges.front(); } /** @brief Instantiate a new half edge and returns it if its unique */ meshHalfEdgePtr InstantiateEdge(int vertexIndex , const std::pair<int, int> uniqueIndexPair , const mesh& mesh , std::queue<meshHalfEdgePtr>& edgePtrs , VertexIndexToHalfEdgePtr& indexToEdgeMap) { auto firstEdge = std::make_shared<MeshHalfEdge>(mesh.vertices[vertexIndex], mesh.uvs[vertexIndex]); auto edgeToAdd = UniqueAdd(firstEdge, indexToEdgeMap, uniqueIndexPair); edgePtrs.push(edgeToAdd); return edgeToAdd; } /** @brief Checks if a certain edge identified with 'uniqueIndexPair' is unique. If it is, it will * be added to 'edgePtrs'. If its not, the original will take its place. * @return a unique meshHalfEdgePtr */ meshHalfEdgePtr UniqueAdd(meshHalfEdgePtr newEdge, VertexIndexToHalfEdgePtr& indexToEdgeMap, edgeVertexIndexPair uniqueIndexPair) { auto iter = indexToEdgeMap.find(uniqueIndexPair); if (iter != indexToEdgeMap.end()) { return iter->second; } auto pair = uniqueIndexPair; indexToEdgeMap.insert({ pair ,newEdge }); //vertexIndexToHalfEdge.Add(key, value); return newEdge; } }; }
36.236994
137
0.550806
[ "mesh", "vector", "transform" ]
2c9e00d81b7801259c884df9128a4f33d576a809
9,897
cpp
C++
src/main.cpp
kurbaniec/PuzzleGame
5fdf67d14ee635f8c74f82a6b2af4ed354b6e5fe
[ "MIT" ]
null
null
null
src/main.cpp
kurbaniec/PuzzleGame
5fdf67d14ee635f8c74f82a6b2af4ed354b6e5fe
[ "MIT" ]
null
null
null
src/main.cpp
kurbaniec/PuzzleGame
5fdf67d14ee635f8c74f82a6b2af4ed354b6e5fe
[ "MIT" ]
null
null
null
#include <iostream> #include <glad/glad.h> #include <GLFW/glfw3.h> #include "utils/print.h" #include "utils/model.h" #include "engine/model/simplemodel.h" #include "engine/factory/InstanceFactory.h" #include "engine/camera/camera.h" #include "engine/renderer/renderer.h" #include "game/demo/DemoGame.h" #include "game/PuzzleGame.h" // Special Thanks! // =============== // * https://learnopengl.com/ // * https://quaternius.com/packs/ultimateplatformer.html // * https://en.cppreference.com/w/ void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xOffset, double yOffset); void cursor_enter_callback(GLFWwindow* window, int entered); // void processInput(GLFWwindow* window); // void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); void window_focus_callback(GLFWwindow* window, int focused); void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); int main(int argc, char** argv) { // glfw: initialize and configure // ------------------------------ glfwInit(); // Not needed, uses highest version automatically // See: https://www.reddit.com/r/opengl/comments/14kocr/comment/c7eo4l4/?utm_source=share&utm_medium=web2x&context=3 // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // Settings & State management // --------------------------- const unsigned int SCR_WIDTH = 1280; const unsigned int SCR_HEIGHT = 720; auto state = std::make_shared<engine::State>(); auto camera = std::make_shared<engine::Camera>(glm::vec3(0.0f, 0.0f, 3.0f)); auto projection = std::make_shared<engine::Window>(SCR_WIDTH, SCR_HEIGHT, state); auto keys = std::make_shared<map<int, int>>(); auto mouseMovement = std::make_shared<engine::MouseMovement>( static_cast<float>(projection->width), static_cast<float>(projection->height) ); state->setCamera(camera); state->setWindow(projection); state->setKeys(keys); state->setMouseMovement(mouseMovement); // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow( projection->width, projection->height, "Puzzle Game", nullptr, nullptr ); if (window == nullptr) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Pass state to glfw // Node: Do not create void* from shared_ptr, leads to crash in release mode (msvc) // See: https://stackoverflow.com/questions/15578935/proper-way-of-casting-pointer-types // And: https://stackoverflow.com/a/61336206/12347616 // And: https://www.reddit.com/r/cpp_questions/comments/d2owlo/comment/ezw398b/?utm_source=share&utm_medium=web2x&context=3 glfwSetWindowUserPointer(window, static_cast<void*>(state.get())); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // glfwSetKeyCallback(window, key_callback); glfwSetCursorEnterCallback(window, cursor_enter_callback); glfwSetWindowFocusCallback(window, window_focus_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); // Enable/Disable vsync // See: https://www.glfw.org/docs/latest/group__context.html#ga6d4e0cdf151b5e579bd67f13202994ed // glfwSwapInterval(0); // Force aspect ratio // See: https://www.glfw.org/docs/latest/group__window.html#ga72ac8cb1ee2e312a878b55153d81b937 //glfwSetWindowAspectRatio(window, 16, 9); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- auto renderer = std::make_shared<engine::Renderer>(state); renderer->setup(); // Set Game // -------- // Check for demo flag // See: https://stackoverflow.com/a/19989185/12347616 // And: https://stackoverflow.com/a/31016372/12347616 bool isDemo = false; for (char **arg = argv; *arg; ++arg) { if (strcmp(*arg, "demo") == 0) { isDemo = true; } } // Create right level std::unique_ptr<GameBasis> game; if (isDemo) { auto demoGame = std::unique_ptr<GameBasis>(new DemoGame(window, state)); game.swap(demoGame); } else { auto demoGame = std::unique_ptr<GameBasis>(new PuzzleGame(window, state)); game.swap(demoGame); } try { // Setup level game->setup(); // Compute model matrices for (auto& instance: state->instances) { instance.second->updateModelMatrix(); } } catch (const runtime_error& error) { std::cerr << error.what() << std::endl; exit(EXIT_FAILURE); } // render loop // ----------- while (!glfwWindowShouldClose(window)) { // Update delta time state->setCurrentFrame(static_cast<float>(glfwGetTime())); // Clear screen renderer->clear(); try { // Process input & game logic game->update(); // Render renderer->draw(); } catch (const runtime_error& error) { std::cerr << error.what() << std::endl; exit(EXIT_FAILURE); } // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. auto& state = *static_cast<engine::State*>(glfwGetWindowUserPointer(window)); auto projection = state.getWindow(); // Check when minimizing window if (height == 0) height = 1; projection->width = width; projection->height = height; glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- void mouse_callback(GLFWwindow* window, double xpos, double ypos) { auto& state = *static_cast<engine::State*>(glfwGetWindowUserPointer(window)); auto camera = state.getCamera(); auto mouse = state.getMouseMovement(); auto xPos = static_cast<float>(xpos); auto yPos = static_cast<float>(ypos); if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) { if (mouse->firstMouse) { mouse->lastX = xPos; mouse->lastY = yPos; mouse->firstMouse = false; } float xOffset = xPos - mouse->lastX; float yOffset = mouse->lastY - yPos; // reversed since y-coordinates go from bottom to top mouse->lastX = xPos; mouse->lastY = yPos; camera->processMouseMovement(xOffset, yOffset); } } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- void scroll_callback(GLFWwindow* window, double xOffset, double yOffset) { auto& state = *static_cast<engine::State*>(glfwGetWindowUserPointer(window)); auto camera = state.getCamera(); auto offset = static_cast<float>(yOffset); camera->processMouseScroll(offset); } // See: https://www.glfw.org/docs/3.3/input_guide.html#cursor_enter void cursor_enter_callback(GLFWwindow* window, int entered) { if (entered) { // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // The cursor entered the content area of the window } } // See: https://www.glfw.org/docs/latest/window_guide.html#window_focus void window_focus_callback(GLFWwindow* window, int focused) { if (focused) { // The window gained input focus if (glfwGetInputMode(window, GLFW_CURSOR) != GLFW_CURSOR_DISABLED) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } } } void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) { if (glfwGetInputMode(window, GLFW_CURSOR) != GLFW_CURSOR_DISABLED) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); } } } /* // toggle bool firstMouse = true; bool disable = false; bool focus = true; // Recommend way to handle key events // See: https://www.glfw.org/docs/3.3/input_guide.html void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_0 && action == GLFW_PRESS) { disable = !disable; print("Pressed Button 0", " | State: ", disable); } if (key == GLFW_KEY_0 && action == GLFW_RELEASE) { print("Released Button 0"); } }*/
37.206767
127
0.636152
[ "render", "model" ]
2c9fcf42b311469c8098642a99e150874816c634
1,053
cpp
C++
HDU/HDU-2181.cpp
zhchuu/OJ-Solutions
09e1c18104db35d7c6919257ebaa0f170f54796c
[ "MIT" ]
null
null
null
HDU/HDU-2181.cpp
zhchuu/OJ-Solutions
09e1c18104db35d7c6919257ebaa0f170f54796c
[ "MIT" ]
null
null
null
HDU/HDU-2181.cpp
zhchuu/OJ-Solutions
09e1c18104db35d7c6919257ebaa0f170f54796c
[ "MIT" ]
null
null
null
/* * HDU-2181 * Hint: dfs * */ #include<stdio.h> #include<memory.h> #include<algorithm> #include<math.h> #include<vector> using namespace std; const int maxn = 20+2; int map[maxn][3], m, cnt; bool vis[maxn]; vector<int> store; void output(){ printf("%d: ", ++cnt); for(int i=0; i<store.size(); i++) printf("%d ", store[i]); printf("%d\n", m); } void dfs(int now, int total){ if(total >= 20){ if(map[now][0] == m || map[now][1] == m || map[now][2] == m) output(); return; }//if for(int i=0; i<3; i++) if(!vis[map[now][i]]){ vis[map[now][i]] = true; store.push_back(map[now][i]); dfs(map[now][i], total+1); store.pop_back(); vis[map[now][i]] = false; } } int main(){ for(int i=1; i<=20; i++) scanf("%d %d %d", &map[i][0], &map[i][1], &map[i][2]); while(~scanf("%d", &m) && m){ cnt = 0; memset(vis, 0, sizeof(vis)); store.push_back(m); vis[m] = true; dfs(m, 1); } return 0; }
20.25
68
0.474834
[ "vector" ]
2c9fd7bdeb8ec0f44fa060178c63e7179b601cc7
5,238
hpp
C++
Source/AllProjects/CIDKernel/CIDKernel_Signals.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/CIDKernel/CIDKernel_Signals.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/CIDKernel/CIDKernel_Signals.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDKernel_Signals.hpp // // AUTHOR: Dean Roddey // // CREATED: 07/25/1999 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for the CIDKernel_SignalHandler.Cpp file. This file // implements the TKrnlSignals namespace, which is the low level mechanism for // handling a small set of async signals that come from the system. It // supports a stack of handlers which can be pushed and popped back off. At // the CIDLib level, safe scope based push/pop is supported via a janitor // class. // // TSignalCallback is an abstract interface via which handlers are called. // This allows classes to implement the interface and have their overridden // method called when signals come in. // // Also defined here is TKrnlSignalJanitor, which is a signal install // janitor for use within the kernel. For public use, CIDLib defines a // higher level one, so this is just for within the kernel so its not // exported. // // CAVEATS/GOTCHAS: // // 1) Installed handler objects are NOT adopted, because they are always // some other type of class into which MSignalHandler is mixed into. // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: MSignalHandler // PREFIX: msh // --------------------------------------------------------------------------- class KRNLEXPORT MSignalHandler { public : // ------------------------------------------------------------------- // Destructor. Constructors are all hidden // ------------------------------------------------------------------- virtual ~MSignalHandler(); // ------------------------------------------------------------------- // Public, virtual methods // ------------------------------------------------------------------- virtual tCIDLib::TBoolean bHandleSignal ( const tCIDLib::ESignals eSignal ) = 0; protected : // ------------------------------------------------------------------- // Hidden constructors and operators // ------------------------------------------------------------------- MSignalHandler(); MSignalHandler(const MSignalHandler&); tCIDLib::TVoid operator=(const MSignalHandler&); }; // --------------------------------------------------------------------------- // The TKrnlSignals namespace // --------------------------------------------------------------------------- namespace TKrnlSignals { // ----------------------------------------------------------------------- // Publically exported methods // ----------------------------------------------------------------------- KRNLEXPORT tCIDLib::TBoolean bRemoveHandler ( MSignalHandler* const pmshToRemove , const tCIDLib::TCard4 c4HandlerId ); KRNLEXPORT tCIDLib::TCard4 c4AddHandler ( MSignalHandler* const pmshToAdd ); KRNLEXPORT tCIDLib::TVoid GenerateCtrlCSignal(); // ----------------------------------------------------------------------- // These are for internal use, and are not exported // ----------------------------------------------------------------------- tCIDLib::TBoolean bCallHandlers ( const tCIDLib::ESignals eSignal ); tCIDLib::TVoid PlatformInit(); } // --------------------------------------------------------------------------- // CLASS: TKrnlSignalJanitor // PREFIX: jan // --------------------------------------------------------------------------- class TKrnlSignalJanitor { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TKrnlSignalJanitor() = delete; TKrnlSignalJanitor ( MSignalHandler* const pmshToAdd ); TKrnlSignalJanitor(const TKrnlSignalJanitor&) =delete; ~TKrnlSignalJanitor(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TKrnlSignalJanitor& operator=(const TKrnlSignalJanitor&) = delete; private : // ------------------------------------------------------------------- // private data members // // m_c4HandlerId // The id we are given upon installation and which we must give // back when removing. // // m_pmshToAdd // The handler object that is added, and then removed. // ------------------------------------------------------------------- tCIDLib::TCard4 m_c4HandlerId; MSignalHandler* m_pmshToAdd; }; #pragma CIDLIB_POPPACK
31.939024
79
0.434326
[ "object" ]
2ca29a20da2eedc177253c5dc58b05403d5db22f
1,357
cpp
C++
LeetCode/AC/598.cpp
JackoQm/Daily_Practices
1662ab963263a27ca8b183463ea645935e86fee6
[ "MIT" ]
null
null
null
LeetCode/AC/598.cpp
JackoQm/Daily_Practices
1662ab963263a27ca8b183463ea645935e86fee6
[ "MIT" ]
null
null
null
LeetCode/AC/598.cpp
JackoQm/Daily_Practices
1662ab963263a27ca8b183463ea645935e86fee6
[ "MIT" ]
null
null
null
/* * From: LeetCode - 598. Range Addition II (https://leetcode.com/problems/range-addition-ii/description/) * Level: Easy * Question: Given an m * n matrix M initialized with all 0's and several update operations. Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b. You need to count and return the number of maximum integers in the matrix after performing all the operations. * Status: AC * Solution: Using set intersection(https://leetcode.com/problems/range-addition-ii/solution/) */ #include <iostream> #include <set> using namespace std; class Solution { public: int maxCount(int m, int n, vector<vector<int>>& ops) { int begin, end; begin = m; end = n; for(int i = 0; i < ops.size(); ++i) { int b, e; b = ops[i][0], e = ops[i][1]; if(b < begin) begin = b; if(e < end) end = e; } return begin*end; } }; /* Standard Answer: public class Solution { public int maxCount(int m, int n, int[][] ops) { for (int[] op: ops) { m = Math.min(m, op[0]); n = Math.min(n, op[1]); } return m * n; } } */
28.87234
206
0.572587
[ "vector" ]
2ca4051d2f6f319ecec7c471ad45e6d4e7fb5a0a
4,345
hpp
C++
bnn/cuda/core/tensor_impl.hpp
czgdp1807/BNN
9c080eda661aa289b30a1b6105b6c2732ac92d77
[ "BSD-3-Clause" ]
1
2020-01-22T20:18:17.000Z
2020-01-22T20:18:17.000Z
bnn/cuda/core/tensor_impl.hpp
czgdp1807/BNN
9c080eda661aa289b30a1b6105b6c2732ac92d77
[ "BSD-3-Clause" ]
null
null
null
bnn/cuda/core/tensor_impl.hpp
czgdp1807/BNN
9c080eda661aa289b30a1b6105b6c2732ac92d77
[ "BSD-3-Clause" ]
null
null
null
#ifndef BNN_BNN_CUDA_CORE_TENSOR_IMPL_HPP #define BNN_BNN_CUDA_CORE_TENSOR_IMPL_HPP #include <bnn/cuda/core/tensor.hpp> #include <bnn/cuda/utils/cuda_wrappers.hpp> #include <bnn/utils/utils.hpp> namespace bnn { namespace cuda { namespace core { template <class data_type> data_type* TensorGPU<data_type>::_reserve_space_gpu (std::vector<unsigned>& shape) { unsigned total_space = 1; for(unsigned i = 0; i < shape.size(); i++) { total_space *= shape.at(i); } data_type* pointer; bnn::cuda::utils::cuda_malloc((void**)(&pointer), total_space*sizeof(data_type)); return pointer; } template <class data_type> unsigned* TensorGPU<data_type>::_init_shape_gpu (std::vector<unsigned>& shape) { unsigned* _shape = new unsigned[shape.size()]; for(unsigned i = 0; i < shape.size(); i++) { _shape[i] = shape.at(i); } return _shape; } template <class data_type> TensorGPU<data_type>::TensorGPU(): bnn::core::TensorCPU<data_type>::TensorCPU(), data_gpu(NULL), ndims_gpu(0), shape_gpu(NULL) { } template <class data_type> TensorGPU<data_type>::TensorGPU (std::vector<unsigned>& shape): bnn::core::TensorCPU<data_type>::TensorCPU(shape), data_gpu(_reserve_space_gpu(shape)), ndims_gpu(shape.size()), shape_gpu(_init_shape_gpu(shape)) { } template <class data_type> unsigned* TensorGPU<data_type>::get_shape(bool gpu) { return gpu ? this->shape_gpu : this->bnn::core::TensorCPU<data_type> ::get_shape(); } template <class data_type> unsigned TensorGPU<data_type>::get_ndims(bool gpu) { return gpu ? this->ndims_gpu : this->bnn::core::TensorCPU<data_type> ::get_ndims(); } template <class data_type> data_type* TensorGPU<data_type>::get_data_pointer(bool gpu) { return gpu ? this->data_gpu : this->bnn::core::TensorCPU<data_type> ::get_data_pointer(); } template <class data_type> void TensorGPU<data_type>::copy_to_host() { unsigned size = 1; for(unsigned i = 0; i < this->get_ndims(true); i++) { size *= this->get_shape(true)[i]; } bnn::cuda::utils::cuda_memcpy( this->get_data_pointer(false), this->get_data_pointer(true), size*sizeof(data_type), bnn::cuda::utils::DeviceToHost); } template <class data_type> void TensorGPU<data_type>::copy_to_device() { unsigned size = 1; for(unsigned i = 0; i < this->get_ndims(false); i++) { size *= this->get_shape(false)[i]; } bnn::cuda::utils::cuda_memcpy( this->get_data_pointer(true), this->get_data_pointer(false), size*sizeof(data_type), bnn::cuda::utils::HostToDevice); } template <class data_type> TensorGPU<data_type>::~TensorGPU() { if(this->shape_gpu != NULL) bnn::cuda::utils::cuda_free((void*)this->shape_gpu); if(this->data_gpu != NULL) bnn::cuda::utils::cuda_free((void*)this->data_gpu); } #include "bnn/templates/cuda_core_tensor.hpp" } } } #endif
31.715328
77
0.457537
[ "shape", "vector" ]
2ca4d1414829c9bd7d46cf4c9fc5ed819fd761d6
1,360
cpp
C++
1054/ConsoleApplicationLab3/ConsoleApplicationLab3/Source.cpp
catalinboja/cpp_examples_2016
784741ea12fd3dd2ebc659b431f7daaf17898956
[ "Apache-2.0" ]
null
null
null
1054/ConsoleApplicationLab3/ConsoleApplicationLab3/Source.cpp
catalinboja/cpp_examples_2016
784741ea12fd3dd2ebc659b431f7daaf17898956
[ "Apache-2.0" ]
null
null
null
1054/ConsoleApplicationLab3/ConsoleApplicationLab3/Source.cpp
catalinboja/cpp_examples_2016
784741ea12fd3dd2ebc659b431f7daaf17898956
[ "Apache-2.0" ]
4
2016-12-21T15:31:37.000Z
2018-08-04T10:36:34.000Z
#include <iostream> using namespace std; class Student { public: int code; char* name; public: int* grades; int noGrades; }; Student initStudent(Student s) { s.code = 0; //DON'T DO THIS //s.name = "John Doe"; s.name = new char [strlen("John Doe")+1]; strcpy(s.name, "John Doe"); s.noGrades = 0; s.grades = NULL; // = 0 return s; } void initStudent2(Student *ps) { ps->code = 0; //DON'T DO THIS //ps->name = "John Doe"; ps->name = new char[strlen("John Doe") + 1]; strcpy(ps->name, "John Doe"); ps->noGrades = 0; ps->grades = NULL; } void initStudent3(Student& s) { s.code = 0; //DON'T DO THIS //s.name = "John Doe"; s.name = new char[strlen("John Doe") + 1]; strcpy(s.name, "John Doe"); s.noGrades = 0; s.grades = NULL; // = 0 } void changeStudentName(Student& s) { cout << endl << "Please insert the new name "; char temp[1000]; cin >> temp; //clear the memory leak if(s.name!=NULL) delete [] s.name; s.name = new char [strlen(temp)+1]; strcpy(s.name, temp); } void main() { //creating an object Student student; //student = initStudent(student); //initStudent2(&student); initStudent3(student); cout << endl << "The student " << student.name << " has the code " << student.code; changeStudentName(student); cout << endl << "The student " << student.name << " has the code " << student.code; }
17.435897
47
0.618382
[ "object" ]
2ca66001716b6b129edee9a049a6ee06787df1bb
14,210
cpp
C++
src/core/demo/NTTSource.cpp
mattdano/palisade
6e49bc3a850672a142eea209e6d71505e689cb81
[ "BSD-2-Clause" ]
null
null
null
src/core/demo/NTTSource.cpp
mattdano/palisade
6e49bc3a850672a142eea209e6d71505e689cb81
[ "BSD-2-Clause" ]
null
null
null
src/core/demo/NTTSource.cpp
mattdano/palisade
6e49bc3a850672a142eea209e6d71505e689cb81
[ "BSD-2-Clause" ]
null
null
null
/* * @author TPOC: contact@palisade-crypto.org * * @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT) * 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. * */ // This is a main() file built to test and time NTT operations // D. Cousins #define PROFILE //need to define in order to turn on timing #define TEST1 //#define TEST2 //#define TEST3 #include <iostream> #include <fstream> #include <vector> #include "math/backend.h" #include "lattice/elemparams.h" #include "lattice/ilparams.h" #include "lattice/ildcrtparams.h" #include "lattice/ilelement.h" #include "utils/inttypes.h" #include "math/distrgen.h" #include "encoding/plaintext.h" #include "time.h" #include <chrono> #include <exception> #include "utils/debug.h" using namespace std; using namespace lbcrypto; //define the main sections of the test void test_NTT(void); // test code //main() need this for Kurts' makefile to ignore this. int main(int argc, char* argv[]){ test_NTT(); return 0; } //Testing macro runs the desired code // res = fn // an a loop nloop times, timed with timer t with res compared to testval #define TESTIT(t, res, fn, testval, nloop) do { \ try { \ TIC(t); \ for (usint j = 0; j< nloop; j++){ \ res = (fn); \ } \ time2 = TOC(t); \ DEBUG(#t << ": " << nloop << " loops " << #res << " = " << #fn << " computation time: " << "\t" << time2 << " us"); \ if (res != testval){ \ cout << "Bad " << #res << " = " << #fn << endl; \ /*vec_diff(res, testval);*/ \ } \ }catch(exception & e) {cout<< #res << " = " << #fn << " caught exception "<< e.what() <<endl;} \ } while (0); //helper function that bulds BigVector from a vector of strings BigVector BBVfromStrvec( std::vector<std::string> &s) { BigVector a(s.size()); for (usint i = 0; i< s.size(); i++){ a.at(i)=s[i]; } return a; } //function to compare two BigVectors and print differing indicies void vec_diff(BigVector &a, BigVector &b) { for (usint i= 0; i < a.GetLength(); ++i){ if (a.at(i) != b.at(i)) { cout << "i: "<< i << endl; cout << "first vector " <<endl; cout << a.at(i); cout << endl; cout << "second vector " <<endl; cout << b.at(i); cout << endl; } } } //function to compare two Poly and print differing values bool clonetest(Poly &a, Poly &b, string name){ if (a != b){ cout << name <<" FAILED "<<endl; cout <<"a:" << a << endl; cout <<"b:" << b << endl; return true; } else { return false; } } //main NTT test suite. void test_NTT () { // Code to test NTT at three different numbers of limbs. int nloop = 100; //number of times to run each test for timing. TimeVar t1,t2, t3,t_total; // timers for TIC() TOC() // captures the time double time1ar, time1af; double time2ar, time2af; double time3ar, time3af; double time1br, time1bf; double time2br, time2bf; double time3br, time3bf; cout<<"testing NTT backend "<<MATHBACKEND; if (BigIntegerBitLength >0) cout<<" BITLENGTH "<< BigIntegerBitLength <<endl; TIC(t_total); //there are three test cases, 1) small modulus 2) approx 48 bits. //3) large numbers and two examples of each //note this fails BigInteger q1 = {"163841"}; BigInteger q1 ("163841"); // for each vector, define a, b inputs as vectors of strings std::vector<std::string> a1strvec = { "127753", "077706", "017133", "022582", "112132", "027625", "126773", "008924", "125972", "002551", "113837", "112045", "100953", "077352", "132013", "057029", }; // this fails too!!! BigVector a1(a1string); // so I wrote this function BigVector a1 = BBVfromStrvec(a1strvec); a1.SetModulus(q1); //b: std::vector<std::string> b1strvec = { "066773", "069572", "142134", "141115", "123182", "155822", "128147", "094818", "135782", "030844", "088634", "099407", "053647", "111689", "028502", "026401", }; BigVector b1 = BBVfromStrvec(b1strvec); b1.SetModulus(q1); //test case 2 BigInteger q2 ("00004057816419532801"); std::vector<std::string> a2strvec = { "00000185225172798255", "00000098879665709163", "00003497410031351258", "00004012431933509255", "00001543020758028581", "00000135094568432141", "00003976954337141739", "00004030348521557120", "00000175940803531155", "00000435236277692967", "00003304652649070144", "00002032520019613814", "00000375749152798379", "00003933203511673255", "00002293434116159938", "00001201413067178193", }; BigVector a2 = BBVfromStrvec(a2strvec); a2.SetModulus(q2); std::vector<std::string> b2strvec = { "00000698898215124963", "00000039832572186149", "00001835473200214782", "00001041547470449968", "00001076152419903743", "00000433588874877196", "00002336100673132075", "00002990190360138614", "00000754647536064726", "00000702097990733190", "00002102063768035483", "00000119786389165930", "00003976652902630043", "00003238750424196678", "00002978742255253796", "00002124827461185795", }; BigVector b2 = BBVfromStrvec(b2strvec); b2.SetModulus(q2); //test case 3 //q3: very large numbers. BigInteger q3("3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589431"); std::vector<std::string> a3strvec = { "2259002487796164904665772121894078584543401744155154298312726209247751689172189255653866355964200768484575418973864307364757237946940733747446643725054", "1478743816308009734668992873633380110912159803397999015955212019971253231528589466789603074746010444199132421555598329082557053986240265071537647362089", "2442250766561334341166822783674395133995556495312318016431141348749482739749788174173081312927274880146329980363424977565638001056841245678661782610982", "917779106114096279364098211126816308037915672568153320523308800097705587686270523428976942621563981845568821206569141624247183330715577260930218556767", "214744931049447103852875386182628152420432967632133352449560778740158135437968557572597545037670326240142368149137864407874100658923913041236510842284", "3022931024526554241483841300690432083112912011870712018209552253068347592628043101662926263810401378532416655773738499681026278335470355055192240903881", "2177879458107855257699914331737144896274676269055062432826552808869348125407671199582563543692287114712642299482144959316835614426673048987634699368975", "297233451802123294436846683552230198845414118375785255038220841170372509047202030175469239142902723134737621108313142071558385068315554041062888072990" }; BigVector a3 = BBVfromStrvec(a3strvec); a3.SetModulus(q3); std::vector<std::string> b3strvec = { "1746404952192586268381151521422372143182145525977836700420382237240400642889251297954418325675184427789348433626369450669892557208439401215109489355089", "220598825371098531288665964851212313477741334812037568788443848101743931352326362481681721872150902208420539619641973896119680592696228972313317042316", "1636408035867347783699588740469182350452165486745277203525427807971352063169622066488977229506420856017031482691439089288020262006748233954177669740311", "1391860681743495586446518646883933051685658718352722633694285758474124803847473349064660555618847951719510263829699292297119131926436045214364252430665", "840450278810654165061961485691366961514650606247291814263792869596294713810125269780258316551932763106025157596216051681623225968811609560121609943365", "2329731862150094912355786583702878434766436140738594274867891494713002534085652731920888891507522355867974791619686673574928137376468103839586921126803", "3059472316627396548271906051517665887700234192652488639437431254697285170484189458770168152800520702020313091234437806236204196526193455750117363744648", "132216870748476988853044482759545262615616157934129470128771906579101230690441206392939162889560305016204867157725209170345968349185675785497832527174" }; BigVector b3 = BBVfromStrvec(b3strvec); b3.SetModulus(q3); #if 1 usint m = 32; // BigInteger modulus(q1); // NextQ(modulus, BigInteger("2"), m1, BigInteger("4"), BigInteger("4")); #ifdef TEST1 BigInteger rootOfUnity1(RootOfUnity<BigInteger>(m, q1)); ILParams params1(m, q1, rootOfUnity1); shared_ptr<ILParams> x1p(new ILParams(params1)); Poly x1a(x1p, Format::COEFFICIENT); //a1.SetModulus(modulus); //note setting modulus does not perform a modulus. //a1.Mod(modulus); x1a.SetValues(a1, Format::COEFFICIENT); Poly x1b(x1p, Format::COEFFICIENT); //b1.SetModulus(modulus); //b1.Mod(modulus); x1b.SetValues(b1, Format::COEFFICIENT); Poly x1aClone(x1a); Poly x1bClone(x1b); #endif #ifdef TEST2 BigInteger rootOfUnity2(RootOfUnity<BigInteger>(m, q2)); ILParams params2(m, q2, rootOfUnity2); shared_ptr<ILParams> x2p(new ILParams(params2)); Poly x2a(x2p, Format::COEFFICIENT); //a2.SetModulus(modulus); //note setting modulus does not perform a modulus. //a2.Mod(modulus); x2a.SetValues(a2, Format::COEFFICIENT); Poly x2b(x2p, Format::COEFFICIENT); //b2.SetModulus(modulus); //b2.Mod(modulus); x2b.SetValues(b2, Format::COEFFICIENT); Poly x2aClone(x2a); Poly x2bClone(x2b); #endif #ifdef TEST3 NextQ(q3, BigInteger("2"), m, BigInteger("4"), BigInteger("4")); cout << "q3 : "<<q3.ToString()<<endl; BigInteger rootOfUnity3(RootOfUnity<BigInteger>(m, q3)); cout << "rootOfUnity3 : "<<rootOfUnity3.ToString()<<endl; ILParams params3(m, q3, rootOfUnity3); shared_ptr<ILParams> x3p(new ILParams(params3)); Poly x3a(x3p, Format::COEFFICIENT); //a3.SetModulus(modulus); //note setting modulus does not perform a modulus. //a3.Mod(modulus); x3a.SetValues(a3, Format::COEFFICIENT); Poly x3b(x3p, Format::COEFFICIENT); //b3.SetModulus(modulus); //b3.Mod(modulus); x3b.SetValues(b3, Format::COEFFICIENT); Poly x3aClone(x3a); Poly x3bClone(x3b); #endif time1af = 0.0; time1bf = 0.0; time2af = 0.0; time2bf = 0.0; time3af = 0.0; time3bf = 0.0; time1ar = 0.0; time1br = 0.0; time2ar = 0.0; time2br = 0.0; time3ar = 0.0; time3br = 0.0; bool failed = false; int ix; cout << "Startng timing"<<endl; for (ix = 0; ix <nloop; ix++) { if (ix%100 == 0) cout << ix <<endl; #ifdef TEST1 //forward TIC(t1); x1a.SwitchFormat(); time1af += TOC_US(t1); TIC(t1); x1b.SwitchFormat(); time1bf += TOC_US(t1); #endif #ifdef TEST2 TIC(t1); x2a.SwitchFormat(); time2af += TOC_US(t1); TIC(t1); x2b.SwitchFormat(); time2bf += TOC_US(t1); #endif #ifdef TEST3 TIC(t1); x3a.SwitchFormat(); time3af += TOC_US(t1); TIC(t1); x3b.SwitchFormat(); time3bf += TOC_US(t1); #endif #ifdef TEST1 //reverse TIC(t1); x1a.SwitchFormat(); time1ar += TOC_US(t1); TIC(t1); x1b.SwitchFormat(); time1br += TOC_US(t1); #endif #ifdef TEST2 TIC(t1); x2a.SwitchFormat(); time2ar += TOC_US(t1); TIC(t1); x2b.SwitchFormat(); time2br += TOC_US(t1); #endif #ifdef TEST3 TIC(t1); x3a.SwitchFormat(); time3ar += TOC_US(t1); TIC(t1); x3b.SwitchFormat(); time3br += TOC_US(t1); #endif #ifdef TEST1 failed |= clonetest(x1a, x1aClone, "x1a"); failed |= clonetest(x1b, x1bClone, "x1b"); #endif #ifdef TEST2 failed |= clonetest(x2a, x2aClone, "x2a"); failed |= clonetest(x2b, x2bClone, "x2b"); #endif #ifdef TEST3 failed |= clonetest(x3a, x3aClone, "x3a"); failed |= clonetest(x3b, x3bClone, "x3b"); #endif } if (failed) { cout << "failure in loop number "<< ix<<endl; } else { time1af/=(double)nloop; time1bf/=(double)nloop; time2af/=(double)nloop; time2bf/=(double)nloop; time3af/=(double)nloop; time3bf/=(double)nloop; time1ar/=(double)nloop; time1br/=(double)nloop; time2ar/=(double)nloop; time2br/=(double)nloop; time3ar/=(double)nloop; time3br/=(double)nloop; cout << nloop << " loops"<<endl; cout << "t1af: " << "\t" << time1af << " us"<< endl; cout << "t1bf: " << "\t" << time1bf << " us"<< endl; cout << "t2af: " << "\t" << time2af << " us"<< endl; cout << "t2bf: " << "\t" << time2bf << " us"<< endl; cout << "t3af: " << "\t" << time3af << " us"<< endl; cout << "t3bf: " << "\t" << time3bf << " us"<< endl; cout << "t1ar: " << "\t" << time1ar << " us"<< endl; cout << "t1br: " << "\t" << time1br << " us"<< endl; cout << "t2ar: " << "\t" << time2ar << " us"<< endl; cout << "t2br: " << "\t" << time2br << " us"<< endl; cout << "t3ar: " << "\t" << time3ar << " us"<< endl; cout << "t3br: " << "\t" << time3br << " us"<< endl; } #endif return ; }
31.577778
171
0.689937
[ "vector" ]
2cad21987fbc9261c4ec1ad8cf54d5f40209168e
7,648
cpp
C++
circe/gl/scene/bvh.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
1
2021-09-17T18:12:47.000Z
2021-09-17T18:12:47.000Z
circe/gl/scene/bvh.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
null
null
null
circe/gl/scene/bvh.cpp
gui-works/circe
c126a8f9521dca1eb23ac47c8f2e8081f2102f17
[ "MIT" ]
2
2021-09-17T18:13:02.000Z
2021-09-17T18:16:21.000Z
/* * Copyright (c) 2017 FilipeCN * * The MIT License (MIT) * * 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 <circe/gl/scene/bvh.h> #include <algorithm> #include <hermes/structures/bvh.h> #include <vector> namespace circe::gl { BVH::BVH(SceneMeshObjectSPtr m) { sceneMesh = m; std::vector<BVHElement> buildData; for (size_t i = 0; i < sceneMesh->mesh()->rawMesh()->meshDescriptor.count; i++) buildData.emplace_back( BVHElement(i, sceneMesh->mesh()->rawMesh()->elementBBox(i))); uint32_t totalNodes = 0; orderedElements.reserve(sceneMesh->mesh()->rawMesh()->meshDescriptor.count); root = recursiveBuild(buildData, 0, sceneMesh->mesh()->rawMesh()->meshDescriptor.count, &totalNodes, orderedElements); nodes.resize(totalNodes); for (uint32_t i = 0; i < totalNodes; i++) new (&nodes[i]) LinearBVHNode; uint32_t offset = 0; flattenBVHTree(root, &offset); } BVH::BVHNode *BVH::recursiveBuild(std::vector<BVHElement> &buildData, uint32_t start, uint32_t end, uint32_t *totalNodes, std::vector<uint32_t> &orderedElements) { (*totalNodes)++; BVHNode *node = new BVHNode(); hermes::bbox3 bbox; for (uint32_t i = start; i < end; ++i) bbox = hermes::make_union(bbox, buildData[i].bounds); // compute all bounds uint32_t nElements = end - start; if (nElements == 1) { // create leaf node uint32_t firstElementOffset = orderedElements.size(); for (uint32_t i = start; i < end; i++) { uint32_t elementNum = buildData[i].ind; orderedElements.emplace_back(elementNum); } node->initLeaf(firstElementOffset, nElements, bbox); } else { // compute bound of primitives hermes::bbox3 centroidBounds; for (uint32_t i = start; i < end; i++) centroidBounds = hermes::make_union(centroidBounds, buildData[i].centroid); int dim = centroidBounds.maxExtent(); // partition primitives uint32_t mid = (start + end) / 2; if (centroidBounds.upper[dim] == centroidBounds.lower[dim]) { node->initInterior( dim, recursiveBuild(buildData, start, mid, totalNodes, orderedElements), recursiveBuild(buildData, mid, end, totalNodes, orderedElements)); return node; } // partition into equally sized subsets std::nth_element(&buildData[start], &buildData[mid], &buildData[end - 1] + 1, Comparepoints(dim)); node->initInterior( dim, recursiveBuild(buildData, start, mid, totalNodes, orderedElements), recursiveBuild(buildData, mid, end, totalNodes, orderedElements)); } return node; } uint32_t BVH::flattenBVHTree(BVHNode *node, uint32_t *offset) { LinearBVHNode *linearNode = &nodes[*offset]; linearNode->bounds = node->bounds; uint32_t myOffset = (*offset)++; if (node->nElements > 0) { linearNode->elementsOffset = node->firstElementOffset; linearNode->nElements = node->nElements; } else { linearNode->axis = node->splitAxis; linearNode->nElements = 0; flattenBVHTree(node->children[0], offset); linearNode->secondChildOffset = flattenBVHTree(node->children[1], offset); } return myOffset; } int BVH::intersect(const hermes::Ray3 &ray, float *t) { PONOS_UNUSED_VARIABLE(t); if (nodes.empty()) return false; hermes::Transform inv = hermes::inverse(sceneMesh->transform); hermes::Ray3 r = inv(ray); int hit = 0; hermes::vec3 invDir(1.f / r.d.x, 1.f / r.d.y, 1.f / r.d.z); uint32_t dirIsNeg[3] = {invDir.x < 0, invDir.y < 0, invDir.z < 0}; uint32_t todoOffset = 0, nodeNum = 0; uint32_t todo[64]; while (true) { LinearBVHNode *node = &nodes[nodeNum]; if (intersect(node->bounds, r, invDir, dirIsNeg)) { if (node->nElements > 0) { // intersect ray with primitives for (uint32_t i = 0; i < node->nElements; i++) { hermes::point3 v0 = sceneMesh->mesh()->rawMesh()->positionElement( orderedElements[node->elementsOffset + i], 0); hermes::point3 v1 = sceneMesh->mesh()->rawMesh()->positionElement( orderedElements[node->elementsOffset + i], 1); hermes::point3 v2 = sceneMesh->mesh()->rawMesh()->positionElement( orderedElements[node->elementsOffset + i], 2); if (hermes::triangle_ray_intersection(v0, v1, v2, r)) hit++; } if (todoOffset == 0) break; nodeNum = todo[--todoOffset]; } else { if (dirIsNeg[node->axis]) { todo[todoOffset++] = nodeNum + 1; nodeNum = node->secondChildOffset; } else { todo[todoOffset++] = node->secondChildOffset; nodeNum++; } } } else { if (todoOffset == 0) break; nodeNum = todo[--todoOffset]; } } return hit; } bool BVH::intersect(const hermes::bbox3 &bounds, const hermes::Ray3 &ray, const hermes::vec3 &invDir, const uint32_t dirIsNeg[3]) const { float hit1, hit2; return hermes::bbox_ray_intersection(bounds, ray, hit1, hit2); float tmin = (bounds[dirIsNeg[0]].x - ray.o.x) * invDir.x; float tmax = (bounds[1 - dirIsNeg[0]].x - ray.o.x) * invDir.x; float tymin = (bounds[dirIsNeg[1]].y - ray.o.y) * invDir.y; float tymax = (bounds[1 - dirIsNeg[1]].y - ray.o.y) * invDir.y; if ((tmin < tymax) || (tymin > tmax)) return false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; float tzmin = (bounds[dirIsNeg[2]].z - ray.o.z) * invDir.z; float tzmax = (bounds[1 - dirIsNeg[2]].z - ray.o.z) * invDir.z; if ((tmin < tzmax) || (tzmin > tmax)) return false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; return tmax > 0; } bool BVH::isInside(const hermes::point3 &p) { hermes::Ray3 r(p, hermes::vec3(1.2, 1.1, 0.1)); hermes::Ray3 r2(p, hermes::vec3(0.2, -1.1, 0.1)); return intersect(r, nullptr) % 2 && intersect(r2, nullptr) % 2; int hit = 0, hit2 = 0; for (size_t i = 0; i < sceneMesh->mesh()->rawMesh()->meshDescriptor.count; i++) { hermes::point3 v0 = sceneMesh->mesh()->rawMesh()->positionElement(i, 0); hermes::point3 v1 = sceneMesh->mesh()->rawMesh()->positionElement(i, 1); hermes::point3 v2 = sceneMesh->mesh()->rawMesh()->positionElement(i, 2); if (hermes::triangle_ray_intersection(v0, v1, v2, r)) hit++; if (hermes::triangle_ray_intersection(v0, v1, v2, r2)) hit2++; } return hit % 2 && hit2 % 2; } } // namespace circe
37.126214
81
0.634022
[ "mesh", "vector", "transform" ]
2cb654ef9b4f07ec00ebd629db2e7c37148c999d
3,136
cpp
C++
src/Manager.cpp
sunillshastry/residence-cli
40c1164105839557317af3eea1b820bef60f23d4
[ "MIT" ]
null
null
null
src/Manager.cpp
sunillshastry/residence-cli
40c1164105839557317af3eea1b820bef60f23d4
[ "MIT" ]
7
2022-01-07T13:32:46.000Z
2022-01-09T16:26:33.000Z
src/Manager.cpp
sunillshastry/residence-cli
40c1164105839557317af3eea1b820bef60f23d4
[ "MIT" ]
null
null
null
#include <iostream> // #include <vector> #include "./../include/Manager.h" /** * The default constructor for the Manager class. Initialises all values to null or zero * Uses the BasicManager class to set all the attribute values to zero */ Manager::Manager() : BasicManager() {} /** * The main constructor for the Manager class. Initialises all values to their respective attributes * Uses the BasicManager class to initialise all the attributes * @param name The name of the manager * @param social_insurance_number The Social Insurance Number of the manager * @param employee_id The unique employee identity number of the manager */ Manager::Manager(std::string name, std::string social_insurance_number, std::string employee_id) : BasicManager(name, social_insurance_number, employee_id) {} /** * Adds a student to the list of all student associated to the manager * Adds a student only if the object is not present already * @param student The student (object) that is to be added */ /* void Manager::add_student(Student student) { if (this->has_student(student.get_student_id())) { throw -1; } else { this->students_list.push_back(student); } } */ /** * Checks if a student is already present in the list of student associated to the manager * @param student_id The unique student identity number * @return true if the student is present, else false */ /* bool Manager::has_student(std::string student_id) { for (int i = 0; i < static_cast<int>(this->students_list.size()); i++) { std::string iterative_id = this->students_list.at(i).get_student_id(); if (student_id == iterative_id) { return true; } } return false; } */ /** * Removes a student from the list of students associated to the manager, if present * @param student_id The unique student identity number */ /* void Manager::remove_student(std::string student_id) { int index = -1; if (!this->has_student(student_id)) { throw -1; } else { for (int i = 0; i < static_cast<int>(this->students_list.size()); i++) { std::string iterative_id = this->students_list.at(i).get_student_id(); if (iterative_id == student_id) { index = i; break; } } } if (index > -1) { this->students_list.erase(this->students_list.begin() + index); } } */ /** * Returns a summary of the manager, along with the students associated * @return A string containing all the information about the Manager and the name of the student associated * to the Manager, as a list. */ std::string Manager::to_string() { std::string result = "Name: " + this->get_name() + "\n"; result += "Social Insurance Number: " + this->get_social_insurance_number() + "\n"; result += "Employee ID: " + this->get_employee_id() + "\n"; // result += "List of students: \n"; /* if (static_cast<int>(this->students_list.size()) > 0) { for (int i = 0; i < static_cast<int>(this->students_list.size()); i++) { std::string student_name = this->students_list.at(i).get_name(); result += std::to_string(i + 1) + ") " + student_name + "\n"; } } else { result += "No students associated\n"; } */ return result; }
26.576271
107
0.688776
[ "object", "vector" ]
2cbc97788ca2f5c934c6b36c80f96d1bc789d887
3,709
cpp
C++
src/umundo/discovery/BroadcastDiscovery.cpp
tklab-tud/umundo
31da28e24c6c935370099745311dd78c80763bd8
[ "BSD-3-Clause" ]
44
2015-02-01T12:39:51.000Z
2022-03-30T15:13:50.000Z
src/umundo/discovery/BroadcastDiscovery.cpp
tklab-tud/umundo
31da28e24c6c935370099745311dd78c80763bd8
[ "BSD-3-Clause" ]
3
2015-01-13T12:47:21.000Z
2017-06-24T04:13:46.000Z
src/umundo/discovery/BroadcastDiscovery.cpp
tklab-tud/umundo
31da28e24c6c935370099745311dd78c80763bd8
[ "BSD-3-Clause" ]
19
2015-04-17T13:50:15.000Z
2022-03-09T09:50:46.000Z
#include "umundo/discovery/BroadcastDiscovery.h" namespace umundo { /** * Have a look at https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L81 to * see how to setup UDP sockets for broadcast. * * Receiving Broadcast messages: https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L700 * Sending Broadcast messages: https://github.com/zeromq/czmq/blob/master/src/zbeacon.c#L751 */ #if 0 SOCKET BroadcastDiscovery::udpSocket = 0; RMutex BroadcastDiscovery::globalMutex; sockaddr_in BroadcastDiscovery::bCastAddress; char BroadcastDiscovery::hostName[NI_MAXHOST]; #endif BroadcastDiscovery::BroadcastDiscovery() { /** * This is called twice overall, once for the prototype in the factory and * once for the instance that is actually used. */ } BroadcastDiscovery::~BroadcastDiscovery() { } #if 0 void BroadcastDiscovery::setupUDPSocket() { RScopeLock(globalMutex); if (udpSocket == 0) { int enable = 1; udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (udpSocket == INVALID_SOCKET) return; if (setsockopt (udpSocket, SOL_SOCKET, SO_BROADCAST, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) { //error } if (setsockopt (udpSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) { //error } #if defined (SO_REUSEPORT) if (setsockopt (udpSocket, SOL_SOCKET, SO_REUSEPORT, (char*)&enable, sizeof(enable)) == SOCKET_ERROR) { //error } #endif in_addr_t bindTo = INADDR_ANY; in_addr_t sendTo = INADDR_BROADCAST; bCastAddress.sin_family = AF_INET; bCastAddress.sin_port = htons(43005); bCastAddress.sin_addr.s_addr = sendTo; sockaddr_in address = bCastAddress; address.sin_addr.s_addr = bindTo; #if (defined (__WINDOWS__)) sockaddr_in sockaddr = address; #elif (defined (__APPLE__)) sockaddr_in sockaddr = bCastAddress; sockaddr.sin_addr.s_addr = htons (INADDR_ANY); #else sockaddr_in sockaddr = bCastAddress; #endif if (bind (udpSocket, (struct sockaddr *) &sockaddr, sizeof (sockaddr_in))) { // error } getnameinfo ((struct sockaddr *) &address, sizeof (sockaddr_in), hostName, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); } } #endif SharedPtr<BroadcastDiscovery> BroadcastDiscovery::getInstance() { if (_instance.get() == NULL) { // setup UDP socket when th first instance is required //setupUDPSocket(); _instance = SharedPtr<BroadcastDiscovery>(new BroadcastDiscovery()); _instance->start(); } return _instance; } SharedPtr<BroadcastDiscovery> BroadcastDiscovery::_instance; SharedPtr<Implementation> BroadcastDiscovery::create() { return getInstance(); } void BroadcastDiscovery::init(const Options*) { /* * This is where you can setup the non-prototype instance, i.e. not the one * in the factory, but the one created from the prototype. * * The options object is not used and empty. */ } void BroadcastDiscovery::suspend() { } void BroadcastDiscovery::resume() { } void BroadcastDiscovery::advertise(const EndPoint& node) { /** * umundo.core asks you to make the given node discoverable */ } void BroadcastDiscovery::add(Node& node) { } void BroadcastDiscovery::unadvertise(const EndPoint& node) { /** * umundo.core asks you to announce the removal of the given node */ } void BroadcastDiscovery::remove(Node& node) { } void BroadcastDiscovery::browse(ResultSet<ENDPOINT_RS_TYPE>* query) { /** * Another node wants to browse for nodes */ } void BroadcastDiscovery::unbrowse(ResultSet<ENDPOINT_RS_TYPE>* query) { /** * Another node no longer wants to browse for nodes */ } std::vector<EndPoint> BroadcastDiscovery::list() { return std::vector<EndPoint>(); } void BroadcastDiscovery::run() { // your very own thread! } }
24.401316
114
0.728498
[ "object", "vector" ]
2cca34c475f1d52adb286a289b50db7e9efdd4f3
1,151
hpp
C++
include/hitables/plane.hpp
smukherjee2016/ToyRT2018
56b1140d1e796beecc78cc8987771fd9d497a267
[ "Apache-2.0" ]
null
null
null
include/hitables/plane.hpp
smukherjee2016/ToyRT2018
56b1140d1e796beecc78cc8987771fd9d497a267
[ "Apache-2.0" ]
null
null
null
include/hitables/plane.hpp
smukherjee2016/ToyRT2018
56b1140d1e796beecc78cc8987771fd9d497a267
[ "Apache-2.0" ]
null
null
null
#pragma once #include "objects/object.hpp" /* * A plane is defined by a point and a normal. */ class Plane : public Object { public: Point3 distanceFromWorldOrigin; Vector3 normal; Plane(const Point3& _distanceFromWorldOrigin, const Vector3& _normal) : distanceFromWorldOrigin(_distanceFromWorldOrigin), normal(_normal) {} std::optional<HitInfo> checkIntersectionAndClosestHit(const Ray& ray) const override { Vector3 tempNormal = normal; //Invert direction toward ray const Float epsilon = 1e-5; Float denominator = glm::dot(ray.d, tempNormal); Float numerator = glm::dot((distanceFromWorldOrigin - ray.o), tempNormal); if(denominator < epsilon) return std::nullopt; Float tSolution = numerator / denominator; if(tSolution < 0.0 || tSolution < ray.tmin || tSolution > ray.tmax) return std::nullopt; HitInfo hitInfo; hitInfo.tIntersection = numerator / denominator; hitInfo.normal = tempNormal; return {hitInfo}; } //IsEmitter bool isEmitter() const override { return false; } };
25.577778
90
0.655083
[ "object" ]
2cd23d7ce65c29749cd3ba6ad5abc7cf77fc3f7f
800
cpp
C++
test/from_string_test.cpp
roopchansinghv/gadgetron
fb6c56b643911152c27834a754a7b6ee2dd912da
[ "MIT" ]
1
2022-02-22T21:06:36.000Z
2022-02-22T21:06:36.000Z
test/from_string_test.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
test/from_string_test.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
// // Created by dchansen on 2/21/19. // #include <gtest/gtest.h> #include "io/from_string.h" using namespace Gadgetron::Core; TEST(FromStringTest,FloatTest){ ASSERT_EQ(42.0f, IO::from_string<float>("42")); ASSERT_EQ(42.0f, IO::from_string<float>("42.0")); ASSERT_EQ(42.0f, IO::from_string<float>("42.0f")); ASSERT_EQ(42.0f, IO::from_string<float>("42e0")); } TEST(FromStringTest,VectorTest){ std::vector<int> vals = {42,43,44,45}; auto result = IO::from_string<std::vector<int>>("42 43 44 45"); ASSERT_EQ(vals,result); auto result2 = IO::from_string<std::vector<int>>("42, 43, 44, 45"); ASSERT_EQ(vals,result2); } TEST(FromStringTest,BoolTest){ ASSERT_EQ(true, IO::from_string<bool>("true")); ASSERT_EQ(false, IO::from_string<bool>("false")); }
23.529412
71
0.66
[ "vector" ]
2ce3a4c55b0cdaad035fb09160f1373cad1d75fd
33,433
cc
C++
src/xenia/kernel/util/xex2.cc
wtfaremyinitials/xenia
16b3ecd5897051f82bc236ad9a4d0ab5cab22e87
[ "BSD-3-Clause" ]
2
2016-11-18T23:12:36.000Z
2019-02-08T14:43:40.000Z
src/xenia/kernel/util/xex2.cc
wtfaremyinitials/xenia
16b3ecd5897051f82bc236ad9a4d0ab5cab22e87
[ "BSD-3-Clause" ]
null
null
null
src/xenia/kernel/util/xex2.cc
wtfaremyinitials/xenia
16b3ecd5897051f82bc236ad9a4d0ab5cab22e87
[ "BSD-3-Clause" ]
null
null
null
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <xenia/kernel/util/xex2.h> #include <vector> #include <third_party/crypto/rijndael-alg-fst.h> #include <third_party/crypto/rijndael-alg-fst.c> #include <third_party/mspack/lzx.h> #include <third_party/mspack/lzxd.c> #include <third_party/mspack/mspack.h> #include <third_party/pe/pe_image.h> using namespace alloy; typedef struct xe_xex2 { xe_ref_t ref; Memory* memory; xe_xex2_header_t header; std::vector<PESection*>* sections; } xe_xex2_t; int xe_xex2_read_header(const uint8_t *addr, const size_t length, xe_xex2_header_t *header); int xe_xex2_decrypt_key(xe_xex2_header_t *header); int xe_xex2_read_image(xe_xex2_ref xex, const uint8_t *xex_addr, const size_t xex_length, Memory* memory); int xe_xex2_load_pe(xe_xex2_ref xex); xe_xex2_ref xe_xex2_load(Memory* memory, const void* addr, const size_t length, xe_xex2_options_t options) { xe_xex2_ref xex = (xe_xex2_ref)xe_calloc(sizeof(xe_xex2)); xe_ref_init((xe_ref)xex); xex->memory = memory; xex->sections = new std::vector<PESection*>(); XEEXPECTZERO(xe_xex2_read_header((const uint8_t*)addr, length, &xex->header)); XEEXPECTZERO(xe_xex2_decrypt_key(&xex->header)); XEEXPECTZERO(xe_xex2_read_image(xex, (const uint8_t*)addr, length, memory)); XEEXPECTZERO(xe_xex2_load_pe(xex)); return xex; XECLEANUP: xe_xex2_release(xex); return NULL; } void xe_xex2_dealloc(xe_xex2_ref xex) { for (std::vector<PESection*>::iterator it = xex->sections->begin(); it != xex->sections->end(); ++it) { delete *it; } xe_xex2_header_t *header = &xex->header; xe_free(header->sections); if (header->file_format_info.compression_type == XEX_COMPRESSION_BASIC) { xe_free(header->file_format_info.compression_info.basic.blocks); } for (size_t n = 0; n < header->import_library_count; n++) { xe_xex2_import_library_t *library = &header->import_libraries[n]; xe_free(library->records); } xex->memory = NULL; } xe_xex2_ref xe_xex2_retain(xe_xex2_ref xex) { xe_ref_retain((xe_ref)xex); return xex; } void xe_xex2_release(xe_xex2_ref xex) { xe_ref_release((xe_ref)xex, (xe_ref_dealloc_t)xe_xex2_dealloc); } const xechar_t* xe_xex2_get_name(xe_xex2_ref xex) { // TODO(benvanik): get name. return NULL; } const xe_xex2_header_t* xe_xex2_get_header(xe_xex2_ref xex) { return &xex->header; } int xe_xex2_read_header(const uint8_t *addr, const size_t length, xe_xex2_header_t *header) { const uint8_t *p = addr; const uint8_t *pc; const uint8_t *ps; xe_xex2_loader_info_t *ldr; header->xex2 = XEGETUINT32BE(p + 0x00); if (header->xex2 != 0x58455832) { return 1; } header->module_flags = (xe_xex2_module_flags)XEGETUINT32BE(p + 0x04); header->exe_offset = XEGETUINT32BE(p + 0x08); header->unknown0 = XEGETUINT32BE(p + 0x0C); header->certificate_offset = XEGETUINT32BE(p + 0x10); header->header_count = XEGETUINT32BE(p + 0x14); for (size_t n = 0; n < header->header_count; n++) { const uint8_t *ph = p + 0x18 + (n * 8); const uint32_t key = XEGETUINT32BE(ph + 0x00); const uint32_t data_offset = XEGETUINT32BE(ph + 0x04); xe_xex2_opt_header_t *opt_header = &header->headers[n]; opt_header->key = key; switch (key & 0xFF) { case 0x01: // dataOffset = data opt_header->length = 0; opt_header->value = data_offset; break; case 0xFF: // dataOffset = offset (first dword in data is size) opt_header->length = XEGETUINT32BE(p + data_offset); opt_header->offset = data_offset; break; default: // dataOffset = size in dwords opt_header->length = (key & 0xFF) * 4; opt_header->offset = data_offset; break; } const uint8_t *pp = p + opt_header->offset; switch (opt_header->key) { case XEX_HEADER_SYSTEM_FLAGS: header->system_flags = (xe_xex2_system_flags)data_offset; break; case XEX_HEADER_RESOURCE_INFO: { xe_xex2_resource_info_t *res = &header->resource_info; XEEXPECTZERO(xe_copy_memory(res->title_id, sizeof(res->title_id), pp + 0x04, 8)); res->address = XEGETUINT32BE(pp + 0x0C); res->size = XEGETUINT32BE(pp + 0x10); if ((opt_header->length - 4) / 16 > 1) { // Ignoring extra resources (not yet seen) XELOGW("ignoring extra XEX_HEADER_RESOURCE_INFO resources"); } } break; case XEX_HEADER_EXECUTION_INFO: { xe_xex2_execution_info_t *ex = &header->execution_info; ex->media_id = XEGETUINT32BE(pp + 0x00); ex->version.value = XEGETUINT32BE(pp + 0x04); ex->base_version.value = XEGETUINT32BE(pp + 0x08); ex->title_id = XEGETUINT32BE(pp + 0x0C); ex->platform = XEGETUINT8BE(pp + 0x10); ex->executable_table = XEGETUINT8BE(pp + 0x11); ex->disc_number = XEGETUINT8BE(pp + 0x12); ex->disc_count = XEGETUINT8BE(pp + 0x13); ex->savegame_id = XEGETUINT32BE(pp + 0x14); } break; case XEX_HEADER_GAME_RATINGS: { xe_xex2_game_ratings_t *ratings = &header->game_ratings; ratings->esrb = (xe_xex2_rating_esrb_value)XEGETUINT8BE(pp + 0x00); ratings->pegi = (xe_xex2_rating_pegi_value)XEGETUINT8BE(pp + 0x01); ratings->pegifi = (xe_xex2_rating_pegi_fi_value)XEGETUINT8BE(pp + 0x02); ratings->pegipt = (xe_xex2_rating_pegi_pt_value)XEGETUINT8BE(pp + 0x03); ratings->bbfc = (xe_xex2_rating_bbfc_value)XEGETUINT8BE(pp + 0x04); ratings->cero = (xe_xex2_rating_cero_value)XEGETUINT8BE(pp + 0x05); ratings->usk = (xe_xex2_rating_usk_value)XEGETUINT8BE(pp + 0x06); ratings->oflcau = (xe_xex2_rating_oflc_au_value)XEGETUINT8BE(pp + 0x07); ratings->oflcnz = (xe_xex2_rating_oflc_nz_value)XEGETUINT8BE(pp + 0x08); ratings->kmrb = (xe_xex2_rating_kmrb_value)XEGETUINT8BE(pp + 0x09); ratings->brazil = (xe_xex2_rating_brazil_value)XEGETUINT8BE(pp + 0x0A); ratings->fpb = (xe_xex2_rating_fpb_value)XEGETUINT8BE(pp + 0x0B); } break; case XEX_HEADER_TLS_INFO: { xe_xex2_tls_info_t *tls = &header->tls_info; tls->slot_count = XEGETUINT32BE(pp + 0x00); tls->raw_data_address = XEGETUINT32BE(pp + 0x04); tls->data_size = XEGETUINT32BE(pp + 0x08); tls->raw_data_size = XEGETUINT32BE(pp + 0x0C); } break; case XEX_HEADER_IMAGE_BASE_ADDRESS: header->exe_address = opt_header->value; break; case XEX_HEADER_ENTRY_POINT: header->exe_entry_point = opt_header->value; break; case XEX_HEADER_DEFAULT_STACK_SIZE: header->exe_stack_size = opt_header->value; break; case XEX_HEADER_DEFAULT_HEAP_SIZE: header->exe_heap_size = opt_header->value; break; case XEX_HEADER_IMPORT_LIBRARIES: { const size_t max_count = XECOUNT(header->import_libraries); size_t count = XEGETUINT32BE(pp + 0x08); XEASSERT(count <= max_count); if (count > max_count) { XELOGW("ignoring %zu extra entries in XEX_HEADER_IMPORT_LIBRARIES", (max_count - count)); count = max_count; } header->import_library_count = count; uint32_t string_table_size = XEGETUINT32BE(pp + 0x04); const char *string_table = (const char*)(pp + 0x0C); pp += 12 + string_table_size; for (size_t m = 0; m < count; m++) { xe_xex2_import_library_t *library = &header->import_libraries[m]; XEEXPECTZERO(xe_copy_memory(library->digest, sizeof(library->digest), pp + 0x04, 20)); library->import_id = XEGETUINT32BE(pp + 0x18); library->version.value = XEGETUINT32BE(pp + 0x1C); library->min_version.value = XEGETUINT32BE(pp + 0x20); const uint16_t name_index = XEGETUINT16BE(pp + 0x24); for (size_t i = 0, j = 0; i < string_table_size;) { if (j == name_index) { XEIGNORE(xestrcpya(library->name, XECOUNT(library->name), string_table + i)); break; } if (string_table[i] == 0) { i++; if (i % 4) { i += 4 - (i % 4); } j++; } else { i++; } } library->record_count = XEGETUINT16BE(pp + 0x26); library->records = (uint32_t*)xe_calloc( library->record_count * sizeof(uint32_t)); XEEXPECTNOTNULL(library->records); pp += 0x28; for (size_t i = 0; i < library->record_count; i++) { library->records[i] = XEGETUINT32BE(pp); pp += 4; } } } break; case XEX_HEADER_STATIC_LIBRARIES: { const size_t max_count = XECOUNT(header->static_libraries); size_t count = (opt_header->length - 4) / 16; XEASSERT(count <= max_count); if (count > max_count) { XELOGW("ignoring %zu extra entries in XEX_HEADER_STATIC_LIBRARIES", (max_count - count)); count = max_count; } header->static_library_count = count; pp += 4; for (size_t m = 0; m < count; m++) { xe_xex2_static_library_t *library = &header->static_libraries[m]; XEEXPECTZERO(xe_copy_memory(library->name, sizeof(library->name), pp + 0x00, 8)); library->name[8] = 0; library->major = XEGETUINT16BE(pp + 0x08); library->minor = XEGETUINT16BE(pp + 0x0A); library->build = XEGETUINT16BE(pp + 0x0C); uint16_t qfeapproval = XEGETUINT16BE(pp + 0x0E); library->approval = (xe_xex2_approval_type)(qfeapproval & 0x8000); library->qfe = qfeapproval & ~0x8000; pp += 16; } } break; case XEX_HEADER_FILE_FORMAT_INFO: { xe_xex2_file_format_info_t *fmt = &header->file_format_info; fmt->encryption_type = (xe_xex2_encryption_type)XEGETUINT16BE(pp + 0x04); fmt->compression_type = (xe_xex2_compression_type)XEGETUINT16BE(pp + 0x06); switch (fmt->compression_type) { case XEX_COMPRESSION_NONE: // TODO: XEX_COMPRESSION_NONE XEASSERTALWAYS(); break; case XEX_COMPRESSION_BASIC: { xe_xex2_file_basic_compression_info_t *comp_info = &fmt->compression_info.basic; uint32_t info_size = XEGETUINT32BE(pp + 0x00); comp_info->block_count = (info_size - 8) / 8; comp_info->blocks = (xe_xex2_file_basic_compression_block_t*) xe_calloc(comp_info->block_count * sizeof(xe_xex2_file_basic_compression_block_t)); XEEXPECTNOTNULL(comp_info->blocks); for (size_t m = 0; m < comp_info->block_count; m++) { xe_xex2_file_basic_compression_block_t *block = &comp_info->blocks[m]; block->data_size = XEGETUINT32BE(pp + 0x08 + (m * 8)); block->zero_size = XEGETUINT32BE(pp + 0x0C + (m * 8)); } } break; case XEX_COMPRESSION_NORMAL: { xe_xex2_file_normal_compression_info_t *comp_info = &fmt->compression_info.normal; uint32_t window_size = XEGETUINT32BE(pp + 0x08); uint32_t window_bits = 0; for (size_t m = 0; m < 32; m++, window_bits++) { window_size <<= 1; if (window_size == 0x80000000) { break; } } comp_info->window_size = XEGETUINT32BE(pp + 0x08); comp_info->window_bits = window_bits; comp_info->block_size = XEGETUINT32BE(pp + 0x0C); XEEXPECTZERO(xe_copy_memory(comp_info->block_hash, sizeof(comp_info->block_hash), pp + 0x10, 20)); } break; case XEX_COMPRESSION_DELTA: // TODO: XEX_COMPRESSION_DELTA XEASSERTALWAYS(); break; } } break; } } // Loader info. pc = p + header->certificate_offset; ldr = &header->loader_info; ldr->header_size = XEGETUINT32BE(pc + 0x000); ldr->image_size = XEGETUINT32BE(pc + 0x004); XEEXPECTZERO(xe_copy_memory(ldr->rsa_signature, sizeof(ldr->rsa_signature), pc + 0x008, 256)); ldr->unklength = XEGETUINT32BE(pc + 0x108); ldr->image_flags = (xe_xex2_image_flags)XEGETUINT32BE(pc + 0x10C); ldr->load_address = XEGETUINT32BE(pc + 0x110); XEEXPECTZERO(xe_copy_memory(ldr->section_digest, sizeof(ldr->section_digest), pc + 0x114, 20)); ldr->import_table_count = XEGETUINT32BE(pc + 0x128); XEEXPECTZERO(xe_copy_memory(ldr->import_table_digest, sizeof(ldr->import_table_digest), pc + 0x12C, 20)); XEEXPECTZERO(xe_copy_memory(ldr->media_id, sizeof(ldr->media_id), pc + 0x140, 16)); XEEXPECTZERO(xe_copy_memory(ldr->file_key, sizeof(ldr->file_key), pc + 0x150, 16)); ldr->export_table = XEGETUINT32BE(pc + 0x160); XEEXPECTZERO(xe_copy_memory(ldr->header_digest, sizeof(ldr->header_digest), pc + 0x164, 20)); ldr->game_regions = (xe_xex2_region_flags)XEGETUINT32BE(pc + 0x178); ldr->media_flags = (xe_xex2_media_flags)XEGETUINT32BE(pc + 0x17C); // Section info follows loader info. ps = p + header->certificate_offset + 0x180; header->section_count = XEGETUINT32BE(ps + 0x000); ps += 4; header->sections = (xe_xex2_section_t*)xe_calloc( header->section_count * sizeof(xe_xex2_section_t)); XEEXPECTNOTNULL(header->sections); for (size_t n = 0; n < header->section_count; n++) { xe_xex2_section_t *section = &header->sections[n]; section->info.value = XEGETUINT32BE(ps); ps += 4; XEEXPECTZERO(xe_copy_memory(section->digest, sizeof(section->digest), ps, sizeof(section->digest))); ps += sizeof(section->digest); } return 0; XECLEANUP: return 1; } int xe_xex2_decrypt_key(xe_xex2_header_t *header) { const static uint8_t xe_xex2_retail_key[16] = { 0x20, 0xB1, 0x85, 0xA5, 0x9D, 0x28, 0xFD, 0xC3, 0x40, 0x58, 0x3F, 0xBB, 0x08, 0x96, 0xBF, 0x91 }; const static uint8_t xe_xex2_devkit_key[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Guess key based on file info. // TODO: better way to finding out which key to use? const uint8_t *xexkey; if (header->execution_info.title_id) { xexkey = xe_xex2_retail_key; } else { xexkey = xe_xex2_devkit_key; } // Decrypt the header key. uint32_t rk[4 * (MAXNR + 1)]; int32_t Nr = rijndaelKeySetupDec(rk, xexkey, 128); rijndaelDecrypt(rk, Nr, header->loader_info.file_key, header->session_key); return 0; } typedef struct mspack_memory_file_t { struct mspack_system sys; void *buffer; off_t buffer_size; off_t offset; } mspack_memory_file; mspack_memory_file *mspack_memory_open(struct mspack_system *sys, void* buffer, const size_t buffer_size) { XEASSERT(buffer_size < INT_MAX); if (buffer_size >= INT_MAX) { return NULL; } mspack_memory_file *memfile = (mspack_memory_file*)xe_calloc( sizeof(mspack_memory_file)); if (!memfile) { return NULL; } memfile->buffer = buffer; memfile->buffer_size = (off_t)buffer_size; memfile->offset = 0; return memfile; } void mspack_memory_close(mspack_memory_file *file) { mspack_memory_file *memfile = (mspack_memory_file*)file; xe_free(memfile); } int mspack_memory_read(struct mspack_file *file, void *buffer, int chars) { mspack_memory_file *memfile = (mspack_memory_file*)file; const off_t remaining = memfile->buffer_size - memfile->offset; const off_t total = MIN(chars, remaining); if (xe_copy_memory(buffer, total, (uint8_t*)memfile->buffer + memfile->offset, total)) { return -1; } memfile->offset += total; return (int)total; } int mspack_memory_write(struct mspack_file *file, void *buffer, int chars) { mspack_memory_file *memfile = (mspack_memory_file*)file; const off_t remaining = memfile->buffer_size - memfile->offset; const off_t total = MIN(chars, remaining); if (xe_copy_memory((uint8_t*)memfile->buffer + memfile->offset, memfile->buffer_size - memfile->offset, buffer, total)) { return -1; } memfile->offset += total; return (int)total; } void *mspack_memory_alloc(struct mspack_system *sys, size_t chars) { XEUNREFERENCED(sys); return xe_calloc(chars); } void mspack_memory_free(void *ptr) { xe_free(ptr); } void mspack_memory_copy(void *src, void *dest, size_t chars) { xe_copy_memory(dest, chars, src, chars); } struct mspack_system *mspack_memory_sys_create() { struct mspack_system *sys = (struct mspack_system *)xe_calloc( sizeof(struct mspack_system)); if (!sys) { return NULL; } sys->read = mspack_memory_read; sys->write = mspack_memory_write; sys->alloc = mspack_memory_alloc; sys->free = mspack_memory_free; sys->copy = mspack_memory_copy; return sys; } void mspack_memory_sys_destroy(struct mspack_system *sys) { xe_free(sys); } void xe_xex2_decrypt_buffer(const uint8_t *session_key, const uint8_t *input_buffer, const size_t input_size, uint8_t* output_buffer, const size_t output_size) { uint32_t rk[4 * (MAXNR + 1)]; uint8_t ivec[16] = {0}; int32_t Nr = rijndaelKeySetupDec(rk, session_key, 128); const uint8_t *ct = input_buffer; uint8_t* pt = output_buffer; for (size_t n = 0; n < input_size; n += 16, ct += 16, pt += 16) { // Decrypt 16 uint8_ts from input -> output. rijndaelDecrypt(rk, Nr, ct, pt); for (size_t i = 0; i < 16; i++) { // XOR with previous. pt[i] ^= ivec[i]; // Set previous. ivec[i] = ct[i]; } } } int xe_xex2_read_image_uncompressed(const xe_xex2_header_t *header, const uint8_t *xex_addr, const size_t xex_length, Memory* memory) { // Allocate in-place the XEX memory. const size_t exe_length = xex_length - header->exe_offset; size_t uncompressed_size = exe_length; uint32_t alloc_result = (uint32_t)memory->HeapAlloc( header->exe_address, uncompressed_size, MEMORY_FLAG_ZERO); if (!alloc_result) { XELOGE("Unable to allocate XEX memory at %.8X-%.8X.", header->exe_address, uncompressed_size); return 2; } uint8_t *buffer = memory->Translate(header->exe_address); const uint8_t *p = (const uint8_t*)xex_addr + header->exe_offset; switch (header->file_format_info.encryption_type) { case XEX_ENCRYPTION_NONE: return xe_copy_memory(buffer, uncompressed_size, p, exe_length); case XEX_ENCRYPTION_NORMAL: xe_xex2_decrypt_buffer(header->session_key, p, exe_length, buffer, uncompressed_size); return 0; default: XEASSERTALWAYS(); return 1; } return 0; } int xe_xex2_read_image_basic_compressed(const xe_xex2_header_t *header, const uint8_t *xex_addr, const size_t xex_length, Memory* memory) { const size_t exe_length = xex_length - header->exe_offset; const uint8_t* source_buffer = (const uint8_t*)xex_addr + header->exe_offset; const uint8_t *p = source_buffer; // Calculate uncompressed length. size_t uncompressed_size = 0; const xe_xex2_file_basic_compression_info_t* comp_info = &header->file_format_info.compression_info.basic; for (size_t n = 0; n < comp_info->block_count; n++) { const size_t data_size = comp_info->blocks[n].data_size; const size_t zero_size = comp_info->blocks[n].zero_size; uncompressed_size += data_size + zero_size; } // Allocate in-place the XEX memory. uint32_t alloc_result = (uint32_t)memory->HeapAlloc( header->exe_address, uncompressed_size, MEMORY_FLAG_ZERO); if (!alloc_result) { XELOGE("Unable to allocate XEX memory at %.8X-%.8X.", header->exe_address, uncompressed_size); XEFAIL(); } uint8_t *buffer = memory->Translate(header->exe_address); uint8_t *d = buffer; uint32_t rk[4 * (MAXNR + 1)]; uint8_t ivec[16] = {0}; int32_t Nr = rijndaelKeySetupDec(rk, header->session_key, 128); for (size_t n = 0; n < comp_info->block_count; n++) { const size_t data_size = comp_info->blocks[n].data_size; const size_t zero_size = comp_info->blocks[n].zero_size; switch (header->file_format_info.encryption_type) { case XEX_ENCRYPTION_NONE: XEEXPECTZERO(xe_copy_memory(d, uncompressed_size - (d - buffer), p, exe_length - (p - source_buffer))); break; case XEX_ENCRYPTION_NORMAL: { const uint8_t *ct = p; uint8_t* pt = d; for (size_t n = 0; n < data_size; n += 16, ct += 16, pt += 16) { // Decrypt 16 uint8_ts from input -> output. rijndaelDecrypt(rk, Nr, ct, pt); for (size_t i = 0; i < 16; i++) { // XOR with previous. pt[i] ^= ivec[i]; // Set previous. ivec[i] = ct[i]; } } } break; default: XEASSERTALWAYS(); return 1; } p += data_size; d += data_size + zero_size; } return 0; XECLEANUP: return 1; } int xe_xex2_read_image_compressed(const xe_xex2_header_t *header, const uint8_t *xex_addr, const size_t xex_length, Memory* memory) { const size_t exe_length = xex_length - header->exe_offset; const uint8_t *exe_buffer = (const uint8_t*)xex_addr + header->exe_offset; // src -> dest: // - decrypt (if encrypted) // - de-block: // 4b total size of next block in uint8_ts // 20b hash of entire next block (including size/hash) // Nb block uint8_ts // - decompress block contents int result_code = 1; uint8_t *compress_buffer = NULL; const uint8_t *p = NULL; uint8_t *d = NULL; uint8_t *deblock_buffer = NULL; size_t block_size = 0; size_t uncompressed_size = 0; struct mspack_system *sys = NULL; mspack_memory_file *lzxsrc = NULL; mspack_memory_file *lzxdst = NULL; struct lzxd_stream *lzxd = NULL; // Decrypt (if needed). bool free_input = false; const uint8_t *input_buffer = exe_buffer; const size_t input_size = exe_length; switch (header->file_format_info.encryption_type) { case XEX_ENCRYPTION_NONE: // No-op. break; case XEX_ENCRYPTION_NORMAL: // TODO: a way to do without a copy/alloc? free_input = true; input_buffer = (const uint8_t*)xe_calloc(input_size); XEEXPECTNOTNULL(input_buffer); xe_xex2_decrypt_buffer(header->session_key, exe_buffer, exe_length, (uint8_t*)input_buffer, input_size); break; default: XEASSERTALWAYS(); return false; } compress_buffer = (uint8_t*)xe_calloc(exe_length); XEEXPECTNOTNULL(compress_buffer); p = input_buffer; d = compress_buffer; // De-block. deblock_buffer = (uint8_t*)xe_calloc(input_size); XEEXPECTNOTNULL(deblock_buffer); block_size = header->file_format_info.compression_info.normal.block_size; while (block_size) { const uint8_t *pnext = p + block_size; const size_t next_size = XEGETINT32BE(p); p += 4; p += 20; // skip 20b hash while(true) { const size_t chunk_size = (p[0] << 8) | p[1]; p += 2; if (!chunk_size) { break; } xe_copy_memory(d, exe_length - (d - compress_buffer), p, chunk_size); p += chunk_size; d += chunk_size; uncompressed_size += 0x8000; } p = pnext; block_size = next_size; } // Allocate in-place the XEX memory. uint32_t alloc_result = (uint32_t)memory->HeapAlloc( header->exe_address, uncompressed_size, MEMORY_FLAG_ZERO); if (!alloc_result) { XELOGE("Unable to allocate XEX memory at %.8X-%.8X.", header->exe_address, uncompressed_size); result_code = 2; XEFAIL(); } uint8_t *buffer = memory->Translate(header->exe_address); // Setup decompressor and decompress. sys = mspack_memory_sys_create(); XEEXPECTNOTNULL(sys); lzxsrc = mspack_memory_open(sys, (void*)compress_buffer, d - compress_buffer); XEEXPECTNOTNULL(lzxsrc); lzxdst = mspack_memory_open(sys, buffer, uncompressed_size); XEEXPECTNOTNULL(lzxdst); lzxd = lzxd_init( sys, (struct mspack_file *)lzxsrc, (struct mspack_file *)lzxdst, header->file_format_info.compression_info.normal.window_bits, 0, 32768, (off_t)header->loader_info.image_size); XEEXPECTNOTNULL(lzxd); XEEXPECTZERO(lzxd_decompress(lzxd, (off_t)header->loader_info.image_size)); result_code = 0; XECLEANUP: if (lzxd) { lzxd_free(lzxd); lzxd = NULL; } if (lzxsrc) { mspack_memory_close(lzxsrc); lzxsrc = NULL; } if (lzxdst) { mspack_memory_close(lzxdst); lzxdst = NULL; } if (sys) { mspack_memory_sys_destroy(sys); sys = NULL; } xe_free(compress_buffer); xe_free(deblock_buffer); if (free_input) { xe_free((void*)input_buffer); } return result_code; } int xe_xex2_read_image(xe_xex2_ref xex, const uint8_t *xex_addr, const size_t xex_length, Memory* memory) { const xe_xex2_header_t *header = &xex->header; switch (header->file_format_info.compression_type) { case XEX_COMPRESSION_NONE: return xe_xex2_read_image_uncompressed( header, xex_addr, xex_length, memory); case XEX_COMPRESSION_BASIC: return xe_xex2_read_image_basic_compressed( header, xex_addr, xex_length, memory); case XEX_COMPRESSION_NORMAL: return xe_xex2_read_image_compressed( header, xex_addr, xex_length, memory); default: XEASSERTALWAYS(); return 1; } } int xe_xex2_load_pe(xe_xex2_ref xex) { const xe_xex2_header_t* header = &xex->header; const uint8_t* p = xex->memory->Translate(header->exe_address); // Verify DOS signature (MZ). const IMAGE_DOS_HEADER* doshdr = (const IMAGE_DOS_HEADER*)p; if (doshdr->e_magic != IMAGE_DOS_SIGNATURE) { XELOGE("PE signature mismatch; likely bad decryption/decompression"); return 1; } // Move to the NT header offset from the DOS header. p += doshdr->e_lfanew; // Verify NT signature (PE\0\0). const IMAGE_NT_HEADERS32* nthdr = (const IMAGE_NT_HEADERS32*)(p); if (nthdr->Signature != IMAGE_NT_SIGNATURE) { return 1; } // Verify matches an Xbox PE. const IMAGE_FILE_HEADER* filehdr = &nthdr->FileHeader; if ((filehdr->Machine != IMAGE_FILE_MACHINE_POWERPCBE) || !(filehdr->Characteristics & IMAGE_FILE_32BIT_MACHINE)) { return 1; } // Verify the expected size. if (filehdr->SizeOfOptionalHeader != IMAGE_SIZEOF_NT_OPTIONAL_HEADER) { return 1; } // Verify optional header is 32bit. const IMAGE_OPTIONAL_HEADER32* opthdr = &nthdr->OptionalHeader; if (opthdr->Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) { return 1; } // Verify subsystem. if (opthdr->Subsystem != IMAGE_SUBSYSTEM_XBOX) { return 1; } // Linker version - likely 8+ // Could be useful for recognizing certain patterns //opthdr->MajorLinkerVersion; opthdr->MinorLinkerVersion; // Data directories of interest: // EXPORT IMAGE_EXPORT_DIRECTORY // IMPORT IMAGE_IMPORT_DESCRIPTOR[] // EXCEPTION IMAGE_CE_RUNTIME_FUNCTION_ENTRY[] // BASERELOC // DEBUG IMAGE_DEBUG_DIRECTORY[] // ARCHITECTURE /IMAGE_ARCHITECTURE_HEADER/ ----- import thunks! // TLS IMAGE_TLS_DIRECTORY // IAT Import Address Table ptr //opthdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_X].VirtualAddress / .Size // Quick scan to determine bounds of sections. size_t upper_address = 0; const IMAGE_SECTION_HEADER* sechdr = IMAGE_FIRST_SECTION(nthdr); for (size_t n = 0; n < filehdr->NumberOfSections; n++, sechdr++) { const size_t physical_address = opthdr->ImageBase + sechdr->VirtualAddress; upper_address = MAX(upper_address, physical_address + sechdr->Misc.VirtualSize); } // Setup/load sections. sechdr = IMAGE_FIRST_SECTION(nthdr); for (size_t n = 0; n < filehdr->NumberOfSections; n++, sechdr++) { PESection* section = (PESection*)xe_calloc(sizeof(PESection)); xe_copy_memory(section->name, sizeof(section->name), sechdr->Name, sizeof(sechdr->Name)); section->name[8] = 0; section->raw_address = sechdr->PointerToRawData; section->raw_size = sechdr->SizeOfRawData; section->address = header->exe_address + sechdr->VirtualAddress; section->size = sechdr->Misc.VirtualSize; section->flags = sechdr->Characteristics; xex->sections->push_back(section); } //DumpTLSDirectory(pImageBase, pNTHeader, (PIMAGE_TLS_DIRECTORY32)0); //DumpExportsSection(pImageBase, pNTHeader); return 0; } const PESection* xe_xex2_get_pe_section(xe_xex2_ref xex, const char* name) { for (std::vector<PESection*>::iterator it = xex->sections->begin(); it != xex->sections->end(); ++it) { if (!xestrcmpa((*it)->name, name)) { return *it; } } return NULL; } int xe_xex2_get_import_infos(xe_xex2_ref xex, const xe_xex2_import_library_t *library, xe_xex2_import_info_t **out_import_infos, size_t *out_import_info_count) { uint8_t *mem = xex->memory->membase(); const xe_xex2_header_t *header = xe_xex2_get_header(xex); // Find library index for verification. size_t library_index = -1; for (size_t n = 0; n < header->import_library_count; n++) { if (&header->import_libraries[n] == library) { library_index = n; break; } } XEASSERT(library_index != (size_t)-1); // Records: // The number of records does not correspond to the number of imports! // Each record points at either a location in text or data - dereferencing the // pointer will yield a value that & 0xFFFF = the import ordinal, // >> 16 & 0xFF = import library index, and >> 24 & 0xFF = 0 if a variable // (just get address) or 1 if a thunk (needs rewrite). // Calculate real count. size_t info_count = 0; for (size_t n = 0; n < library->record_count; n++) { const uint32_t record = library->records[n]; const uint32_t value = XEGETUINT32BE(mem + record); if (value & 0xFF000000) { // Thunk for previous record - ignore. } else { // Variable/thunk. info_count++; } } // Allocate storage. xe_xex2_import_info_t *infos = (xe_xex2_import_info_t*)xe_calloc( info_count * sizeof(xe_xex2_import_info_t)); XEEXPECTNOTNULL(infos); XEASSERTNOTZERO(info_count); // Construct infos. for (size_t n = 0, i = 0; n < library->record_count; n++) { const uint32_t record = library->records[n]; const uint32_t value = XEGETUINT32BE(mem + record); const uint32_t type = (value & 0xFF000000) >> 24; // Verify library index matches given library. //XEASSERT(library_index == ((value >> 16) & 0xFF)); switch (type) { case 0x00: { xe_xex2_import_info_t* info = &infos[i++]; info->ordinal = value & 0xFFFF; info->value_address = record; } break; case 0x01: { // Thunk for previous record. XEASSERT(i > 0); xe_xex2_import_info_t* info = &infos[i - 1]; XEASSERT(info->ordinal == (value & 0xFFFF)); info->thunk_address = record; } break; default: //XEASSERTALWAYS(); break; } } *out_import_info_count = info_count; *out_import_infos = infos; return 0; XECLEANUP: xe_free(infos); *out_import_info_count = 0; *out_import_infos = NULL; return 1; }
34.185072
80
0.621512
[ "vector" ]
2ce69aa4094600941d87d75a72889a1cf2bbbe86
2,783
cpp
C++
src/VariableValue.cpp
robertsmeets/rjhg-pl
87721b77f92d5180c34123265fac70dcf54c77a9
[ "MIT" ]
1
2015-03-19T15:38:20.000Z
2015-03-19T15:38:20.000Z
src/VariableValue.cpp
robertsmeets/rjhg-pl
87721b77f92d5180c34123265fac70dcf54c77a9
[ "MIT" ]
7
2016-04-08T05:32:53.000Z
2019-03-05T05:26:10.000Z
src/VariableValue.cpp
robertsmeets/rjhg-pl
87721b77f92d5180c34123265fac70dcf54c77a9
[ "MIT" ]
1
2015-04-13T14:23:50.000Z
2015-04-13T14:23:50.000Z
/* * VariableValue.cpp * * Created on: Jul 1, 2015 * Author: Robert */ #include "VariableValue.h" VariableValue::VariableValue(string c) { value = c; } VariableValue::~VariableValue() { } void VariableValue::print(int level) { for (int i = 0; i < level; i++) { printf("+"); } printf("VariableValue <%s>\n",value.c_str()); } void VariableValue::emit(CodeGenerator* cg, ProcedureNode* pn) { map<string, uint16_t>* local_variables; map<string, uint16_t>::iterator foundIter; vector<string>* parameters; vector<string>::iterator it2; // // now we have to look up the variable name. // Can be either a local variable, a parameter name, an instance variable or // a global variable // local_variables = pn->getLocalVariables(); foundIter = local_variables->find(value); if (foundIter == local_variables->end()) { parameters = pn->getParameters(); for (it2 = parameters->begin(); it2 != parameters->end(); ++it2) { if ((*it2) == value) { uint16_t number = it2 - parameters->begin(); // // it is a parameter // cg->emit(OPCODE_LOD, 0, number, NULL); // LOD break; } } if (it2 == parameters->end()) { // // look for instance variable // uint16_t j = pn->getInstanceVarNum(value); if (j == 0xffff) { // // check for global variable // vector<string> globals = cg->getProgramNode()->getGlobalVariables(); it2 = find(globals.begin(), globals.end(), value); if (it2 == globals.end()) { // // not found. error // printf("Variable not found <%s>\n",value.c_str()); exit(-1); } else { // // global was found. Emit LDG // uint16_t number = it2 - globals.begin() + 1; cg -> emit(OPCODE_LDG, number, 0, NULL); } } else { cg->emit(OPCODE_LDI, j, pn->getParameters()->size(), NULL); // LDI return; } } } else { // // it is a local variable // int sz1 = pn->getParameters()->size(); int av = local_variables->at(value); // add the parameters plus one for self int offset = sz1 + av; if (pn->getClassDefinition() != NULL) { offset++; } cg->emit(OPCODE_LOD, 0, offset, NULL); // LOD } } string VariableValue::stype() { return "VariableValue"; } string VariableValue::getName() { return value; } void VariableValue::setTopLevel() {}
25.53211
80
0.508444
[ "vector" ]
2ce9649b14a158ac107222af455996838d2f56a6
2,968
cpp
C++
test/unit_tests/UnitTestSearch.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
3
2017-08-08T21:06:02.000Z
2020-01-08T13:23:36.000Z
test/unit_tests/UnitTestSearch.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2016-12-17T00:18:56.000Z
2019-08-09T15:29:25.000Z
test/unit_tests/UnitTestSearch.cpp
jrood-nrel/percept
363cdd0050443760d54162f140b2fb54ed9decf0
[ "BSD-2-Clause" ]
2
2017-11-30T07:02:41.000Z
2019-08-05T17:07:04.000Z
// Copyright 2002 - 2008, 2010, 2011 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. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <stk_search/CoarseSearch.hpp> #include <stk_search/BoundingBox.hpp> #include <stk_util/util/Writer.hpp> #include <stk_util/diag/WriterExt.hpp> #include <gtest/gtest.h> #include <stk_search/CoarseSearch.hpp> #include <iostream> using namespace stk::diag; static const int box_count = 100; namespace percept { namespace unit_tests { /// PLATFORM_NOTE gcc4.3 /// If DIM here is set to 2, the code failes to compile due to dependence of Oct tree code on assuming Dim = 3 in bounding boxes #define DIM 3 #ifndef REDS TEST(search, test1) { typedef stk::search::IdentProc<uint64_t,unsigned> IdentProc; typedef stk::search::Point<float> Point; typedef stk::search::Box<float> Box; typedef std::pair<Point,IdentProc> BoundingPoint; typedef std::pair<Box,IdentProc> BoundingBox; typedef std::vector<std::pair<IdentProc, IdentProc> > IdentProcRelation; stk::ParallelMachine comm = MPI_COMM_WORLD; //stk::diag::WriterThrowSafe _write_throw_safe(dw()); //!dw().m(LOG_SEARCH) << "Use case 1" << stk::diag::push << stk::diag::dendl; int parallel_rank = stk::parallel_machine_rank(comm); // int parallel_size = stk::parallel_machine_size(comm); std::vector<BoundingBox> domain_vector; Point min_corner, max_corner; for (int i = parallel_rank*box_count; i < (parallel_rank + 1)*box_count; ++i) { min_corner[0] = i; min_corner[1] = 0; min_corner[2] = 0; max_corner[0] = i+1; max_corner[1] = 1; max_corner[2] = 1; BoundingBox domain; domain.second.set_id(i); domain.first = Box(min_corner,max_corner); domain_vector.push_back(domain); } std::vector<BoundingPoint> range_vector; Point center; for (int i = parallel_rank*box_count; i < (parallel_rank + 1)*box_count; ++i) { center[0] = i+0.5f; center[1] = 0.5f; center[2] = 0.5f; BoundingPoint p; p.second.set_id(i); p.first = center; range_vector.push_back(p); } //dw().m(LOG_SEARCH) << "range " << range_vector << dendl; //dw().m(LOG_SEARCH) << "domain " << domain_vector << dendl; //dw().m(LOG_SEARCH) << "Search algorithm " << order.m_algorithm << dendl; IdentProcRelation relation; stk::search::coarse_search(range_vector, domain_vector, stk::search::BOOST_RTREE, comm, relation); if (0) { //for (unsigned i = 0; i < relation.size(); i++) for (unsigned i = 0; i < 10; i++) { std::cout << "relation[ " << i << "]= {" << relation[i].first << "} --> { " << relation[i].second << "}" << std::endl; } } //dw().m(LOG_SEARCH) << "relation " << relation << dendl; //dw().m(LOG_SEARCH) << stk::diag::pop; } #endif } }
27.481481
128
0.667116
[ "vector" ]
f8e9613c174a0f93a29da2154c8aba08d457366b
785
cpp
C++
tests/std/tests/Dev09_152755_tr1_nested_bind/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
8,232
2019-09-16T22:51:24.000Z
2022-03-31T03:55:39.000Z
tests/std/tests/Dev09_152755_tr1_nested_bind/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
2,263
2019-09-17T05:19:55.000Z
2022-03-31T21:05:47.000Z
tests/std/tests/Dev09_152755_tr1_nested_bind/test.cpp
isra-fel/STL
6ae9a578b4f52193dc523922c943a2214a873577
[ "Apache-2.0" ]
1,276
2019-09-16T22:51:40.000Z
2022-03-31T03:30:05.000Z
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <algorithm> #include <assert.h> #include <functional> #include <math.h> #include <vector> using namespace std; using namespace std::placeholders; #define STATIC_ASSERT(...) static_assert(__VA_ARGS__, #__VA_ARGS__) class point { public: point(double x, double y) : m_x(x), m_y(y) {} double mag() const { return sqrt(m_x * m_x + m_y * m_y); } private: double m_x; double m_y; }; int main() { vector<point> v; v.push_back(point(3, 4)); v.push_back(point(5, 12)); v.push_back(point(8, 15)); assert(count_if(v.begin(), v.end(), bind(greater<double>(), bind(&point::mag, _1), 10)) == 2); }
21.216216
99
0.614013
[ "vector" ]
f8fb998277aa09ff08769146443f783c17910178
1,291
cpp
C++
BinarySearchTree/bfsTraversal.cpp
rt1599/algorithms
4bce9649875af5d1a99ca2365a76cf07021be4d4
[ "MIT" ]
472
2018-05-25T06:45:44.000Z
2020-01-06T15:46:09.000Z
BinarySearchTree/bfsTraversal.cpp
rt1599/algorithms
4bce9649875af5d1a99ca2365a76cf07021be4d4
[ "MIT" ]
6
2020-01-25T22:22:44.000Z
2021-06-01T04:53:25.000Z
BinarySearchTree/bfsTraversal.cpp
rt1599/algorithms
4bce9649875af5d1a99ca2365a76cf07021be4d4
[ "MIT" ]
44
2019-03-02T07:38:38.000Z
2020-01-01T16:05:06.000Z
/** * LevelOrder traversal of a tree is breadth first traversal for the tree * * Example: * * F * / \ * B G * / \ \ * A D I * * Level Order Traversal := F -> B -> G -> A -> D -> I */ #include <iostream> #include <queue> #include "BST/BST.hpp" void levelOrder(const BST& tree, std::vector<int>& output); /* Main Operational Function */ int main() { BST tree; int original[] = { 9, 5, 3, 10, 6, 1, 7, 4 }; for (int i : original) tree.insert(i); std::vector<int> output; levelOrder(tree, output); for (int o : output) std::cout << o << " "; std::cout << "\n"; return 0; } /** * Breadth First Traversal (Level Order Traversal) * @param tree bst tree object * @param output output of level order traversal is stored in vector */ void levelOrder(const BST& tree, std::vector<int>& output) { Node* root = tree.getRoot(); if (root == nullptr) return; std::queue<Node*> q; q.push(root); while(!q.empty()) { Node* node = q.front(); output.push_back(node->data); if (node->left != nullptr) { q.push(node->left); } if (node->right != nullptr) { q.push(node->right); } q.pop(); } }
20.822581
73
0.522851
[ "object", "vector" ]
f8fed1a174b04e43971e641f365a930cf5131f2f
702
cpp
C++
cf/shua/743D.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
2
2021-06-09T12:27:07.000Z
2021-06-11T12:02:03.000Z
cf/shua/743D.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
1
2021-09-08T12:00:05.000Z
2021-09-08T14:52:30.000Z
cf/shua/743D.cpp
tusikalanse/acm-icpc
20150f42752b85e286d812e716bb32ae1fa3db70
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 10; long long dp[N], sz[N], ans = -1e18; int n, a[N], x, y; vector<int> G[N]; void dfs(int rt, int fa) { sz[rt] = a[rt]; for(auto j : G[rt]) { if(j == fa) continue; dfs(j, rt); if(dp[rt] != -1e18) ans = max(ans, dp[rt] + dp[j]); dp[rt] = max(dp[rt], dp[j]); sz[rt] += sz[j]; } dp[rt] = max(dp[rt], sz[rt]); } int main() { scanf("%d", &n); for(int i = 1; i <= n; ++i) { scanf("%d", &a[i]); dp[i] = -1e18; } for(int i = 1; i < n; ++i) { scanf("%d%d", &x, &y); G[x].push_back(y); G[y].push_back(x); } dfs(1, 0); if(ans == -1e18) { puts("Impossible"); } else printf("%lld\n", ans); return 0; }
16.325581
36
0.482906
[ "vector" ]
5d12381ae4e872fac4c9ee5a07ae424e03f3653b
610
cpp
C++
codeforces/520/B.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
5
2020-06-30T12:44:25.000Z
2021-07-14T06:35:57.000Z
codeforces/520/B.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
null
null
null
codeforces/520/B.cpp
amitdu6ey/Online-Judge-Submissions
9585aec29228211454bca5cf1d5738f49fb0aa8f
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define ll long long using namespace std; map<ll,ll> d; vector<ll> adj; map<ll,bool> v; void bfs(ll n, ll m){ queue<ll> q; q.push(n); d[n]=0; while(!q.empty()){ ll s = q.front(); q.pop(); v[s]=true; if(2*s <= 2*m && !v[2*s]) adj.push_back(2*s); if(s-1 > 0 && !v[s-1]) adj.push_back(s-1); for(int u : adj){ if(v[u]) continue; d[u]=d[s]+1; v[u]=true; q.push(u); if(u==m){ return; } } adj.clear(); } } int main(){ ll n,m; cin>>n>>m; bfs(n,m); /*for(auto u : d){ cout<<u.first<<" "<<u.second<<"\n"; }*/ cout<<d[m]; return 0; }
14.878049
47
0.493443
[ "vector" ]
5d1e11094945b4c453a59df2f950acbd5c0680b3
15,048
cc
C++
examples/prolonged_ncs/tworobots/scots-files/tworobots.cc
mkhaled87/SENSE
a0f5ce28fc03181d66f0751a1849cc39a88e7cd7
[ "BSD-3-Clause" ]
2
2019-10-10T21:39:43.000Z
2020-12-21T20:34:12.000Z
examples/prolonged_ncs/tworobots/scots-files/tworobots.cc
mkhaled87/SENSE
a0f5ce28fc03181d66f0751a1849cc39a88e7cd7
[ "BSD-3-Clause" ]
null
null
null
examples/prolonged_ncs/tworobots/scots-files/tworobots.cc
mkhaled87/SENSE
a0f5ce28fc03181d66f0751a1849cc39a88e7cd7
[ "BSD-3-Clause" ]
null
null
null
/* * robot.cc * * created on: 11.01.2017 * author: M. Khaled */ /* * information about this example is given in the readme file * */ #include <array> #include <iostream> #include "cuddObj.hh" #include "SymbolicSet.hh" #include "SymbolicModelGrowthBound.hh" #include "TicToc.hh" #include "RungeKutta4.hh" #include "FixedPoint.hh" /* state space dim */ #define sDIM 4 #define iDIM 4 /* data types for the ode solver */ typedef std::array<double,sDIM> state_type; typedef std::array<double,iDIM> input_type; /* sampling time */ const double tau = 1; /* number of intermediate steps in the ode solver */ const int nint=5; OdeSolver ode_solver(sDIM,nint,tau); /* we integrate the robot ode by 0.3 sec (the result is stored in x) */ auto robot_post = [](state_type &x, input_type &u) -> void { /* the ode describing the robot */ auto rhs =[](state_type& xx, const state_type &x, input_type &u) -> void { xx[0] = (x[0]*0) + u[0]; xx[1] = (x[1]*0) + u[1]; xx[2] = (x[2]*0) + u[2]; xx[3] = (x[3]*0) + u[3]; }; ode_solver(rhs,x,u); }; /* computation of the growth bound (the result is stored in r) */ auto radius_post = [](state_type &r, input_type &u) -> void { r[0] = u[0]*0; r[1] = u[1]*0; r[2] = u[2]*0; r[3] = u[3]*0; }; /* State Space Params */ #define ARENA_WIDTH 16 #define ARENA_HIGHT 16 #define SS_X1_LB 0 #define SS_X2_LB 0 #define SS_X3_LB SS_X1_LB #define SS_X4_LB SS_X2_LB #define SS_X1_UB (ARENA_WIDTH-1) #define SS_X2_UB (ARENA_HIGHT-1) #define SS_X3_UB SS_X1_UB #define SS_X4_UB SS_X2_UB #define SS_X1_MU 1 #define SS_X2_MU 1 #define SS_X3_MU SS_X1_MU #define SS_X4_MU SS_X2_MU /* Input Space Params */ #define IS_U1_LB -1 #define IS_U2_LB -1 #define IS_U3_LB -1 #define IS_U4_LB -1 #define IS_U1_UB 1 #define IS_U2_UB 1 #define IS_U3_UB 1 #define IS_U4_UB 1 #define IS_U1_MU 1 #define IS_U2_MU 1 #define IS_U3_MU 1 #define IS_U4_MU 1 /* Target Set Params*/ #define T_CUBE_WIDTH 1 #define T_MARGIN 2 #define T1_X1_LB (SS_X1_LB+T_MARGIN) #define T1_X2_LB (SS_X2_LB+T_MARGIN) #define T1_X1_UB (T1_X1_LB+T_CUBE_WIDTH) #define T1_X2_UB (T1_X2_LB+T_CUBE_WIDTH) #define T2_X1_LB (SS_X1_UB-T_MARGIN-T_CUBE_WIDTH) #define T2_X2_LB (SS_X2_UB-T_MARGIN-T_CUBE_WIDTH) #define T2_X1_UB (T2_X1_LB+T_CUBE_WIDTH) #define T2_X2_UB (T2_X2_LB+T_CUBE_WIDTH) #define T3_X3_LB (SS_X3_LB+T_MARGIN) #define T3_X4_LB (SS_X4_UB-T_MARGIN-T_CUBE_WIDTH) #define T3_X3_UB (T3_X3_LB+T_CUBE_WIDTH) #define T3_X4_UB (T3_X4_LB+T_CUBE_WIDTH) #define T4_X3_LB (SS_X3_UB-T_MARGIN-T_CUBE_WIDTH) #define T4_X4_LB (SS_X4_LB+T_MARGIN) #define T4_X3_UB (T4_X3_LB+T_CUBE_WIDTH) #define T4_X4_UB (T4_X4_LB+T_CUBE_WIDTH) /* Target Set Params*/ // Center box #define O1_BOX_W 3 #define O1_X1_LB ((SS_X1_UB/2) - O1_BOX_W + 2) #define O1_X2_LB ((SS_X2_UB/2) - O1_BOX_W + 2) #define O1_X1_UB (O1_X1_LB + O1_BOX_W) #define O1_X2_UB (O1_X2_LB + O1_BOX_W) // Right Rectangle #define O2_REC_W 3 #define O2_REC_H 1 #define O2_X1_LB (SS_X1_UB - O2_REC_W - 1) #define O2_X2_LB ((SS_X2_UB/2) - O2_REC_H + 1) #define O2_X1_UB (O2_X1_LB + O2_REC_W) #define O2_X2_UB (O2_X2_LB + O2_REC_H) // Left Rectangle #define O3_REC_W 3 #define O3_REC_H 1 #define O3_X1_LB (SS_X1_LB + 1) #define O3_X2_LB ((SS_X2_UB/2) - O3_REC_H + 1) #define O3_X1_UB (O3_X1_LB + O3_REC_W) #define O3_X2_UB (O3_X2_LB + O3_REC_H) // Bottom Rectangle #define O4_REC_W 1 #define O4_REC_H 3 #define O4_X1_LB ((SS_X1_UB/2) - O4_REC_W + 1) #define O4_X2_LB (SS_X2_LB + 1) #define O4_X1_UB (O4_X1_LB + O4_REC_W) #define O4_X2_UB (O4_X2_LB + O4_REC_H) // Top Rectangle #define O5_REC_W 1 #define O5_REC_H 3 #define O5_X1_LB ((SS_X1_UB/2) - O5_REC_W + 1) #define O5_X2_LB (SS_X2_UB - O5_REC_H - 1) #define O5_X1_UB (O5_X1_LB + O5_REC_W) #define O5_X2_UB (O5_X2_LB + O5_REC_H) /* construct state space */ scots::SymbolicSet robotCreateStateSpace(Cudd &mgr) { /* setup the workspace of the synthesis problem and the uniform grid */ /* lower bounds of the hyper rectangle */ double lb[sDIM] = {SS_X1_LB,SS_X2_LB,SS_X3_LB,SS_X4_LB}; /* upper bounds of the hyper rectangle */ double ub[sDIM] = {SS_X1_UB,SS_X2_UB,SS_X3_UB,SS_X4_UB}; /* grid node distance diameter */ double mu[sDIM] = {SS_X1_MU,SS_X2_MU,SS_X3_MU,SS_X4_MU}; /* eta is added to the bound so as to ensure that the whole * [0,10]x[0,10]x[-pi-eta,pi+eta] is covered by the cells */ scots::SymbolicSet ss(mgr,sDIM,lb,ub,mu); /* add the grid points to the SymbolicSet ss */ ss.addGridPoints(); double HC[8*sDIM]={-1, 0, 0, 0, 1, 0, 0, 0, 0,-1, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 1}; /* Constrain: two robots should not exist at same position !*/ double nu1=SS_X1_MU*0.1; double nu2=SS_X2_MU*0.1; for(double i=SS_X1_LB; i<=SS_X1_UB; i+=SS_X1_MU){ for(double j=SS_X2_LB; j<=SS_X2_UB; j+=SS_X2_MU){ double h[8] = {-((i)-nu1), (i)+nu1,-((j)-nu2), (j)+nu2, -((i)-nu1), (i)+nu1,-((j)-nu2), (j)+nu2}; ss.remPolytope(8,HC,h, scots::OUTER); } } /* obstacles in the state space */ scots::SymbolicSet ss_obst = ss; // Center Box: double h11[8] = {-O1_X1_LB, O1_X1_UB, -O1_X2_LB, O1_X2_UB, -SS_X3_LB, SS_X3_UB, -SS_X4_LB, SS_X4_UB}; double h12[8] = {-SS_X1_LB, SS_X1_UB, -SS_X2_LB, SS_X2_UB, -O1_X1_LB, O1_X1_UB, -O1_X2_LB, O1_X2_UB}; ss.remPolytope(8,HC,h11, scots::OUTER); ss.remPolytope(8,HC,h12, scots::OUTER); ss_obst.addPolytope(8,HC,h11, scots::OUTER); // Right Rectangle: double h21[8] = {-O2_X1_LB, O2_X1_UB, -O2_X2_LB, O2_X2_UB, -SS_X3_LB, SS_X3_UB, -SS_X4_LB, SS_X4_UB}; double h22[8] = {-SS_X1_LB, SS_X1_UB, -SS_X2_LB, SS_X2_UB, -O2_X1_LB, O2_X1_UB, -O2_X2_LB, O2_X2_UB}; ss.remPolytope(8,HC,h21, scots::OUTER); ss.remPolytope(8,HC,h22, scots::OUTER); ss_obst.addPolytope(8,HC,h21, scots::OUTER); // Left Rectangle: double h31[8] = {-O3_X1_LB, O3_X1_UB, -O3_X2_LB, O3_X2_UB, -SS_X3_LB, SS_X3_UB, -SS_X4_LB, SS_X4_UB}; double h32[8] = {-SS_X1_LB, SS_X1_UB, -SS_X2_LB, SS_X2_UB, -O3_X1_LB, O3_X1_UB, -O3_X2_LB, O3_X2_UB}; ss.remPolytope(8,HC,h31, scots::OUTER); ss.remPolytope(8,HC,h32, scots::OUTER); ss_obst.addPolytope(8,HC,h31, scots::OUTER); // Bottom Rectangle: double h41[8] = {-O4_X1_LB, O4_X1_UB, -O4_X2_LB, O4_X2_UB, -SS_X3_LB, SS_X3_UB, -SS_X4_LB, SS_X4_UB}; double h42[8] = {-SS_X1_LB, SS_X1_UB, -SS_X2_LB, SS_X2_UB, -O4_X1_LB, O4_X1_UB, -O4_X2_LB, O4_X2_UB}; ss.remPolytope(8,HC,h41, scots::OUTER); ss.remPolytope(8,HC,h42, scots::OUTER); ss_obst.addPolytope(8,HC,h41, scots::OUTER); // Top Rectangle: double h51[8] = {-O5_X1_LB, O5_X1_UB, -O5_X2_LB, O5_X2_UB, -SS_X3_LB, SS_X3_UB, -SS_X4_LB, SS_X4_UB}; double h52[8] = {-SS_X1_LB, SS_X1_UB, -SS_X2_LB, SS_X2_UB, -O5_X1_LB, O5_X1_UB, -O5_X2_LB, O5_X2_UB}; ss.remPolytope(8,HC,h51, scots::OUTER); ss.remPolytope(8,HC,h52, scots::OUTER); ss_obst.addPolytope(8,HC,h51, scots::OUTER); ss_obst.writeToFile("tworobots_obst_matlab.bdd"); return ss; } /* construct input space */ scots::SymbolicSet robotCreateInputSpace(Cudd &mgr) { /* lower bounds of the hyper rectangle */ double lb[sDIM] = {IS_U1_LB,IS_U2_LB,IS_U3_LB,IS_U4_LB}; /* upper bounds of the hyper rectangle */ double ub[sDIM] = {IS_U1_UB,IS_U2_UB,IS_U3_UB,IS_U4_UB}; /* grid node distance diameter */ double mu[sDIM] = {IS_U1_MU,IS_U2_MU,IS_U3_MU,IS_U4_MU}; scots::SymbolicSet is(mgr,iDIM,lb,ub,mu); is.addGridPoints(); return is; } int main() { TicToc tt; Cudd mgr; /****************************************************************************/ /* construct SymbolicSet for the state space */ /****************************************************************************/ scots::SymbolicSet ss=robotCreateStateSpace(mgr); ss.writeToFile("tworobots_ss.bdd"); /* write SymbolicSet of obstacles to robot_obst.bdd */ ss.complement(); ss.writeToFile("tworobots_obst.bdd"); ss.complement(); std::cout << "Unfiorm grid details:" << std::endl; ss.printInfo(1); /****************************************************************************/ /* we define the target set */ /****************************************************************************/ /* first make a copy of the state space so that we obtain the grid * information in the new symbolic set */ scots::SymbolicSet ts = ss; scots::SymbolicSet ts1 = ss; scots::SymbolicSet ts2 = ss; scots::SymbolicSet ts3 = ss; scots::SymbolicSet ts4 = ss; scots::SymbolicSet ts13 = ss; scots::SymbolicSet ts14 = ss; scots::SymbolicSet ts23 = ss; scots::SymbolicSet ts24 = ss; /* define the target set as a symbolic set */ double HC[8*sDIM]={-1, 0, 0, 0, 1, 0, 0, 0, 0,-1, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 1}; /* compute inner approximation of P={ x | H x<= h1 } */ double h1[8] = {-T1_X1_LB, T1_X1_UB, -T1_X2_LB, T1_X2_UB, -SS_X3_LB, SS_X3_UB, -SS_X4_LB, SS_X4_UB}; ts1.addPolytope(8,HC,h1, scots::OUTER); ts.addPolytope(8,HC,h1, scots::OUTER); double h2[8] = {-T2_X1_LB, T2_X1_UB, -T2_X2_LB, T2_X2_UB, -SS_X3_LB, SS_X3_UB, -SS_X4_LB, SS_X4_UB}; ts2.addPolytope(8,HC,h2, scots::OUTER); ts.addPolytope(8,HC,h2, scots::OUTER); double h3[8] = {-SS_X1_LB, SS_X1_UB, -SS_X2_LB, SS_X2_UB, -T3_X3_LB, T3_X3_UB, -T3_X4_LB, T3_X4_UB}; ts3.addPolytope(8,HC,h3, scots::OUTER); ts.addPolytope(8,HC,h3, scots::OUTER); std::cout << "h= " << -1*h3[0] << " , " << h3[1] << " , " << -1*h3[2] << " , " << h3[3] << " , "; std::cout << -1*h3[4] << " , " << h3[5] << " , " << -1*h3[6] << " , " << h3[7] << std::endl; double h4[8] = {-SS_X1_LB, SS_X1_UB, -SS_X2_LB, SS_X2_UB, -T4_X3_LB, T4_X3_UB, -T4_X4_LB, T4_X4_UB}; ts4.addPolytope(8,HC,h4, scots::OUTER); ts.addPolytope(8,HC,h4, scots::OUTER); ts1.writeToFile("tworobots_ts1.bdd"); ts2.writeToFile("tworobots_ts2.bdd"); ts3.writeToFile("tworobots_ts3.bdd"); ts4.writeToFile("tworobots_ts4.bdd"); ts.writeToFile("tworobots_ts.bdd"); ts13.setSymbolicSet(ts1.getSymbolicSet() & ts3.getSymbolicSet()); ts14.setSymbolicSet(ts1.getSymbolicSet() & ts4.getSymbolicSet()); ts23.setSymbolicSet(ts2.getSymbolicSet() & ts3.getSymbolicSet()); ts24.setSymbolicSet(ts2.getSymbolicSet() & ts4.getSymbolicSet()); ts13.writeToFile("tworobots_ts13.bdd"); ts14.writeToFile("tworobots_ts14.bdd"); ts23.writeToFile("tworobots_ts23.bdd"); ts24.writeToFile("tworobots_ts24.bdd"); /****************************************************************************/ /* construct SymbolicSet for the input space */ /****************************************************************************/ scots::SymbolicSet is=robotCreateInputSpace(mgr); is.writeToFile("robot_is.bdd"); std::cout << std::endl << "Input space details:" << std::endl; is.printInfo(0); /****************************************************************************/ /* setup class for symbolic model computation */ /****************************************************************************/ /* first create SymbolicSet of post variables * by copying the SymbolicSet of the state space and assigning new BDD IDs */ scots::SymbolicSet sspost(ss,1); /* instantiate the SymbolicModel */ scots::SymbolicModelGrowthBound<state_type,input_type> abstraction(&ss, &is, &sspost); /* compute the transition relation */ tt.tic(); abstraction.computeTransitionRelation(robot_post, radius_post); std::cout << std::endl; tt.toc(); abstraction.getTransitionRelation().writeToFile("tworobots_rel.bdd"); /* get the number of elements in the transition relation */ std::cout << std::endl << "Number of elements in the transition relation: " << abstraction.getSize() << std::endl; /****************************************************************************/ /* we continue with the controller synthesis */ /****************************************************************************/ /* we setup a fixed point object to compute reachabilty controller */ scots::FixedPoint fp(&abstraction); /* the fixed point algorithm operates on the BDD directly */ BDD T1 = ts1.getSymbolicSet(); BDD T2 = ts2.getSymbolicSet(); BDD T3 = ts3.getSymbolicSet(); BDD T4 = ts4.getSymbolicSet(); /* the output of the fixed point computation are two bdd's */ tt.tic(); /* we implement the nested fixed point algorithm * * mu X. nu Y. ( pre(Y) & T ) | pre(X) * */ tt.tic(); size_t i,j; /* outer fp*/ BDD X=mgr.bddZero(); BDD XX=mgr.bddOne(); /* inner fp*/ BDD Y1=mgr.bddOne(); BDD YY1=mgr.bddZero(); BDD Y2=mgr.bddOne(); BDD YY2=mgr.bddZero(); BDD Y3=mgr.bddOne(); BDD YY3=mgr.bddZero(); BDD Y4=mgr.bddOne(); BDD YY4=mgr.bddZero(); /* the controller */ BDD C1=mgr.bddZero(); // assigned to T1, T3 BDD C2=mgr.bddZero(); // assigned to T1, T4 BDD C3=mgr.bddZero(); // assigned to T2, T3 BDD C4=mgr.bddZero(); // assigned to T2, T4 BDD U=is.getCube(); for(i=1; XX != X; i++) { X=XX; BDD preX=fp.pre(X); /* init inner fp */ YY1 = mgr.bddZero(); for(j=1; YY1 != Y1; j++) { Y1=YY1; YY1= (( preX & (T1&T3) )) | fp.pre(Y1); BDD N1 = YY1 & (!(C1.ExistAbstract(U))); C1 = C1 | N1; } std::cout << "Iterations inner1: " << j << std::endl; /* init inner fp */ YY2 = mgr.bddZero(); for(j=1; YY2 != Y2; j++) { Y2=YY2; YY2= (( preX & (T1&T4) )) | fp.pre(Y2); BDD N2 = YY2 & (!(C2.ExistAbstract(U))); C2 = C2 | N2; } std::cout << "Iterations inner2: " << j << std::endl; /* init inner fp */ YY3 = mgr.bddZero(); for(j=1; YY3 != Y3; j++) { Y3=YY3; YY3= (( preX & (T2&T3) )) | fp.pre(Y3); BDD N3 = YY3 & (!(C3.ExistAbstract(U))); C3 = C3 | N3; } std::cout << "Iterations inner3: " << j << std::endl; /* init inner fp */ YY4 = mgr.bddZero(); for(j=1; YY4 != Y4; j++) { Y4=YY4; YY4= (( preX & (T2&T4) )) | fp.pre(Y4); BDD N4 = YY4 & (!(C4.ExistAbstract(U))); C4 = C4 | N4; } std::cout << "Iterations inner4: " << j << std::endl; XX=YY1 & YY2 & YY3 & YY4; } std::cout << "Iterations outer: " << i << std::endl; tt.toc(); scots::SymbolicSet cont1(ss,is); cont1.setSymbolicSet(C1); cont1.writeToFile("tworobots_cont1.bdd"); scots::SymbolicSet cont2(ss,is); cont2.setSymbolicSet(C2); cont2.writeToFile("tworobots_cont2.bdd"); scots::SymbolicSet cont3(ss,is); cont3.setSymbolicSet(C3); cont3.writeToFile("tworobots_cont3.bdd"); scots::SymbolicSet cont4(ss,is); cont4.setSymbolicSet(C4); cont4.writeToFile("tworobots_cont4.bdd"); return 1; }
30.035928
116
0.607257
[ "object", "model" ]
5d226ef6900eb3dd1e7c939456f105702a49912c
1,837
cpp
C++
2_course/2_week/3_merge_tables/main.cpp
claytonjwong/Algorithms-UCSD
09d433a1cbc00dc8d913ece8716ac539b81340cd
[ "Unlicense" ]
6
2019-11-13T01:19:28.000Z
2021-08-10T19:19:57.000Z
2_course/2_week/3_merge_tables/main.cpp
claytonjwong/Algorithms-UCSD
09d433a1cbc00dc8d913ece8716ac539b81340cd
[ "Unlicense" ]
null
null
null
2_course/2_week/3_merge_tables/main.cpp
claytonjwong/Algorithms-UCSD
09d433a1cbc00dc8d913ece8716ac539b81340cd
[ "Unlicense" ]
3
2019-11-13T03:11:15.000Z
2020-11-28T20:05:38.000Z
/** * * C++ implementation to merge tables using Union-Find algorithm (disjoint sets) * * (c) Copyright 2019 Clayton J. Wong ( http://www.claytonjwong.com ) * **/ #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <vector> #include <string> using namespace std; class DisjointSet { public: using Collection = vector< int >; DisjointSet( istream& is, int N ) : P( N+1 ), V{ 0 }, M{ 0 } { // N+1 (P)arent set representatives for 1-based indexing, { 0 } is a dummy for corresponding 1-based indexed (V)alues ( i.e. V.size() == 1 ) generate( P.begin(), P.end(), [ i = -1 ]() mutable { return ++i; }); // init each (P)arent as a set representative of itself ( i.e. P[ 0 ] = 0, P[ 1 ] = 1, ... , P[ N-1 ] = N-1, P[ N ] = N ) copy_n( istream_iterator< int >( is ), N, back_inserter( V ) ); // read each set representative's (V)alue and append onto { 0 } for 1-based indexing M = *max_element( V.begin(), V.end() ); // (M)aximum (V)alue } int Union( int a, int b ){ a = Find( a ); b = Find( b ); if( a == b ) return M; P[ b ] = P[ a ]; V[ a ] += V[ b ], V[ b ] = 0; if( M < V[ a ] ) M = V[ a ]; return M; } int Find( int x ){ if( P[ x ] == x ) return P[ x ]; return P[ x ] = Find( P[ x ] ); } private: Collection P, V; // (P)arent / (V)alue int M; // (M)aximum value }; int main() { string line; auto N{ 0 }, M{ 0 }; { getline( cin, line ); istringstream is{ line }; is >> N >> M; } DisjointSet ds{ cin, N }; for( auto a{ 0 }, b{ 0 } ; M--; ){ cin >> a >> b; cout << ds.Union( a, b ) << endl; } return 0; }
30.114754
217
0.481764
[ "vector" ]
5d23223a95ee724d2547c5bf38fbd2cfdaf3c695
123,767
cxx
C++
inetcore/mshtml/src/site/base/dom.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/mshtml/src/site/base/dom.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/mshtml/src/site/base/dom.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "headers.hxx" #pragma MARK_DATA(__FILE__) #pragma MARK_CODE(__FILE__) #pragma MARK_CONST(__FILE__) #ifndef X_ELEMENT_HXX_ #define X_ELEMENT_HXX_ #include "element.hxx" #endif #ifndef X_FORMKRNL_HXX_ #define X_FORMKRNL_HXX_ #include "formkrnl.hxx" #endif #ifndef X_DOM_HXX_ #define X_DOM_HXX_ #include "dom.hxx" #endif #ifndef X_COLLBASE_HXX_ #define X_COLLBASE_HXX_ #include "collbase.hxx" #endif #ifndef X_DOMCOLL_HXX_ #define X_DOMCOLL_HXX_ #include "domcoll.hxx" #endif #ifndef X_TPOINTER_HXX_ #define X_TPOINTER_HXX_ #include "tpointer.hxx" #endif #ifndef X_TREEPOS_HXX_ #define X_TREEPOS_HXX_ #include "treepos.hxx" #endif #ifndef X_QI_IMPL_H_ #define X_QI_IMPL_H_ #include "qi_impl.h" #endif #ifndef X_HEDELEMS_HXX_ #define X_HEDELEMS_HXX_ #include "hedelems.hxx" #endif #ifndef X_ROOTELEM_HXX #define X_ROOTELEM_HXX #include "rootelem.hxx" #endif #ifndef X_COMMENT_HXX #define X_COMMENT_HXX #include "comment.hxx" #endif #ifndef X_EOBJECT_HXX #define X_EOBJECT_HXX #include "eobject.hxx" #endif #define _cxx_ #include "dom.hdl" //////////////////////////////////////////////////////////////////////////////// // // DOM Helper methods: // //////////////////////////////////////////////////////////////////////////////// static HRESULT CrackDOMNode ( IUnknown *pNode, CDOMTextNode**ppTextNode, CElement **ppElement, CMarkup * pWindowedMarkupContext ) { CMarkup *pMarkup; // Used to check if node is of type CDocument HRESULT hr = THR(pNode->QueryInterface(CLSID_CElement, (void **)ppElement)); if (hr) { // If node supports Markup, it cant be CElement or CDOMTextNode & by elimination, it has to be CDocument hr = THR(pNode->QueryInterface(CLSID_CMarkup, (void **)&pMarkup)); if (hr) { if (ppTextNode) { hr = THR(pNode->QueryInterface(CLSID_HTMLDOMTextNode, (void **)ppTextNode)); if (!hr && (pWindowedMarkupContext != (*ppTextNode)->GetWindowedMarkupContext())) hr = E_INVALIDARG; } } else { *ppElement = pMarkup->Root(); // If CDocument, set element to root element if ( pWindowedMarkupContext != pMarkup->GetWindowedMarkupContext() ) hr = E_INVALIDARG; } } else { Assert( (*ppElement)->Tag() != ETAG_ROOT ); if ( pWindowedMarkupContext != (*ppElement)->GetWindowedMarkupContext()) hr = E_INVALIDARG; } RRETURN ( hr ); } static HRESULT CrackDOMNodeVARIANT ( VARIANT *pVarNode, CDOMTextNode**ppTextNode, CElement **ppElement, CMarkup * pWindowedMarkupContext ) { HRESULT hr = S_OK; switch (V_VT(pVarNode)) { case VT_DISPATCH: case VT_UNKNOWN: if (V_UNKNOWN(pVarNode)) { // Element OR Text Node ?? hr = THR(CrackDOMNode(V_UNKNOWN(pVarNode), ppTextNode, ppElement, pWindowedMarkupContext)); } break; case VT_NULL: case VT_ERROR: hr = S_OK; break; default: hr = E_INVALIDARG; break; } RRETURN ( hr ); } static HRESULT GetDOMInsertHelper ( CElement *pRefElement, CDOMTextNode *pRefTextNode, CMarkupPointer *pmkptrPos ) { HRESULT hr = E_UNEXPECTED; Assert ( pRefElement || pRefTextNode ); Assert ( !(pRefElement && pRefTextNode ) ); if ( pRefElement ) { // Element Insert if (!pRefElement->IsInMarkup()) goto Cleanup; hr = THR(pmkptrPos->MoveAdjacentToElement ( pRefElement, pRefElement->Tag() == ETAG_ROOT? ELEM_ADJ_AfterBegin : ELEM_ADJ_BeforeBegin )); if ( hr ) goto Cleanup; } else { // Text Node Insert // Reposition the text node, then confirm we are it's parent CMarkupPointer *pmkpTextPtr = NULL; hr = THR(pRefTextNode->GetMarkupPointer ( &pmkpTextPtr )); if ( hr ) goto Cleanup; hr = THR(pmkptrPos->MoveToPointer ( pmkpTextPtr )); if ( hr ) goto Cleanup; } Cleanup: RRETURN ( hr ); } static HRESULT InsertDOMNodeHelper ( CElement *pNewElement, CDOMTextNode *pNewTextNode, CMarkupPointer *pmkptrTarget ) { HRESULT hr = S_OK; Assert ( pNewTextNode || pNewElement ); if ( pNewElement ) { CDoc *pDoc = pNewElement->Doc(); // Insert/Move element with content if (pNewElement->IsInMarkup() && !pNewElement->IsNoScope()) { CMarkupPointer mkptrStart(pDoc); CMarkupPointer mkptrEnd(pDoc); Assert(pNewElement->Tag() != ETAG_PARAM); hr = THR(pNewElement->GetMarkupPtrRange (&mkptrStart, &mkptrEnd) ); if ( hr ) goto Cleanup; hr = THR(pDoc->Move(&mkptrStart, &mkptrEnd, pmkptrTarget, MUS_DOMOPERATION)); } else { if (pNewElement->IsInMarkup()) { Assert(pNewElement->Tag() != ETAG_PARAM || !DYNCAST(CParamElement, pNewElement)->_pelObjParent); hr = THR(pDoc->RemoveElement(pNewElement, MUS_DOMOPERATION)); if ( hr ) goto Cleanup; } else if (pNewElement->Tag() == ETAG_PARAM) { // remove <PARAM> from exisiting <OBJECT> if present, first CParamElement *pelParam = DYNCAST(CParamElement, pNewElement); if (pelParam->_pelObjParent) { Assert(pelParam->_idxParam != -1); pelParam->_pelObjParent->RemoveParam(pelParam); Assert(pelParam->_idxParam == -1); Assert(!pelParam->_pelObjParent); } } hr = THR(pDoc->InsertElement(pNewElement, pmkptrTarget, NULL, MUS_DOMOPERATION)); } if (hr) goto Cleanup; } else { // Insert Text content hr = THR(pNewTextNode->MoveTo ( pmkptrTarget )); if (hr) goto Cleanup; } Cleanup: RRETURN(hr); } static HRESULT RemoveDOMNodeHelper ( CDoc *pDoc, CElement *pChildElement, CDOMTextNode *pChildTextNode ) { HRESULT hr = S_OK; CMarkup *pMarkupTarget = NULL; Assert ( pChildTextNode || pChildElement ); if ( pChildTextNode ) { // Removing a TextNode hr = THR(pChildTextNode->Remove()); } else if (pChildElement->IsInMarkup()) { // Removing an element if (!pChildElement->IsNoScope()) { CMarkupPointer mkptrStart ( pDoc ); CMarkupPointer mkptrEnd ( pDoc ); CMarkupPointer mkptrTarget ( pDoc ); hr = THR(pDoc->CreateMarkup(&pMarkupTarget, pChildElement->GetWindowedMarkupContext())); if ( hr ) goto Cleanup; hr = THR( pMarkupTarget->SetOrphanedMarkup( TRUE ) ); if( hr ) goto Cleanup; hr = THR(mkptrTarget.MoveToContainer(pMarkupTarget,TRUE)); if (hr) goto Cleanup; hr = THR(pChildElement->GetMarkupPtrRange (&mkptrStart, &mkptrEnd) ); if ( hr ) goto Cleanup; hr = THR(pDoc->Move(&mkptrStart, &mkptrEnd, &mkptrTarget, MUS_DOMOPERATION)); } else hr = THR(pDoc->RemoveElement(pChildElement, MUS_DOMOPERATION)); } Cleanup: ReleaseInterface ( (IUnknown*)pMarkupTarget ); // Creating it addref'd it once RRETURN(hr); } static HRESULT ReplaceDOMNodeHelper ( CDoc *pDoc, CElement *pTargetElement, CDOMTextNode *pTargetNode, CElement *pSourceElement, CDOMTextNode *pSourceTextNode ) { CMarkupPointer mkptrInsert ( pDoc ); HRESULT hr; // Position ourselves in the right spot hr = THR(GetDOMInsertHelper ( pTargetElement, pTargetNode, &mkptrInsert )); if ( hr ) goto Cleanup; mkptrInsert.SetGravity ( POINTER_GRAVITY_Left ); { // Lock the markup, to prevent it from going away in case the entire contents are being removed. CMarkup::CLock MarkupLock(mkptrInsert.Markup()); // Remove myself hr = THR(RemoveDOMNodeHelper ( pDoc, pTargetElement, pTargetNode )); if ( hr ) goto Cleanup; // Insert the new element & all its content hr = THR(InsertDOMNodeHelper( pSourceElement, pSourceTextNode, &mkptrInsert )); if ( hr ) goto Cleanup; } Cleanup: RRETURN(hr); } static HRESULT SwapDOMNodeHelper ( CDoc *pDoc, CElement *pElem, CDOMTextNode *pTextNode, CElement *pElemSwap, CDOMTextNode *pTextNodeSwap ) { CMarkupPointer mkptrThisInsert ( pDoc ); CMarkupPointer mkptrSwapInsert ( pDoc ); HRESULT hr; // Position ourselves in the right spot if (!pElem || pElem->IsInMarkup()) { hr = THR(GetDOMInsertHelper ( pElem, pTextNode, &mkptrThisInsert )); if (hr) goto Cleanup; } if (!pElemSwap || pElemSwap->IsInMarkup()) { hr = THR(GetDOMInsertHelper ( pElemSwap, pTextNodeSwap, &mkptrSwapInsert )); if (hr) goto Cleanup; } // Lock the markup, to prevent it from going away in case the entire contents are being removed. if (mkptrSwapInsert.Markup()) mkptrSwapInsert.Markup()->AddRef(); // Insert the new element & all its content if (mkptrThisInsert.IsPositioned()) hr = THR(InsertDOMNodeHelper( pElemSwap, pTextNodeSwap, &mkptrThisInsert )); else hr = THR(RemoveDOMNodeHelper(pDoc, pElemSwap, pTextNodeSwap)); if ( hr ) goto Cleanup; // Insert the new element & all its content if (mkptrSwapInsert.IsPositioned()) { hr = THR(InsertDOMNodeHelper( pElem, pTextNode, &mkptrSwapInsert )); mkptrSwapInsert.Markup()->Release(); } else hr = THR(RemoveDOMNodeHelper(pDoc, pElem, pTextNode)); Cleanup: RRETURN(hr); } static HRESULT CreateTextNode ( CDoc *pDoc, CMarkupPointer *pmkpTextEnd, long lTextID, CDOMTextNode **ppTextNode ) { CMarkupPointer *pmarkupWalkBegin = NULL; HRESULT hr = S_OK; Assert ( ppTextNode ); Assert ( !(*ppTextNode) ); if ( lTextID != 0 ) { *ppTextNode = (CDOMTextNode *)pDoc-> _HtPvPvDOMTextNodes.Lookup ( (void *)(DWORD_PTR)(lTextID<<4) ); } if ( !(*ppTextNode) ) { // Need to create a Text Node pmarkupWalkBegin = new CMarkupPointer (pDoc); if ( !pmarkupWalkBegin ) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR(pmarkupWalkBegin->MoveToPointer ( pmkpTextEnd )); if ( hr ) goto Cleanup; hr = THR(pmarkupWalkBegin->Left( TRUE, NULL, NULL, NULL, NULL, &lTextID)); if ( hr ) goto Cleanup; if ( lTextID == 0 ) { hr = THR(pmarkupWalkBegin->SetTextIdentity(pmkpTextEnd, &lTextID)); if ( hr ) goto Cleanup; } // Stick to the text hr = THR(pmarkupWalkBegin->SetGravity (POINTER_GRAVITY_Right)); if ( hr ) goto Cleanup; // Need to set Glue Also! Assert( lTextID != 0 ); *ppTextNode = new CDOMTextNode ( lTextID, pDoc, pmarkupWalkBegin ); if ( !*ppTextNode ) { hr = E_OUTOFMEMORY; goto Cleanup; } // Now give ownership of this markup pointer to the text Node pmarkupWalkBegin = NULL; hr = THR(pDoc->_HtPvPvDOMTextNodes.Insert ( (void*)(DWORD_PTR)(lTextID<<4), (void*)*ppTextNode ) ); if ( hr ) goto Cleanup; } else { (*ppTextNode)->AddRef(); } Cleanup: delete pmarkupWalkBegin; RRETURN(hr); } static HRESULT GetPreviousHelper ( CDoc *pDoc, CMarkupPointer *pmarkupWalk, IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; CTreeNode *pNodeLeft; MARKUP_CONTEXT_TYPE context; long lTextID; if (!ppNode) { hr = E_POINTER; goto Cleanup; } *ppNode = NULL; hr = THR(pmarkupWalk->Left( FALSE, &context, &pNodeLeft, NULL, NULL, &lTextID)); if ( hr ) goto Cleanup; switch ( context ) { case CONTEXT_TYPE_Text: { // Text Node CDOMTextNode *pTextNode = NULL; // If we find text we ccannot have left the scope of our parent hr = THR(CreateTextNode (pDoc, pmarkupWalk, lTextID, &pTextNode )); if ( hr ) goto Cleanup; hr = THR ( pTextNode->QueryInterface ( IID_IHTMLDOMNode, (void **)ppNode ) ); if ( hr ) goto Cleanup; pTextNode->Release(); } break; case CONTEXT_TYPE_EnterScope: case CONTEXT_TYPE_NoScope: // Return Disp to Element hr = THR(pNodeLeft->GetElementInterface ( IID_IHTMLDOMNode, (void **) ppNode )); if ( hr ) goto Cleanup; break; case CONTEXT_TYPE_ExitScope: case CONTEXT_TYPE_None: break; default: Assert(FALSE); // Should never happen break; } Cleanup: RRETURN(hr); } static HRESULT GetNextHelper ( CDoc *pDoc, CMarkupPointer *pmarkupWalk, IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; CTreeNode *pnodeRight; MARKUP_CONTEXT_TYPE context; long lTextID; if (!ppNode) { hr = E_POINTER; goto Cleanup; } *ppNode = NULL; hr = THR( pmarkupWalk->Right( TRUE, &context, &pnodeRight, NULL, NULL, &lTextID)); if ( hr ) goto Cleanup; switch ( context ) { case CONTEXT_TYPE_Text: { // Text Node CDOMTextNode *pTextNode = NULL; // If we find text we ccannot have left the scope of our parent hr = THR(CreateTextNode (pDoc, pmarkupWalk, lTextID, &pTextNode )); if ( hr ) goto Cleanup; hr = THR ( pTextNode->QueryInterface ( IID_IHTMLDOMNode, (void **)ppNode ) ); if ( hr ) goto Cleanup; pTextNode->Release(); } break; case CONTEXT_TYPE_EnterScope: case CONTEXT_TYPE_NoScope: // Return Disp to Element hr = THR(pnodeRight->GetElementInterface ( IID_IHTMLDOMNode, (void **) ppNode )); if ( hr ) goto Cleanup; break; case CONTEXT_TYPE_ExitScope: case CONTEXT_TYPE_None: break; default: Assert(FALSE); // Should never happen break; } Cleanup: RRETURN(hr); } #if DBG == 1 static BOOL IsRootOnlyIfDocument(IHTMLDOMNode *pNode, CElement *pElement) { HRESULT hr; CMarkup * pMarkup; if( pElement && pElement->Tag() == ETAG_ROOT ) { hr = THR(pNode->QueryInterface(CLSID_CMarkup, (void **)&pMarkup)); if( hr ) { return FALSE; } } return TRUE; } #endif static HRESULT CurrentScope ( CMarkupPointer *pMkpPtr, IHTMLElement ** ppElemCurrent, CTreeNode ** ppNode ) { HRESULT hr = S_OK; CTreeNode * pTreeNode = NULL; Assert( (!ppElemCurrent && ppNode) || (ppElemCurrent && !ppNode) ); pMkpPtr->Validate(); if (pMkpPtr->IsPositioned()) { pTreeNode = pMkpPtr->Branch(); if (pTreeNode->Tag() == ETAG_ROOT && !pTreeNode->Element()->GetMarkup()->HasDocument()) pTreeNode = NULL; } if (ppNode) { *ppNode = pTreeNode; goto Cleanup; } else { Assert(ppElemCurrent); *ppElemCurrent = NULL; if (pTreeNode) { hr = THR( pTreeNode->GetElementInterface( IID_IHTMLElement, (void **) ppElemCurrent ) ); if (hr) goto Cleanup; } } Cleanup: RRETURN( hr ); } static HRESULT ParentNodeHelper( CTreeNode *pNode, IHTMLDOMNode **pparentNode ) { HRESULT hr = S_OK; CElement * pElement; CMarkup * pMarkup; CDocument * pDocument; BOOL fDocumentPresent; *pparentNode = NULL; if (pNode->Tag() == ETAG_ROOT) { pElement = pNode->Element(); pMarkup = pElement->GetMarkup(); Assert(pMarkup); fDocumentPresent = pMarkup->HasDocument(); hr = THR(pMarkup->EnsureDocument(&pDocument)); if ( hr ) goto Cleanup; Assert(pDocument); if (!fDocumentPresent) pDocument->_lnodeType = 11; hr = THR(pDocument->QueryInterface( IID_IHTMLDOMNode, (void**) pparentNode )); if ( hr ) goto Cleanup; } else { hr = THR(pNode->GetElementInterface ( IID_IHTMLDOMNode, (void**) pparentNode )); if ( hr ) goto Cleanup; } Cleanup: RRETURN( hr ); } static HRESULT ScanText(CDoc *pDoc, CMarkupPointer *pMkpStart, CMarkupPointer *pMkpTxtEnd, CMarkupPointer *pMkpEnd) { HRESULT hr = S_OK; MARKUP_CONTEXT_TYPE context = CONTEXT_TYPE_None; long lTextID; BOOL fEnterText = FALSE; CDOMTextNode *pTextNode; do { hr = THR(pMkpTxtEnd->Right(TRUE, &context, NULL, NULL, NULL, &lTextID)); if (hr) goto Cleanup; if (lTextID) { Assert(context == CONTEXT_TYPE_Text); if (!fEnterText) { hr = THR(pMkpTxtEnd->Right(FALSE, &context, NULL, NULL, NULL, NULL)); if (hr) goto Cleanup; if (context == CONTEXT_TYPE_Text) fEnterText = TRUE; } if (fEnterText) { pTextNode = (CDOMTextNode *)pDoc->_HtPvPvDOMTextNodes.Lookup((void *)(DWORD_PTR)(lTextID<<4)); pTextNode->TearoffTextNode(pMkpStart, pMkpTxtEnd); } } else if (fEnterText && (context != CONTEXT_TYPE_Text)) fEnterText = FALSE; hr = THR(pMkpStart->MoveToPointer(pMkpTxtEnd)); if (hr) goto Cleanup; } while(pMkpTxtEnd->IsLeftOf(pMkpEnd)); Cleanup: RRETURN(hr); } static HRESULT OwnerDocHelper(IDispatch **ppretdoc, CDOMTextNode *pDOMTextNode, CElement *pElement) { HRESULT hr = S_OK; CMarkup *pMarkup; CDocument *pDocument = NULL; Assert(!!pDOMTextNode ^ !!pElement); if( !ppretdoc ) { hr = E_POINTER; goto Cleanup; } *ppretdoc = NULL; pMarkup = pDOMTextNode? pDOMTextNode->GetWindowedMarkupContext() : pElement->GetWindowedMarkupContext(); Assert( pMarkup ); if ( ! pMarkup ) { hr = E_FAIL; goto Cleanup; } if( pMarkup->HasDocument() ) { pDocument = pMarkup->Document(); Assert(pDocument); Assert(pDocument->_lnodeType == 9); hr = THR(pDocument->QueryInterface(IID_IDispatch, (void **)ppretdoc)); if (hr) goto Cleanup; } Cleanup: RRETURN(hr); } //////////////////////////////////////////////////////////////////////////////// // // IHTMLDOMTextNode methods: // //////////////////////////////////////////////////////////////////////////////// MtDefine(CDOMTextNode, ObjectModel, "CDOMTextNode") //+---------------------------------------------------------------- // // member : classdesc // //+---------------------------------------------------------------- const CBase::CLASSDESC CDOMTextNode::s_classdesc = { &CLSID_HTMLDOMTextNode, // _pclsid 0, // _idrBase #ifndef NO_PROPERTY_PAGE NULL, // _apClsidPages #endif // NO_PROPERTY_PAGE NULL, // _pcpi 0, // _dwFlags &IID_IHTMLDOMTextNode, // _piidDispinterface &s_apHdlDescs, // _apHdlDesc }; HRESULT CDOMTextNode::PrivateQueryInterface(REFIID iid, void **ppv) { HRESULT hr = E_NOINTERFACE; if ( !ppv ) { hr = E_INVALIDARG; goto Cleanup; } *ppv = NULL; switch (iid.Data1) { QI_INHERITS((IPrivateUnknown *)this, IUnknown) QI_TEAROFF_DISPEX(this, NULL) QI_TEAROFF(this, IHTMLDOMTextNode2, NULL) QI_TEAROFF(this, IHTMLDOMTextNode, NULL) QI_TEAROFF(this, IHTMLDOMNode, NULL) QI_TEAROFF(this, IHTMLDOMNode2, NULL) QI_TEAROFF(this, IObjectIdentity, NULL) } if ( iid == CLSID_HTMLDOMTextNode ) { *ppv = (void*)this; return S_OK; } if (*ppv) { ((IUnknown*)*ppv)->AddRef(); return S_OK; } Cleanup: return hr; } HRESULT CDOMTextNode::UpdateTextID( CMarkupPointer *pMkpPtr ) { HRESULT hr = S_OK; long lNewTextID; hr = THR(_pMkpPtr->SetTextIdentity(pMkpPtr, &lNewTextID)); if ( hr ) goto Cleanup; // Update the Doc Text Node Ptr Lookup _pDoc->_HtPvPvDOMTextNodes.Remove ( (void *)(DWORD_PTR)(_lTextID<<4) ); _lTextID = lNewTextID; hr = THR(_pDoc->_HtPvPvDOMTextNodes.Insert ( (void*)(DWORD_PTR)(_lTextID<<4), (void*)this ) ); if ( hr ) goto Cleanup; Cleanup: RRETURN( hr ); } HRESULT CDOMTextNode::MoveToOffset( long loffset, CMarkupPointer *pMkpPtr, CMarkupPointer *pMkpEnd ) { HRESULT hr = S_OK; MARKUP_CONTEXT_TYPE context; long lTextID; long lMove = loffset; // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, pMkpEnd ) ); if ( hr ) goto Cleanup; pMkpEnd->SetGravity(POINTER_GRAVITY_Right); hr = THR(pMkpPtr->MoveToPointer(_pMkpPtr)); if( hr ) goto Cleanup; if( loffset ) { hr = THR( pMkpPtr->Right( TRUE, &context, NULL, &lMove, NULL, &lTextID)); if( hr ) goto Cleanup; Assert( lTextID == _lTextID ); Assert( context == CONTEXT_TYPE_Text ); if ( loffset != lMove ) { hr = E_INVALIDARG; goto Cleanup; } } Cleanup: RRETURN( hr ); } HRESULT CDOMTextNode::InsertTextHelper( CMarkupPointer *pMkpPtr, BSTR bstrstring, long loffset) { HRESULT hr = S_OK; // If loffset=0, _pMkpPtr is affected by remove / insert, & should not become unpositioned if(!loffset) _pMkpPtr->SetGravity( POINTER_GRAVITY_Left ); pMkpPtr->SetGravity ( POINTER_GRAVITY_Right ); hr = THR( _pDoc->InsertText( pMkpPtr, bstrstring, -1, MUS_DOMOPERATION ) ); if ( hr ) goto Cleanup; // Restore the proper gravity, so that new TextID can be set later. _pMkpPtr->SetGravity( POINTER_GRAVITY_Right ); Cleanup: RRETURN( hr ); } HRESULT CDOMTextNode::RemoveTextHelper(CMarkupPointer *pMkpStart, long lCount, long loffset) { HRESULT hr = S_OK; CMarkupPointer MkpRight(_pDoc); if( lCount ) { hr = THR(MkpRight.MoveToPointer(pMkpStart)); if( hr ) goto Cleanup; hr = THR( MkpRight.Right( TRUE, NULL, NULL, &lCount, NULL, NULL) ); if( hr ) goto Cleanup; // If loffset=0, _pMkpPtr is affected by remove / insert, & should not become unpositioned if(!loffset) _pMkpPtr->SetGravity ( POINTER_GRAVITY_Left ); // Remove the Text hr = THR(_pDoc->Remove ( pMkpStart, &MkpRight, MUS_DOMOPERATION )); if ( hr ) goto Cleanup; } Cleanup: RRETURN( hr ); } HRESULT CDOMTextNode::get_data(BSTR *pbstrData) { HRESULT hr = S_OK; MARKUP_CONTEXT_TYPE context; long lCharCount = -1; long lTextID; if ( !pbstrData ) goto Cleanup; *pbstrData = NULL; // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, (CMarkupPointer * )NULL ) ); if ( hr ) goto Cleanup; // Walk right (hopefully) over text, inital pass, don't move just get count of chars hr = THR( _pMkpPtr->Right( FALSE, &context, NULL, &lCharCount, NULL, &lTextID)); if ( hr ) goto Cleanup; Assert ( lTextID == _lTextID ); if ( context == CONTEXT_TYPE_Text ) { // Alloc memory hr = FormsAllocStringLen ( NULL, lCharCount, pbstrData ); if ( hr ) goto Cleanup; hr = THR( _pMkpPtr->Right( FALSE, &context, NULL, &lCharCount, *pbstrData, &lTextID)); if ( hr ) goto Cleanup; } Cleanup: RRETURN(SetErrorInfo(hr)); } CDOMTextNode::CDOMTextNode ( long lTextID, CDoc *pDoc, CMarkupPointer *pmkptr ) { Assert(pDoc); Assert(pmkptr); _pDoc = pDoc ; _lTextID = lTextID ; _pDoc->AddRef(); // Due to lookaside table _pMkpPtr = pmkptr; // markup ptr will manage Markup in which text node is in. _pMkpPtr->SetKeepMarkupAlive(TRUE); // Add glue so that tree services can manage ptr movement // between markups automatically during splice operations _pMkpPtr->SetCling(TRUE); } CDOMTextNode::~CDOMTextNode() { // tidy up lookaside _pDoc->_HtPvPvDOMTextNodes.Remove ( (void *)(DWORD_PTR)(_lTextID<<4) ); // Tidy up markup ptr/markup _pMkpPtr->SetKeepMarkupAlive(FALSE); _pMkpPtr->SetCling(FALSE); _pDoc->Release(); delete _pMkpPtr; } HRESULT STDMETHODCALLTYPE CDOMTextNode::IsEqualObject(IUnknown * pUnk) { HRESULT hr; IUnknown * pUnkThis = NULL; CDOMTextNode * pTargetTextNode; if (!pUnk) { hr = E_POINTER; goto Cleanup; } // Test standard COM identity first hr = THR_NOTRACE(QueryInterface(IID_IUnknown, (void **)&pUnkThis)); if (hr) goto Cleanup; if (pUnk == pUnkThis) { hr = S_OK; goto Cleanup; } // Do the dodgy CLSID QI hr = THR(pUnk->QueryInterface(CLSID_HTMLDOMTextNode, (void**)&pTargetTextNode)); if ( hr ) goto Cleanup; hr = (_lTextID == pTargetTextNode->_lTextID) ? S_OK : S_FALSE; Cleanup: ReleaseInterface(pUnkThis); RRETURN1(hr, S_FALSE); } HRESULT CDOMTextNode::cloneNode(VARIANT_BOOL fDeep, IHTMLDOMNode **ppNodeCloned) { HRESULT hr; CMarkupPointer mkpRight (_pDoc ); CMarkupPointer mkpTarget (_pDoc ); CMarkup *pMarkup = NULL; CMarkupPointer *pmkpStart = NULL; if ( !ppNodeCloned ) { hr = E_POINTER; goto Cleanup; } hr = THR(_pDoc->CreateMarkup ( &pMarkup, GetWindowedMarkupContext() )); if ( hr ) goto Cleanup; hr = THR( pMarkup->SetOrphanedMarkup( TRUE ) ); if( hr ) goto Cleanup; // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, &mkpRight ) ); if ( hr ) goto Cleanup; hr = THR(mkpTarget.MoveToContainer( pMarkup, TRUE ) ); if ( hr ) goto Cleanup; mkpTarget.SetGravity ( POINTER_GRAVITY_Right ); // Copy the markup across to the new markup container // (mkpTarget gets moved to the right of the text as a result) hr = THR( _pDoc->Copy ( _pMkpPtr, &mkpRight, &mkpTarget, MUS_DOMOPERATION ) ); if ( hr ) goto Cleanup; // Create the new text node markup pointer - will be handed off to text node pmkpStart = new CMarkupPointer ( _pDoc ); if ( !pmkpStart ) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR(pmkpStart->MoveToContainer( pMarkup, TRUE ) ); if ( hr ) goto Cleanup; // Create the new text node hr = THR(_pDoc->CreateDOMTextNodeHelper(pmkpStart, &mkpTarget, ppNodeCloned)); if ( hr ) goto Cleanup; pmkpStart = NULL; // Text Node owns the pointer Cleanup: ReleaseInterface ( (IUnknown*)pMarkup ); // Text node addref'ed it delete pmkpStart; RRETURN( hr ); } HRESULT CDOMTextNode::splitText(long lOffset, IHTMLDOMNode**ppRetNode ) { HRESULT hr = S_OK; CMarkupPointer mkpRight (_pDoc); CMarkupPointer mkpEnd (_pDoc); CMarkupPointer *pmkpStart = NULL; long lMove = lOffset; long lTextID; if ( lOffset < 0 || !ppRetNode) { hr = E_INVALIDARG; goto Cleanup; } // Split the text at the given offset to make a new text node, return the new text node pmkpStart = new CMarkupPointer ( _pDoc ); if ( !pmkpStart ) { hr = E_OUTOFMEMORY; goto Cleanup; } // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, &mkpRight ) ); if ( hr ) goto Cleanup; hr = THR(pmkpStart->MoveToPointer ( _pMkpPtr )); if ( hr ) goto Cleanup; lMove = lOffset; hr = THR(pmkpStart->Right ( TRUE, NULL, NULL, &lOffset, NULL, &lTextID )); if ( hr ) goto Cleanup; // Position at point of split hr = THR(mkpEnd.MoveToPointer (pmkpStart)); if ( hr ) goto Cleanup; // If my TextID changed, I moved outside my text node if ( lOffset != lMove ) { hr = E_INVALIDARG; goto Cleanup; } // Create the new text node hr = THR(_pDoc->CreateDOMTextNodeHelper(pmkpStart, &mkpRight, ppRetNode)); if ( hr ) goto Cleanup; pmkpStart = NULL; // New Text Node owns pointer // Re-Id the split text for original text node hr = THR(_pMkpPtr->SetTextIdentity(&mkpEnd, &lTextID)); if ( hr ) goto Cleanup; // Update the Doc Text Node Ptr Lookup _pDoc->_HtPvPvDOMTextNodes.Remove ( (void *)(DWORD_PTR)(_lTextID<<4) ); _lTextID = lTextID; hr = THR(_pDoc->_HtPvPvDOMTextNodes.Insert ( (void*)(DWORD_PTR)(_lTextID<<4), (void*)this ) ); if ( hr ) goto Cleanup; Cleanup: delete pmkpStart; RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::put_data(BSTR bstrData) { HRESULT hr = S_OK; CMarkupPointer mkpRight (_pDoc); CMarkupPointer mkpStart (_pDoc); // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, &mkpRight ) ); if ( hr ) goto Cleanup; Assert(_pMkpPtr->Cling()); // Set left gravity so that _pMkpPtr is not unpositioned, due to remove. _pMkpPtr->SetGravity ( POINTER_GRAVITY_Left ); // Remove the old Text hr = THR(_pDoc->Remove ( _pMkpPtr, &mkpRight, MUS_DOMOPERATION )); if ( hr ) goto Cleanup; // OK, old text is out, put the new stuff in hr = THR(mkpStart.MoveToPointer ( _pMkpPtr )); if ( hr ) goto Cleanup; // Set gravity of mkpStart to right, so that it moves to the end when text is inserted // at _pMkpPtr, which remains at the beginning due to left gravity. mkpStart.SetGravity(POINTER_GRAVITY_Right); hr = THR( _pDoc->InsertText( _pMkpPtr, bstrData, -1, MUS_DOMOPERATION ) ); if ( hr ) goto Cleanup; // restore gravity of _pMkpPtr to right _pMkpPtr->SetGravity(POINTER_GRAVITY_Right); hr = THR(UpdateTextID(&mkpStart)); if( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::toString(BSTR *pbstrData) { RRETURN(SetErrorInfo(get_data(pbstrData))); } HRESULT CDOMTextNode::get_length(long *pLength) { HRESULT hr = S_OK; long lCharCount = -1; long lTextID; MARKUP_CONTEXT_TYPE context; if ( !pLength ) { hr = E_POINTER; goto Cleanup; } *pLength = 0; // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, (CMarkupPointer *)NULL ) ); if ( hr ) goto Cleanup; // Walk right (hopefully) over text, inital pass, don't move just get count of chars hr = THR( _pMkpPtr->Right( FALSE, &context, NULL, &lCharCount, NULL, &lTextID)); if ( hr ) goto Cleanup; Assert ( lTextID == _lTextID ); if ( context == CONTEXT_TYPE_Text ) { *pLength = lCharCount; } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::get_nodeType(long *pnodeType) { HRESULT hr = S_OK; if (!pnodeType) { hr = E_POINTER; goto Cleanup; } *pnodeType = 3; // DOM_TEXTNODE Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::get_nodeName(BSTR *pbstrNodeName) { HRESULT hr = S_OK; if (!pbstrNodeName) { hr = E_POINTER; goto Cleanup; } *pbstrNodeName = NULL; hr = THR(FormsAllocString ( _T("#text"), pbstrNodeName )); if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::get_nodeValue(VARIANT *pvarValue) { HRESULT hr = S_OK; if (!pvarValue) { hr = E_POINTER; goto Cleanup; } pvarValue->vt = VT_BSTR; hr = THR(get_data(&V_BSTR(pvarValue))); Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::put_nodeValue(VARIANT varValue) { HRESULT hr = S_OK; CVariant varBSTRValue; hr = THR(varBSTRValue.CoerceVariantArg ( &varValue, VT_BSTR )); if ( hr ) goto Cleanup; hr = THR( put_data ( V_BSTR((VARIANT *)&varBSTRValue))); Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::get_firstChild ( IHTMLDOMNode **ppNode ) { if (ppNode) *ppNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CDOMTextNode::get_lastChild ( IHTMLDOMNode **ppNode ) { if (ppNode) *ppNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CDOMTextNode::get_previousSibling ( IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; CMarkupPointer markupWalk ( _pDoc ); // Move the markup pointer adjacent to the Text hr = THR(_pMkpPtr->FindTextIdentity ( _lTextID, (CMarkupPointer *)NULL )); if ( hr ) goto Cleanup; hr = THR(markupWalk.MoveToPointer(_pMkpPtr)); if ( hr ) goto Cleanup; hr = THR(GetPreviousHelper ( _pDoc, &markupWalk, ppNode )); if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::get_nextSibling ( IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; CMarkupPointer markupWalk ( _pDoc ); // Move the markup pointer adjacent to the Text hr = THR(_pMkpPtr->FindTextIdentity ( _lTextID, &markupWalk )); if ( hr ) goto Cleanup; hr = THR(GetNextHelper ( _pDoc, &markupWalk, ppNode )); if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::get_parentNode(IHTMLDOMNode **pparentNode) { HRESULT hr = S_OK; CTreeNode * pNode; if (!pparentNode) { hr = E_POINTER; goto Cleanup; } *pparentNode = NULL; // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, (CMarkupPointer *)NULL ) ); if ( hr ) goto Cleanup; hr = CurrentScope(_pMkpPtr, NULL, &pNode); if ( hr ) goto Cleanup; if (!pNode) { goto Cleanup; } hr = THR(ParentNodeHelper(pNode, pparentNode)); if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::hasChildNodes(VARIANT_BOOL *p) { HRESULT hr = S_OK; if (!p) { hr = E_POINTER; goto Cleanup; } *p = VARIANT_FALSE; Cleanup: RRETURN(SetErrorInfo(hr)); } CDOMChildrenCollection * CDOMTextNode::EnsureDOMChildrenCollectionPtr ( ) { CDOMChildrenCollection *pDOMPtr = NULL; GetPointerAt ( FindAAIndex ( DISPID_INTERNAL_CDOMCHILDRENPTRCACHE,CAttrValue::AA_Internal ), (void **)&pDOMPtr ); if ( !pDOMPtr ) { pDOMPtr = new CDOMChildrenCollection ( this, FALSE /* fIsElement */ ); if ( pDOMPtr ) { AddPointer ( DISPID_INTERNAL_CDOMCHILDRENPTRCACHE, (void *)pDOMPtr, CAttrValue::AA_Internal ); } } else { pDOMPtr->AddRef(); } return pDOMPtr; } HRESULT CDOMTextNode::get_childNodes(IDispatch **ppChildCollection) { HRESULT hr = S_OK; CDOMChildrenCollection *pChildren; if ( !ppChildCollection ) goto Cleanup; *ppChildCollection = NULL; pChildren = EnsureDOMChildrenCollectionPtr(); if ( !pChildren ) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR(pChildren->QueryInterface (IID_IDispatch,(void **)ppChildCollection)); if ( hr ) goto Cleanup; pChildren->Release(); // Lifetime is controlled by extrenal ref. Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::get_attributes(IDispatch **ppAttrCollection) { HRESULT hr = S_OK; if (!ppAttrCollection) { hr = E_POINTER; goto Cleanup; } *ppAttrCollection = NULL; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::removeNode(VARIANT_BOOL fDeep,IHTMLDOMNode** ppnewNode) { HRESULT hr = THR ( Remove () ); if ( hr ) goto Cleanup; if ( ppnewNode ) { hr = THR(QueryInterface (IID_IHTMLDOMNode, (void**)ppnewNode )); } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::replaceNode(IHTMLDOMNode *pNodeReplace, IHTMLDOMNode **ppNodeReplaced) { HRESULT hr; CDOMTextNode *pNewTextNode = NULL; CElement *pNewElement = NULL; if ( ppNodeReplaced ) *ppNodeReplaced = NULL; if ( !pNodeReplace ) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(CrackDOMNode((IUnknown*)pNodeReplace, &pNewTextNode, &pNewElement, GetWindowedMarkupContext())); if ( hr ) goto Cleanup; Assert(IsRootOnlyIfDocument(pNodeReplace, pNewElement)); hr = THR(ReplaceDOMNodeHelper ( _pDoc, NULL, this, pNewElement, pNewTextNode )); if ( hr ) goto Cleanup; if ( ppNodeReplaced ) { hr = THR(QueryInterface(IID_IHTMLDOMNode, (void**)ppNodeReplaced)); } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::swapNode(IHTMLDOMNode *pNodeSwap, IHTMLDOMNode **ppNodeSwapped) { CElement * pSwapElement = NULL; CDOMTextNode * pSwapText = NULL; HRESULT hr; if ( ppNodeSwapped ) *ppNodeSwapped = NULL; if ( !pNodeSwap ) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(CrackDOMNode((IUnknown*)pNodeSwap, &pSwapText, &pSwapElement, GetWindowedMarkupContext() )); if ( hr ) goto Cleanup; Assert(IsRootOnlyIfDocument(pNodeSwap, pSwapElement)); hr = THR (SwapDOMNodeHelper ( _pDoc, NULL, this, pSwapElement, pSwapText )); if ( hr ) goto Cleanup; if ( ppNodeSwapped ) { hr = THR(QueryInterface(IID_IHTMLDOMNode, (void**)ppNodeSwapped)); } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::insertBefore(IHTMLDOMNode *pNewChild, VARIANT refChild, IHTMLDOMNode **ppRetNode) { if (ppRetNode) *ppRetNode = NULL; // Don't expect this method to be called on a text node RRETURN(SetErrorInfo(E_UNEXPECTED)); } HRESULT CDOMTextNode::appendChild(IHTMLDOMNode *pNewChild, IHTMLDOMNode **ppRetNode) { if (ppRetNode) *ppRetNode = NULL; // Don't expect this method to be called on a text node RRETURN(SetErrorInfo(E_UNEXPECTED)); } HRESULT CDOMTextNode::replaceChild(IHTMLDOMNode *pNewChild, IHTMLDOMNode *pOldChild, IHTMLDOMNode **ppRetNode) { if (ppRetNode) *ppRetNode = NULL; // Don't expect this method to be called on a text node RRETURN(SetErrorInfo(E_UNEXPECTED)); } HRESULT CDOMTextNode::removeChild(IHTMLDOMNode *pOldChild, IHTMLDOMNode **ppRetNode) { if (ppRetNode) *ppRetNode = NULL; // Don't expect this method to be called on a text node RRETURN(SetErrorInfo(E_UNEXPECTED)); } HRESULT CDOMTextNode::GetMarkupPointer( CMarkupPointer **ppMkp ) { HRESULT hr; // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, (CMarkupPointer *)NULL ) ); if ( hr ) goto Cleanup; *ppMkp = _pMkpPtr; Cleanup: RRETURN(hr); } HRESULT CDOMTextNode::Remove ( void ) { // Move it into it's own Markup container HRESULT hr; CMarkup *pMarkup = NULL; CMarkupPointer mkpPtr (_pDoc); hr = THR( _pDoc->CreateMarkup( &pMarkup, GetWindowedMarkupContext() ) ); if (hr) goto Cleanup; hr = THR( pMarkup->SetOrphanedMarkup( TRUE ) ); if( hr ) goto Cleanup; hr = THR(mkpPtr.MoveToContainer( pMarkup, TRUE ) ); if ( hr ) goto Cleanup; hr = THR(MoveTo ( &mkpPtr )); if ( hr ) goto Cleanup; Cleanup: // Leave markup refcount at 1, text node is keeping it alive ReleaseInterface ( (IUnknown*)pMarkup ); RRETURN(hr); } HRESULT CDOMTextNode::MoveTo ( CMarkupPointer *pmkptrTarget ) { HRESULT hr; CMarkupPointer mkpEnd(_pDoc); long lCount; hr = THR(get_length(&lCount)); if ( hr ) goto Cleanup; // Move the markup pointer adjacent to the Text hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, &mkpEnd ) ); if ( hr ) goto Cleanup; pmkptrTarget->SetGravity ( POINTER_GRAVITY_Left ); // should have right gravity, which with cling will move it also along with text Assert(_pMkpPtr->Gravity()); Assert(_pMkpPtr->Cling()); hr = THR(_pDoc->Move ( _pMkpPtr, &mkpEnd, pmkptrTarget, MUS_DOMOPERATION )); Cleanup: RRETURN(hr); } inline CMarkup * CDOMTextNode::GetWindowedMarkupContext() { return _pMkpPtr->Markup()->GetWindowedMarkupContext(); } // IHTMLDOMTextNode2 methods HRESULT CDOMTextNode::substringData (long loffset, long lCount, BSTR* pbstrsubString) { HRESULT hr = E_POINTER; long lMove = lCount; CMarkupPointer mkpptr(_pDoc); CMarkupPointer mkpend(_pDoc); BSTR bstrTemp; if ( !pbstrsubString ) goto Cleanup; if ( lCount < 0 || loffset < 0) { hr = E_INVALIDARG; goto Cleanup; } *pbstrsubString = NULL; hr = THR(MoveToOffset(loffset, &mkpptr, &mkpend)); if ( hr ) goto Cleanup; hr = FormsAllocStringLen( NULL, lCount, pbstrsubString ); if ( hr ) goto Cleanup; hr = THR( mkpptr.Right( FALSE, NULL, NULL, &lMove, *pbstrsubString, NULL) ); if ( hr ) goto Cleanup; if(lMove != lCount) { Assert(lMove < lCount); hr = FormsAllocStringLen(*pbstrsubString, lMove, &bstrTemp ); SysFreeString(*pbstrsubString); *pbstrsubString = bstrTemp; } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::appendData (BSTR bstrstring) { HRESULT hr = S_OK; CMarkupPointer mkpptr(_pDoc); hr = THR( _pMkpPtr->FindTextIdentity ( _lTextID, &mkpptr ) ); if ( hr ) goto Cleanup; hr = THR(InsertTextHelper(&mkpptr, bstrstring, -1)); if( hr ) goto Cleanup; hr = THR(UpdateTextID(&mkpptr)); if( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::insertData (long loffset, BSTR bstrstring) { HRESULT hr = S_OK; CMarkupPointer mkpptr(_pDoc); CMarkupPointer mkpend(_pDoc); if ( loffset < 0) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(MoveToOffset(loffset, &mkpptr, &mkpend)); if ( hr ) goto Cleanup; hr = THR(InsertTextHelper(&mkpptr, bstrstring, loffset)); if( hr ) goto Cleanup; hr = THR(UpdateTextID(&mkpend)); if( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::deleteData (long loffset, long lCount) { HRESULT hr = S_OK; CMarkupPointer mkpStart (_pDoc); CMarkupPointer mkpend (_pDoc); if( !lCount ) goto Cleanup; if( loffset < 0 || lCount < 0 ) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(MoveToOffset(loffset, &mkpStart, &mkpend)); if ( hr ) goto Cleanup; hr = THR(RemoveTextHelper(&mkpStart, lCount, loffset)); if ( hr ) goto Cleanup; _pMkpPtr->SetGravity(POINTER_GRAVITY_Right); hr = THR(UpdateTextID(&mkpend)); if( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::replaceData (long loffset, long lCount, BSTR bstrstring) { HRESULT hr = S_OK; CMarkupPointer mkpStart (_pDoc); CMarkupPointer mkpend (_pDoc); if( loffset < 0 || lCount < 0 ) goto Cleanup; hr = THR(MoveToOffset(loffset, &mkpStart, &mkpend)); if ( hr ) goto Cleanup; hr = THR(RemoveTextHelper(&mkpStart, lCount, loffset)); if ( hr ) goto Cleanup; hr = THR(InsertTextHelper(&mkpStart, bstrstring, loffset)); if( hr ) goto Cleanup; hr = THR(UpdateTextID(&mkpend)); if( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDOMTextNode::get_ownerDocument(IDispatch **ppretdoc) { return OwnerDocHelper(ppretdoc, this, NULL); } HRESULT CDOMTextNode::TearoffTextNode(CMarkupPointer *pMkpStart, CMarkupPointer *pMkpEnd) { HRESULT hr = S_OK; CMarkup *pMarkup = NULL; CMarkupPointer mkpEndPtr(_pDoc); hr = THR(_pDoc->CreateMarkup(&pMarkup, GetWindowedMarkupContext())); if (hr) goto Cleanup; hr = THR(pMarkup->SetOrphanedMarkup(TRUE)); if (hr) goto Cleanup; hr = THR(mkpEndPtr.MoveToContainer(pMarkup, TRUE)); if (hr) goto Cleanup; mkpEndPtr.SetGravity(POINTER_GRAVITY_Right); // should have right gravity, which with cling will move it also along with text Assert(_pMkpPtr->Gravity()); Assert(_pMkpPtr->Cling()); Assert(!pMkpEnd->Cling()); hr = THR(_pDoc->Move(_pMkpPtr, pMkpEnd, &mkpEndPtr, MUS_DOMOPERATION)); if (hr) goto Cleanup; Assert(!pMkpStart->Gravity()); Assert(pMkpStart->IsEqualTo(pMkpEnd)); Assert(_pMkpPtr->IsLeftOf(&mkpEndPtr)); pMkpEnd->SetGravity(POINTER_GRAVITY_Right); Assert(_pMkpPtr->Gravity()); Assert(_pMkpPtr->Cling()); hr = THR(_pDoc->Copy(_pMkpPtr, &mkpEndPtr, pMkpEnd, MUS_DOMOPERATION)); if (hr) goto Cleanup; Assert(pMkpStart->IsLeftOf(pMkpEnd)); Cleanup: ReleaseInterface((IUnknown*)pMarkup); // Text node addref'ed it RRETURN(hr); } //////////////////////////////////////////////////////////////////////////////// // // IHTMLDOMAttribute methods: // //////////////////////////////////////////////////////////////////////////////// MtDefine(CAttribute, ObjectModel, "CAttribute") //+---------------------------------------------------------------- // // member : classdesc // //+---------------------------------------------------------------- const CBase::CLASSDESC CAttribute::s_classdesc = { &CLSID_HTMLDOMAttribute, // _pclsid 0, // _idrBase #ifndef NO_PROPERTY_PAGE NULL, // _apClsidPages #endif // NO_PROPERTY_PAGE NULL, // _pcpi 0, // _dwFlags &IID_IHTMLDOMAttribute, // _piidDispinterface &s_apHdlDescs, // _apHdlDesc }; CAttribute::CAttribute(const PROPERTYDESC *pPropDesc, DISPID dispid, CElement *pElem, CDocument *pDocument) { _pPropDesc = pPropDesc; _dispid = dispid; _pElem = pElem; if (pElem) pElem->SubAddRef(); _pDocument = pDocument; if (_pDocument) { _pDocument->SubAddRef(); _pMarkup = pDocument->Markup(); } if (_pMarkup) _pMarkup->SubAddRef(); } CAttribute::~CAttribute() { if(_pElem) _pElem->SubRelease(); if(_pMarkup) _pMarkup->SubRelease(); if(_pDocument) _pDocument->SubRelease(); } HRESULT CAttribute::PrivateQueryInterface(REFIID iid, void **ppv) { *ppv = NULL; switch (iid.Data1) { QI_INHERITS((IPrivateUnknown *)this, IUnknown) QI_TEAROFF_DISPEX(this, NULL) QI_TEAROFF(this, IHTMLDOMAttribute, NULL) QI_TEAROFF(this, IHTMLDOMAttribute2, NULL) default: if (iid == CLSID_CAttribute) { *ppv = this; // Weak ref return S_OK; } } if (*ppv) { ((IUnknown*)*ppv)->AddRef(); return S_OK; } return E_NOINTERFACE; } // // Attribute helpers // static HRESULT GetIndexHelper(LPTSTR pchName, AAINDEX *paaIdx, AAINDEX *pvaaIdx, DISPID *pdispid, PROPERTYDESC **ppPropDesc, CElement *pElement, DWORD dwFlags) { HRESULT hr = S_OK; Assert(pchName && paaIdx && pdispid && ppPropDesc && pElement); *ppPropDesc = (PROPERTYDESC *)pElement->FindPropDescForName(pchName); if(!*ppPropDesc) { hr = THR(pElement->GetExpandoDISPID(pchName, pdispid, dwFlags)); if (hr) goto Cleanup; } else { *pdispid = (*ppPropDesc)->GetDispid(); } Assert(*pdispid); *paaIdx = pElement->FindAAIndex(*pdispid, CAttrValue::AA_DOMAttribute); if (pvaaIdx) *pvaaIdx = pElement->FindAAIndex(*pdispid, *ppPropDesc ? CAttrValue::AA_Attribute : CAttrValue::AA_Expando); Cleanup: RRETURN(hr); } static HRESULT PutNodeValueHelper(CAttribute *pAttribute, AAINDEX aaIdx, VARIANT varValue) { HRESULT hr; Assert(pAttribute); Assert(pAttribute->_pElem); if (pAttribute->_pPropDesc) { DISPPARAMS dp; dp.rgvarg = &varValue; dp.rgdispidNamedArgs = NULL; dp.cArgs = 1; dp.cNamedArgs = 0; hr = THR(pAttribute->_pElem->Invoke(pAttribute->_dispid, IID_NULL, g_lcidUserDefault, DISPATCH_PROPERTYPUT, &dp, NULL, NULL, NULL)); if (hr) goto Cleanup; } else { Assert(pAttribute->_dispid != DISPID_UNKNOWN); Assert(pAttribute->_pElem->IsExpandoDISPID(pAttribute->_dispid)); if (aaIdx == AA_IDX_UNKNOWN) { hr = THR(CAttrArray::Set(pAttribute->_pElem->GetAttrArray(), pAttribute->_dispid, &varValue, NULL, CAttrValue::AA_Expando)); } else { CAttrArray *pAA = *pAttribute->_pElem->GetAttrArray(); Assert(pAA && aaIdx == pAttribute->_pElem->FindAAIndex(pAttribute->_dispid, CAttrValue::AA_Expando)); hr = THR(pAA->SetAt(aaIdx, &varValue)); } if (hr) goto Cleanup; } Cleanup: RRETURN(hr); } static HRESULT GetNodeValueHelper(CAttribute *pAttribute, AAINDEX aaIdx, VARIANT *pvarValue) { HRESULT hr = E_FAIL; Assert(pAttribute); Assert(pAttribute->_pElem); if (pAttribute->_pPropDesc) { if (!(pAttribute->_pPropDesc->GetPPFlags() & PROPPARAM_SCRIPTLET)) { DISPPARAMS dp = { NULL, NULL, 0, 0 }; hr = THR (pAttribute->_pElem->Invoke(pAttribute->_dispid, IID_NULL, g_lcidUserDefault, DISPATCH_PROPERTYGET, &dp, pvarValue, NULL, NULL)); } if (hr) { if (aaIdx == AA_IDX_UNKNOWN) aaIdx = pAttribute->_pElem->FindAAIndex(pAttribute->_dispid, CAttrValue::AA_Attribute); else Assert(aaIdx == pAttribute->_pElem->FindAAIndex(pAttribute->_dispid, CAttrValue::AA_Attribute)); hr = THR(pAttribute->_pElem->GetVariantAt(aaIdx, pvarValue)); if (hr) goto Cleanup; } } else { Assert(pAttribute->_dispid != DISPID_UNKNOWN); Assert(pAttribute->_pElem->IsExpandoDISPID(pAttribute->_dispid)); if (aaIdx == AA_IDX_UNKNOWN) aaIdx = pAttribute->_pElem->FindAAIndex(pAttribute->_dispid, CAttrValue::AA_Expando); else Assert(aaIdx == pAttribute->_pElem->FindAAIndex(pAttribute->_dispid, CAttrValue::AA_Expando)); Assert(aaIdx != AA_IDX_UNKNOWN); hr = THR(pAttribute->_pElem->GetVariantAt(aaIdx, pvarValue)); if (hr) goto Cleanup; } Cleanup: RRETURN(hr); } static HRESULT RemoveAttrHelper(LPTSTR pchAttrName, PROPERTYDESC **ppPropDesc, DISPID *pdispid, AAINDEX *paaIdx, AAINDEX *pvaaIdx, CElement *pElement, IHTMLDOMAttribute **ppAttribute, DWORD dwFlags) { HRESULT hr; CAttribute *pretAttr = NULL; Assert(pchAttrName && paaIdx && pvaaIdx && pdispid && ppPropDesc && pElement && ppAttribute); hr = THR(GetIndexHelper(pchAttrName, paaIdx, pvaaIdx, pdispid, ppPropDesc, pElement, dwFlags)); if (hr) goto Cleanup; if (*paaIdx == AA_IDX_UNKNOWN) { if (*pvaaIdx != AA_IDX_UNKNOWN) { // No Attr Node of same name as pAttr exists, but there exists an attr value, // create new node for returning to caller pretAttr = new CAttribute(NULL, DISPID_UNKNOWN, NULL); if (!pretAttr) { hr = E_OUTOFMEMORY; goto Cleanup; } pretAttr->_cstrName.Set(pchAttrName); Assert(pretAttr->_varValue.IsEmpty()); //NOTE: may need to get invoked value here for defaults etc. hr = THR(pElement->GetVariantAt(*pvaaIdx, &pretAttr->_varValue)); if (hr) goto Cleanup; } } else { // Attr Node of same name as pAttr already exists, just return it. IUnknown *pUnk; hr = THR(pElement->GetUnknownObjectAt(*paaIdx, &pUnk)); if (hr) goto Cleanup; pretAttr = (CAttribute *)pUnk; Assert(pretAttr); Assert(pretAttr->_varValue.IsEmpty()); hr = THR(GetNodeValueHelper(pretAttr, *pvaaIdx, &pretAttr->_varValue)); if (hr) goto Cleanup; } if (pretAttr) { if (pretAttr->_pElem) { pretAttr->_pElem->SubRelease(); pretAttr->_pElem = NULL; pretAttr->_pPropDesc = NULL; pretAttr->_dispid = DISPID_UNKNOWN; } Assert(!pretAttr->_pPropDesc); Assert(pretAttr->_dispid == DISPID_UNKNOWN); hr = THR(pretAttr->PrivateQueryInterface(IID_IHTMLDOMAttribute, (void **)ppAttribute)); pretAttr->Release(); if (hr) goto Cleanup; } Cleanup: RRETURN(hr); } void CBase::RemoveDOMAttrNode(DISPID dispid) { Assert(IsExpandoDISPID(dispid)); AAINDEX aaIdx = FindAAIndex(dispid, CAttrValue::AA_DOMAttribute); if (aaIdx != AA_IDX_UNKNOWN) { IUnknown *pUnk; CAttribute *pAttr; IGNORE_HR(GetUnknownObjectAt(aaIdx, &pUnk)); pAttr = (CAttribute *)pUnk; if (pAttr) { Assert(pAttr->_varValue.IsEmpty()); Assert(pAttr->_pElem); IGNORE_HR(GetNodeValueHelper(pAttr, AA_IDX_UNKNOWN, &pAttr->_varValue)); pAttr->_pElem->SubRelease(); pAttr->_pElem = NULL; pAttr->_pPropDesc = NULL; pAttr->_dispid = DISPID_UNKNOWN; pAttr->Release(); } DeleteAt(aaIdx); } } HRESULT CBase::UpdateDomAttrCollection(BOOL fDelete, DISPID dispid) { HRESULT hr = S_OK; AAINDEX collIdx; CAttrCollectionator *pAttrCollator = NULL; Assert(IsExpandoDISPID(dispid)); collIdx = _pAA->FindAAIndex(DISPID_INTERNAL_CATTRIBUTECOLLPTRCACHE, CAttrValue::AA_Internal); if (collIdx != AA_IDX_UNKNOWN) { hr = THR(GetPointerAt(collIdx, (void **)&pAttrCollator)); if (hr) goto Cleanup; if (!fDelete) { CAttrCollectionator::AttrDesc ad; ad._pPropdesc = NULL; ad._dispid = dispid; hr = THR(pAttrCollator->_aryAttrDescs.AppendIndirect(&ad)); if (hr) goto Cleanup; } else { long i; for (i = pAttrCollator->_lexpandoStartIndex; i < pAttrCollator->_aryAttrDescs.Size(); i++) { if (dispid == pAttrCollator->_aryAttrDescs[i]._dispid) { pAttrCollator->_aryAttrDescs.Delete(i); break; } } } } Cleanup: RRETURN(hr); } HRESULT CAttribute::get_nodeName(BSTR *pbstrName) { HRESULT hr = E_POINTER; if (!pbstrName) goto Cleanup; *pbstrName = NULL; Assert((LPTSTR)_cstrName); hr = THR(_cstrName.AllocBSTR(pbstrName)); if (hr) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::get_nodeValue(VARIANT *pvarValue) { HRESULT hr = E_POINTER; if (!pvarValue) goto Cleanup; Assert((LPTSTR)_cstrName); if (!_pElem) { // Ether Attribuite Node Assert(_dispid == DISPID_UNKNOWN); Assert(!_pPropDesc); hr = THR(VariantCopy(pvarValue, &_varValue)); if (hr) goto Cleanup; } else { hr = THR(GetNodeValueHelper(this, AA_IDX_UNKNOWN, pvarValue)); if (hr) goto Cleanup; } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::put_nodeValue(VARIANT varValue) { HRESULT hr; Assert((LPTSTR)_cstrName); if (!_pElem) { // Ether Attribuite Node Assert(_dispid == DISPID_UNKNOWN); Assert(!_pPropDesc); hr = THR(_varValue.Copy(&varValue)); if (hr) goto Cleanup; } else { hr = THR(PutNodeValueHelper(this, AA_IDX_UNKNOWN, varValue)); if (hr) goto Cleanup; } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::get_specified(VARIANT_BOOL *pbSpecified) { HRESULT hr = S_OK; CAttrValue::AATYPE aaType; AAINDEX aaIdx; Assert((LPTSTR)_cstrName); if (!pbSpecified) { hr = E_POINTER; goto Cleanup; } if (!_pElem) { // Ether Attribuite Node Assert(_dispid == DISPID_UNKNOWN); Assert(!_pPropDesc); *pbSpecified = VB_FALSE; goto Cleanup; } aaType = _pPropDesc ? CAttrValue::AA_Attribute : CAttrValue::AA_Expando; // not there in AA aaIdx = _pElem->FindAAIndex((_dispid == DISPID_CElement_style_Str) ? DISPID_INTERNAL_INLINESTYLEAA : _dispid, (_dispid == DISPID_CElement_style_Str) ? CAttrValue::AA_AttrArray : aaType); if (_dispid == DISPID_CElement_style_Str && aaIdx != AA_IDX_UNKNOWN) { if (!_pElem->GetAttrValueAt(aaIdx)->GetAA()->HasAnyAttribute(TRUE)) aaIdx = AA_IDX_UNKNOWN; } *pbSpecified = (aaIdx == AA_IDX_UNKNOWN) ? VARIANT_FALSE : VARIANT_TRUE; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::get_name(BSTR *pbstrName) { return get_nodeName(pbstrName); } HRESULT CAttribute::get_value(BSTR *pbstrvalue) { HRESULT hr; CVariant varValue; VARIANT varRet; if (!pbstrvalue) { hr = E_POINTER; goto Cleanup; } hr = THR(get_nodeValue(&varValue)); if (hr) goto Cleanup; VariantInit(&varRet); // TODO: Need to handle style properly hr = THR(VariantChangeTypeSpecial(&varRet, &varValue, VT_BSTR)); if (hr) goto Cleanup; *pbstrvalue = V_BSTR(&varRet); Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::put_value(BSTR bstrvalue) { VARIANT varValue; V_VT(&varValue) = VT_BSTR; V_BSTR(&varValue) = bstrvalue; return put_nodeValue(varValue); } HRESULT CAttribute::get_expando(VARIANT_BOOL *pfIsExpando) { HRESULT hr = S_OK; if (!pfIsExpando) { hr = E_POINTER; goto Cleanup; } Assert((LPTSTR)_cstrName); Assert(!_pElem || _pPropDesc || _pElem->IsExpandoDISPID(_dispid)); *pfIsExpando = (!_pElem || _pPropDesc) ? VB_FALSE : VB_TRUE; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::get_nodeType(long *pnodeType) { HRESULT hr = S_OK; if (!pnodeType) { hr = E_POINTER; goto Cleanup; } *pnodeType = 2; // DOM_ATTRIBUTE Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::get_parentNode(IHTMLDOMNode **pparentNode) { if(pparentNode) *pparentNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::get_childNodes(IDispatch **ppChildCollection) { if(ppChildCollection) *ppChildCollection = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::get_firstChild ( IHTMLDOMNode **ppNode ) { if (ppNode) *ppNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::get_lastChild ( IHTMLDOMNode **ppNode ) { if (ppNode) *ppNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::get_previousSibling ( IHTMLDOMNode **ppNode ) { if (ppNode) *ppNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::get_nextSibling ( IHTMLDOMNode **ppNode ) { if (ppNode) *ppNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::get_attributes(IDispatch **ppAttrCollection) { if (ppAttrCollection) *ppAttrCollection = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::get_ownerDocument(IDispatch **ppretdoc) { HRESULT hr = S_OK; if(!ppretdoc) { hr = E_POINTER; goto Cleanup; } if(_pDocument) { hr = E_ACCESSDENIED; if ( _pMarkup && _pDocument->Markup() && _pMarkup->AccessAllowed(_pDocument->Markup())) { hr = THR(_pDocument->QueryInterface(IID_IDispatch, (void **)ppretdoc)); } goto Cleanup; } *ppretdoc = NULL; if(!_pElem) { hr = E_FAIL; goto Cleanup; } hr = THR(_pElem->get_ownerDocument(ppretdoc)); Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::insertBefore(IHTMLDOMNode *pNewChild, VARIANT refChild, IHTMLDOMNode **ppRetNode) { if (ppRetNode) *ppRetNode = NULL; // Don't expect this method to be called on a attribute node RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::replaceChild(IHTMLDOMNode *pNewChild, IHTMLDOMNode *pOldChild, IHTMLDOMNode **ppRetNode) { if (ppRetNode) *ppRetNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::removeChild(IHTMLDOMNode *pOldChild, IHTMLDOMNode **ppRetNode) { if (ppRetNode) *ppRetNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::appendChild(IHTMLDOMNode *pNewChild, IHTMLDOMNode **ppRetNode) { if (ppRetNode) *ppRetNode = NULL; RRETURN(SetErrorInfo(S_OK)); } HRESULT CAttribute::hasChildNodes(VARIANT_BOOL *p) { HRESULT hr = S_OK; if (!p) { hr = E_POINTER; goto Cleanup; } *p = VARIANT_FALSE; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CAttribute::cloneNode(VARIANT_BOOL fDeep, IHTMLDOMAttribute **ppNodeCloned) { HRESULT hr = S_OK; CDocument * pDocument; Assert((LPTSTR)_cstrName); if(!ppNodeCloned) { hr = E_POINTER; goto Cleanup; } *ppNodeCloned = NULL; if(_pElem) { IDispatch * pIDispDocument; hr = THR(_pElem->get_document(&pIDispDocument)); if(hr) goto Cleanup; hr = THR(pIDispDocument->QueryInterface(CLSID_CDocument, (void **) &pDocument)); pIDispDocument->Release(); if(hr) goto Cleanup; } else { Assert(_pDocument); pDocument = _pDocument; } hr = THR(pDocument->createAttribute(_cstrName, ppNodeCloned)); Cleanup: RRETURN(SetErrorInfo(hr)); } //////////////////////////////////////////////////////////////////////////////// // // IHTMLDOMNode methods: // //////////////////////////////////////////////////////////////////////////////// HRESULT CElement::get_nodeType(long *pnodeType) { HRESULT hr = S_OK; if (!pnodeType) { hr = E_POINTER; goto Cleanup; } if(Tag() != ETAG_RAW_COMMENT) *pnodeType = 1; // ELEMENT_NODE else *pnodeType = 8; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_nodeName(BSTR *pbstrNodeName) { HRESULT hr = S_OK; if(Tag() != ETAG_RAW_COMMENT) hr = THR(get_tagName ( pbstrNodeName )); else { if (!pbstrNodeName) { hr = E_POINTER; goto Cleanup; } *pbstrNodeName = NULL; hr = THR(FormsAllocString ( _T("#comment"), pbstrNodeName )); if ( hr ) goto Cleanup; } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_nodeValue(VARIANT *pvarValue) { HRESULT hr = S_OK; if (!pvarValue) { hr = E_POINTER; goto Cleanup; } if (Tag() != ETAG_RAW_COMMENT) pvarValue->vt = VT_NULL; else { VariantInit(pvarValue); pvarValue->vt = VT_BSTR; return DYNCAST(CCommentElement, this)->get_data(&V_BSTR(pvarValue)); } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::put_nodeValue(VARIANT varValue) { HRESULT hr = S_OK; if (Tag() == ETAG_RAW_COMMENT) { if (V_VT(&varValue) == VT_BSTR) { return DYNCAST(CCommentElement, this)->put_data(V_BSTR(&varValue)); } else hr = E_INVALIDARG; } RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_lastChild ( IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; CMarkupPointer markupWalk ( Doc() ); if (!ppNode) { hr = E_POINTER; goto Cleanup; } *ppNode = NULL; if (ETAG_OBJECT == Tag() || ETAG_APPLET == Tag()) { CObjectElement *pelObj = DYNCAST(CObjectElement, this); int c = pelObj->_aryParams.Size(); if (c) hr = THR(pelObj->_aryParams[c-1]->QueryInterface(IID_IHTMLDOMNode, (void **)ppNode)); goto Cleanup; // done } if ( IsNoScope() ) goto Cleanup; if ( !IsInMarkup() ) // Can just return NULL goto Cleanup; hr = THR(markupWalk.MoveAdjacentToElement( this, ELEM_ADJ_BeforeEnd)); if ( hr ) goto Cleanup; hr = THR(GetPreviousHelper ( Doc(), &markupWalk, ppNode )); if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_previousSibling ( IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; CMarkupPointer markupWalk ( Doc() ); if (!ppNode) { hr = E_POINTER; goto Cleanup; } *ppNode = NULL; if (ETAG_PARAM == Tag()) { CParamElement *pelParam = DYNCAST(CParamElement, this); CObjectElement *pelObj = pelParam->_pelObjParent; if (pelObj) { Assert(pelObj->_aryParams.Size() && pelParam->_idxParam != -1 && pelParam->_idxParam < pelObj->_aryParams.Size()); if (pelParam->_idxParam > 0) hr = THR(pelObj->_aryParams[pelParam->_idxParam-1]->QueryInterface(IID_IHTMLDOMNode, (void **)ppNode)); goto Cleanup; // done } } if ( !IsInMarkup() ) // Can just return NULL goto Cleanup; hr = THR( markupWalk.MoveAdjacentToElement( this, ELEM_ADJ_BeforeBegin)); if ( hr ) goto Cleanup; hr = THR(GetPreviousHelper ( Doc(), &markupWalk, ppNode )); if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_nextSibling ( IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; CMarkupPointer markupWalk ( Doc() ); if (!ppNode) { hr = E_POINTER; goto Cleanup; } *ppNode = NULL; if (ETAG_PARAM == Tag()) { CParamElement *pelParam = DYNCAST(CParamElement, this); CObjectElement *pelObj = pelParam->_pelObjParent; if (pelObj) { Assert(pelObj->_aryParams.Size() && pelParam->_idxParam != -1 && pelParam->_idxParam < pelObj->_aryParams.Size()); if (pelParam->_idxParam+1 < pelObj->_aryParams.Size()) hr = THR(pelObj->_aryParams[pelParam->_idxParam+1]->QueryInterface(IID_IHTMLDOMNode, (void **)ppNode)); goto Cleanup; // done } } if ( !IsInMarkup() ) // Can just return NULL goto Cleanup; hr = THR( markupWalk.MoveAdjacentToElement( this, ELEM_ADJ_AfterEnd)); if ( hr ) goto Cleanup; hr = THR(GetNextHelper ( Doc(), &markupWalk, ppNode )); Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_firstChild ( IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; CMarkupPointer markupWalk ( Doc() ); if (!ppNode) { hr = E_POINTER; goto Cleanup; } *ppNode = NULL; if (ETAG_OBJECT == Tag() || ETAG_APPLET == Tag()) { CObjectElement *pelObj = DYNCAST(CObjectElement, this); if (pelObj->_aryParams.Size()) hr = THR(pelObj->_aryParams[0]->QueryInterface(IID_IHTMLDOMNode, (void **)ppNode)); goto Cleanup; // done } if ( !IsInMarkup() ) // Can just return NULL goto Cleanup; if ( IsNoScope() ) goto Cleanup; hr = THR( markupWalk.MoveAdjacentToElement( this, ELEM_ADJ_AfterBegin)); if ( hr ) goto Cleanup; hr = THR(GetNextHelper ( Doc(), &markupWalk, ppNode )); Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_parentNode(IHTMLDOMNode **pparentNode) { HRESULT hr = S_OK; CTreeNode *pNode; if (!pparentNode) { hr = E_POINTER; goto Cleanup; } *pparentNode = NULL; pNode = GetFirstBranch(); if ( !pNode ) { if (ETAG_PARAM == Tag()) { CObjectElement *pelObj = DYNCAST(CParamElement, this)->_pelObjParent; if (pelObj) hr = THR(pelObj->QueryInterface(IID_IHTMLDOMNode, (void **)pparentNode)); } goto Cleanup; } pNode = pNode->Parent(); hr = THR(ParentNodeHelper(pNode, pparentNode)); if( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::DOMWalkChildren ( long lWantItem, long *plCount, IDispatch **ppDispItem ) { HRESULT hr = S_OK; CMarkupPointer markupWalk (Doc()); CMarkupPointer markupWalkEnd (Doc()); CTreeNode *pnodeRight; MARKUP_CONTEXT_TYPE context; long lCount = 0; BOOL fWantItem = (lWantItem == -1 ) ? FALSE : TRUE; long lTextID; BOOL fDone = FALSE; if (ppDispItem) *ppDispItem = NULL; if (!IsInMarkup()) goto Cleanup; hr = THR( markupWalk.MoveAdjacentToElement( this, Tag() == ETAG_ROOT ? ELEM_ADJ_AfterBegin : ELEM_ADJ_BeforeBegin)); if ( hr ) goto Cleanup; hr = THR( markupWalkEnd.MoveAdjacentToElement( this, Tag() == ETAG_ROOT ? ELEM_ADJ_BeforeEnd : ELEM_ADJ_AfterEnd)); if ( hr ) goto Cleanup; do { hr = THR( markupWalk.Right( TRUE, &context, &pnodeRight, NULL, NULL, &lTextID)); if ( hr ) goto Cleanup; switch ( context ) { case CONTEXT_TYPE_None: fDone = TRUE; break; case CONTEXT_TYPE_ExitScope://don't care ... if ( pnodeRight->Element() == this ) goto NotFound; break; case CONTEXT_TYPE_EnterScope: if ( pnodeRight->Element() != this ) { // Add to our child list lCount++; // Go to the end of this element, since we will handle it as a container hr = THR( markupWalk.MoveAdjacentToElement( pnodeRight->Element(), ELEM_ADJ_AfterEnd)); if ( hr ) goto Cleanup; // Need to test we haven't left the scope of my parent. // Overlapping could cause us to move outside if ( markupWalkEnd.IsLeftOf( & markupWalk ) ) { fDone = TRUE; } } break; case CONTEXT_TYPE_Text: lCount++; break; case CONTEXT_TYPE_NoScope: if ( pnodeRight->Element() == this ) { // Left scope of current noscope element goto NotFound; } else { // Add to our child list lCount++; } break; } if (fWantItem && (lCount-1 == lWantItem )) { // Found the item we're looking for if ( !ppDispItem ) goto Cleanup; // Didn't want an item, just validating index if ( context == CONTEXT_TYPE_Text ) { // Text Node CDOMTextNode *pTextNode = NULL; hr = THR(CreateTextNode (Doc(), &markupWalk, lTextID, &pTextNode )); if ( hr ) goto Cleanup; hr = THR ( pTextNode->QueryInterface ( IID_IDispatch, (void **)ppDispItem ) ); if ( hr ) goto Cleanup; pTextNode->Release(); } else { // Return Disp to Element hr = THR(pnodeRight->GetElementInterface ( IID_IDispatch, (void **) ppDispItem )); if ( hr ) goto Cleanup; } goto Cleanup; } // else just looking for count } while( !fDone ); NotFound: if ( fWantItem ) { // Didn't find it - index must be beyond range hr = E_INVALIDARG; } Cleanup: if ( plCount ) *plCount = lCount; return hr; } HRESULT CElement::hasChildNodes(VARIANT_BOOL *p) { HRESULT hr = S_OK; if (!p) goto Cleanup; if (Tag() == ETAG_OBJECT || Tag() == ETAG_APPLET) { *p = DYNCAST(CObjectElement, this)->_aryParams.Size() ? VARIANT_TRUE : VARIANT_FALSE; goto Cleanup; } *p = VARIANT_FALSE; if ( !IsInMarkup() ) // Can just return FALSE goto Cleanup; // See if we have a child at Index == 0 hr = THR( DOMWalkChildren ( 0, NULL, NULL )); if ( hr == E_INVALIDARG ) { // Invalid Index hr = S_OK; goto Cleanup; } else if ( hr ) goto Cleanup; *p = VARIANT_TRUE; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_childNodes(IDispatch **ppChildCollection) { HRESULT hr = S_OK; CDOMChildrenCollection *pChildren; if ( !ppChildCollection ) goto Cleanup; *ppChildCollection = NULL; pChildren = EnsureDOMChildrenCollectionPtr(); if ( !pChildren ) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR(pChildren->QueryInterface (IID_IDispatch,(void **)ppChildCollection)); if ( hr ) goto Cleanup; pChildren->Release(); // Lifetime is controlled by extrenal ref. Cleanup: RRETURN(SetErrorInfo(hr)); } CAttrCollectionator * CElement::EnsureAttributeCollectionPtr ( ) { HRESULT hr = S_OK; CAttrCollectionator *pAttrCollator = NULL; IGNORE_HR(GetPointerAt(FindAAIndex(DISPID_INTERNAL_CATTRIBUTECOLLPTRCACHE, CAttrValue::AA_Internal), (void **)&pAttrCollator)); if (!pAttrCollator) { pAttrCollator = new CAttrCollectionator(this); if (pAttrCollator) { pAttrCollator->EnsureCollection(); hr = THR(AddPointer(DISPID_INTERNAL_CATTRIBUTECOLLPTRCACHE, (void *)pAttrCollator, CAttrValue::AA_Internal )); if (hr) goto Cleanup; } } else { pAttrCollator->AddRef(); } Cleanup: return pAttrCollator; } HRESULT CElement::get_attributes(IDispatch **ppAttrCollection) { HRESULT hr = S_OK; CAttrCollectionator *pAttrCollator = NULL; if (!ppAttrCollection) { hr = E_POINTER; goto Cleanup; } *ppAttrCollection = NULL; if(Tag() == ETAG_RAW_COMMENT) // Comment tags should return NULL according to spec goto Cleanup; pAttrCollator = EnsureAttributeCollectionPtr(); if ( !pAttrCollator ) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR(pAttrCollator->QueryInterface(IID_IDispatch, (void **)ppAttrCollection)); if ( hr ) goto Cleanup; Cleanup: if (pAttrCollator) pAttrCollator->Release(); RRETURN(SetErrorInfo(hr)); } HRESULT CElement::GetDOMInsertPosition ( CElement *pRefElement, CDOMTextNode *pRefTextNode, CMarkupPointer *pmkptrPos ) { HRESULT hr = S_OK; if ( !pRefElement && !pRefTextNode ) { // As per DOM spec, if refChild is NULL Insert at end of child list // but only if the elem into which it is to be inserted can have children! if (IsNoScope()) { hr = E_UNEXPECTED; goto Cleanup; } hr = THR(EnsureInMarkup()); if ( hr ) goto Cleanup; hr = THR(pmkptrPos->MoveAdjacentToElement ( this, ELEM_ADJ_BeforeEnd )); } else { hr = GetDOMInsertHelper (pRefElement, pRefTextNode, pmkptrPos ); } Cleanup: RRETURN(hr); } HRESULT CElement::appendChild(IHTMLDOMNode *pNewChild, IHTMLDOMNode **ppRetNode) { CVariant varEmpty(VT_NULL); return insertBefore ( pNewChild, *(VARIANT *)&varEmpty, ppRetNode ); } static BOOL IsChild(CElement *pelParent, CElement *pelChild, CDOMTextNode *pTextNode) { Assert(pelParent); Assert(!pelChild || !pTextNode); if (pelChild) { if ((pelParent->Tag() == ETAG_OBJECT || pelParent->Tag() == ETAG_APPLET) && pelChild->Tag() == ETAG_PARAM) { CParamElement *pelParam = DYNCAST(CParamElement, pelChild); Assert((pelParam->_pelObjParent != pelParent) || (pelParent->Tag() == ETAG_OBJECT) || (pelParent->Tag() == ETAG_APPLET)); return (pelParam->_pelObjParent == pelParent); } CTreeNode *pNode = pelChild->GetFirstBranch(); if (!pNode || !pNode->Parent() || (pNode->Parent()->Element() != pelParent)) return FALSE; } else if (pTextNode) { CElement *pelTxtNodeParent = NULL; IHTMLElement *pITxtNodeParent = NULL; Assert(pTextNode->MarkupPtr()); Assert(pTextNode->MarkupPtr()->Cling()); // Must have Glue! Assert(pTextNode->MarkupPtr()->Gravity()); // Must have right gravity. CurrentScope(pTextNode->MarkupPtr(), &pITxtNodeParent, NULL); if (pITxtNodeParent) pITxtNodeParent->QueryInterface(CLSID_CElement, (void **)&pelTxtNodeParent); ReleaseInterface(pITxtNodeParent); if (pelTxtNodeParent != pelParent) return FALSE; } return TRUE; } HRESULT CElement::insertBefore(IHTMLDOMNode *pNewChild, VARIANT refChild, IHTMLDOMNode **ppRetNode) { HRESULT hr; CElement * pRefElement = NULL; CDOMTextNode * pRefTextNode = NULL; CElement * pNewElement = NULL; CDOMTextNode * pNewTextNode = NULL; CDoc * pDoc = Doc(); CMarkupPointer mkpPtr (pDoc); if (!pNewChild) { hr = E_POINTER; goto Cleanup; } hr = THR(CrackDOMNodeVARIANT(&refChild, &pRefTextNode, &pRefElement, GetWindowedMarkupContext())); if (hr) goto Cleanup; hr = THR(CrackDOMNode((IUnknown*)pNewChild, &pNewTextNode, &pNewElement, GetWindowedMarkupContext())); if (hr) goto Cleanup; Assert(IsRootOnlyIfDocument(pNewChild, pNewElement)); if (!IsChild(this, pRefElement, pRefTextNode)) { hr = E_INVALIDARG; goto Cleanup; } if (pNewElement && (Tag() == ETAG_OBJECT || Tag() == ETAG_APPLET)) { Assert(!pRefElement || pRefElement->Tag() == ETAG_PARAM); CObjectElement *pelObj = DYNCAST(CObjectElement, this); hr = THR(pelObj->AddParam(pNewElement, pRefElement)); } else { // Position ourselves in the right spot hr = THR(GetDOMInsertPosition(pRefElement, pRefTextNode, &mkpPtr)); if (hr) goto Cleanup; // Now mkpPtr is Positioned at the insertion point, insert the new content hr = THR(InsertDOMNodeHelper(pNewElement, pNewTextNode, &mkpPtr)); } if (hr) goto Cleanup; if (ppRetNode) hr = THR(pNewChild->QueryInterface(IID_IHTMLDOMNode, (void**)ppRetNode)); Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::replaceChild(IHTMLDOMNode *pNewChild, IHTMLDOMNode *pOldChild, IHTMLDOMNode **pRetNode) { HRESULT hr; CElement * pOldElement = NULL; CDOMTextNode * pOldTextNode = NULL; CElement * pNewElement = NULL; CDOMTextNode * pNewTextNode = NULL; CDoc * pDoc = Doc(); CMarkupPointer mkpPtr(pDoc); // Pull pOldChild, and all its contents, out of the tree, into its own tree // replace it with pNewChild, and all its contents if (!pNewChild || !pOldChild) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(CrackDOMNode((IUnknown*)pOldChild, &pOldTextNode, &pOldElement, GetWindowedMarkupContext() )); if ( hr ) goto Cleanup; hr = THR(CrackDOMNode((IUnknown*)pNewChild, &pNewTextNode, &pNewElement, GetWindowedMarkupContext() )); if ( hr ) goto Cleanup; Assert(IsRootOnlyIfDocument(pNewChild, pNewElement)); if (!IsChild(this, pOldElement, pOldTextNode)) { hr = E_INVALIDARG; goto Cleanup; } if (Tag() == ETAG_OBJECT || Tag() == ETAG_APPLET) { CObjectElement *pelObj = DYNCAST(CObjectElement, this); if (pNewElement && pOldElement) { Assert(pOldElement->Tag() == ETAG_PARAM); hr = THR(pelObj->ReplaceParam(pNewElement, pOldElement)); if (hr) goto Cleanup; // Return the node being replaced if (pRetNode) hr = THR(pOldChild->QueryInterface(IID_IHTMLDOMNode, (void**)pRetNode)); goto Cleanup; // done } } // Position ourselves in the right spot hr = THR(GetDOMInsertPosition ( pOldElement, pOldTextNode, &mkpPtr )); if ( hr ) goto Cleanup; mkpPtr.SetGravity ( POINTER_GRAVITY_Left ); { // Lock the markup, to prevent it from going away in case the entire contents are being removed. CMarkup::CLock MarkupLock(mkpPtr.Markup()); hr = THR(RemoveDOMNodeHelper ( pDoc, pOldElement, pOldTextNode )); if ( hr ) goto Cleanup; // Now mkpPtr is Positioned at the insertion point, insert the new content hr = THR(InsertDOMNodeHelper( pNewElement, pNewTextNode, &mkpPtr )); if ( hr ) goto Cleanup; // Return the node being replaced if ( pRetNode ) hr = THR(pOldChild->QueryInterface ( IID_IHTMLDOMNode, (void**)pRetNode)); } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::removeChild(IHTMLDOMNode *pOldChild, IHTMLDOMNode **pRetNode) { HRESULT hr; CDOMTextNode *pChildTextNode = NULL; CElement *pChildElement = NULL; CDoc *pDoc = Doc(); // Remove the child from the tree, putting it in its own tree if ( !pOldChild ) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(CrackDOMNode((IUnknown*)pOldChild, &pChildTextNode, &pChildElement, GetWindowedMarkupContext() )); if ( hr ) goto Cleanup; if (!IsChild(this, pChildElement, pChildTextNode)) { hr = E_INVALIDARG; goto Cleanup; } if (pChildElement && (Tag() == ETAG_OBJECT || Tag() == ETAG_APPLET)) { Assert(pChildElement->Tag() == ETAG_PARAM); CObjectElement *pelObj = DYNCAST(CObjectElement, this); hr = THR(pelObj->RemoveParam(pChildElement)); } else hr = THR(RemoveDOMNodeHelper(pDoc, pChildElement, pChildTextNode)); if ( hr ) goto Cleanup; // Return the node being removed if ( pRetNode ) hr = THR(pOldChild->QueryInterface ( IID_IHTMLDOMNode, (void**)pRetNode)); Cleanup: RRETURN(SetErrorInfo(hr)); } // // IHTMLDocument3 DOM methods // HRESULT CDoc::CreateDOMTextNodeHelper ( CMarkupPointer *pmkpStart, CMarkupPointer *pmkpEnd, IHTMLDOMNode **ppTextNode) { HRESULT hr; long lTextID; CDOMTextNode *pTextNode; // ID it hr = THR(pmkpStart->SetTextIdentity( pmkpEnd, &lTextID )); if ( hr ) goto Cleanup; // set right gravity so that an adjacent text node's markup ptr can never // move accidentally. hr = THR(pmkpStart->SetGravity ( POINTER_GRAVITY_Right )); if (hr) goto Cleanup; // Text Node takes ownership of pmkpStart pTextNode = new CDOMTextNode ( lTextID, this, pmkpStart ); // AddRef's the Markup if ( !pTextNode ) { hr = E_OUTOFMEMORY; goto Cleanup; } if ( ppTextNode ) { hr = THR(pTextNode->QueryInterface ( IID_IHTMLDOMNode, (void**)ppTextNode )); if ( hr ) goto Cleanup; } pTextNode->Release(); // Creating AddREf'd it once - refcount owned by external AddRef hr = THR(_HtPvPvDOMTextNodes.Insert ( (void*)(DWORD_PTR)(lTextID<<4), (void*)pTextNode ) ); if ( hr ) goto Cleanup; Cleanup: RRETURN(hr); } // // IE5 XOM. Extensions for document construction // HRESULT CElement::GetMarkupPtrRange(CMarkupPointer *pmkptrStart, CMarkupPointer *pmkptrEnd, BOOL fEnsureMarkup) { HRESULT hr; Assert(pmkptrStart); Assert(pmkptrEnd); if (fEnsureMarkup) { hr = THR(EnsureInMarkup()); if (hr) goto Cleanup; } hr = THR(pmkptrStart->MoveAdjacentToElement(this, Tag() == ETAG_ROOT? ELEM_ADJ_AfterBegin : ELEM_ADJ_BeforeBegin)); if (hr) goto Cleanup; hr = THR(pmkptrEnd->MoveAdjacentToElement(this, Tag() == ETAG_ROOT? ELEM_ADJ_BeforeEnd : ELEM_ADJ_AfterEnd)); Cleanup: return hr; } HRESULT CElement::cloneNode(VARIANT_BOOL fDeep, IHTMLDOMNode **ppNodeCloned) { HRESULT hr = E_OUTOFMEMORY; CDoc * pDoc = Doc(); CMarkup * pMarkupTarget = NULL; CElement * pElement = NULL; CTreeNode * pNode; if ( !ppNodeCloned || Tag() == ETAG_ROOT ) { hr = E_INVALIDARG; goto Cleanup; } *ppNodeCloned = NULL; if (!fDeep || !IsInMarkup() || IsNoScope()) { hr = THR(Clone(&pElement, pDoc)); if (hr) goto Cleanup; hr = THR(pElement->PrivateQueryInterface(IID_IHTMLDOMNode, (void **)ppNodeCloned)); if (hr) goto Cleanup; pElement->Release(); Assert(Tag() != ETAG_PARAM || (!(DYNCAST(CParamElement, pElement)->_pelObjParent) && DYNCAST(CParamElement, this)->_pelObjParent)); if (fDeep && (Tag() == ETAG_OBJECT || Tag() == ETAG_APPLET)) { CParamElement *pelParamClone; CObjectElement *pelObj = DYNCAST(CObjectElement, this); CObjectElement *pelObjClone = DYNCAST(CObjectElement, pElement); Assert(pelObjClone->_aryParams.Size() == 0); for (int i = 0; i < pelObj->_aryParams.Size(); i++) { Assert(pelObj->_aryParams[i] && pelObj->_aryParams[i]->Tag() == ETAG_PARAM); hr = THR(pelObj->_aryParams[i]->Clone((CElement **)&pelParamClone, pDoc)); if (hr) goto Cleanup; Assert(pelParamClone->_idxParam == -1); Assert(!pelParamClone->_pelObjParent); hr = THR(pelObjClone->AddParam(pelParamClone, NULL)); if (hr) goto Cleanup; Assert(pelParamClone->_idxParam == i); Assert(pelParamClone->_pelObjParent == pelObjClone); pelParamClone->Release(); Assert(pelParamClone->GetObjectRefs());; } Assert(pelObj->_aryParams.Size() == pelObjClone->_aryParams.Size()); } } else { CMarkupPointer mkptrStart ( pDoc ); CMarkupPointer mkptrEnd ( pDoc ); CMarkupPointer mkptrTarget ( pDoc ); // Get src ptrs hr = THR(GetMarkupPtrRange(&mkptrStart, &mkptrEnd)); if (hr) goto Cleanup; // create new markup hr = THR(pDoc->CreateMarkup(&pMarkupTarget, GetWindowedMarkupContext())); if (hr) goto Cleanup; hr = THR( pMarkupTarget->SetOrphanedMarkup( TRUE ) ); if( hr ) goto Cleanup; // Get target ptr hr = THR(mkptrTarget.MoveToContainer(pMarkupTarget,TRUE)); if (hr) goto Cleanup; // Copy src -> target hr = THR(pDoc->Copy(&mkptrStart, &mkptrEnd, &mkptrTarget, MUS_DOMOPERATION)); if (hr) goto Cleanup; // This addrefs the markup too! // Go Right to pick up the new node ptr hr = THR(mkptrTarget.Right(FALSE, NULL, &pNode, 0, NULL,NULL)); if (hr) goto Cleanup; hr = THR(pNode->Element()->PrivateQueryInterface(IID_IHTMLDOMNode, (void **)ppNodeCloned)); if (hr) goto Cleanup; } Cleanup: // release extra markup lock if (pMarkupTarget) pMarkupTarget->Release(); RRETURN(SetErrorInfo(hr)); } // Surgicaly remove pElemApply out of its current context, // Apply it over this element HRESULT CElement::applyElement(IHTMLElement *pElemApply, BSTR bstrWhere, IHTMLElement **ppElementApplied) { HRESULT hr; CDoc *pDoc = Doc(); CMarkupPointer mkptrStart(pDoc); CMarkupPointer mkptrEnd (pDoc); CElement *pElement; htmlApplyLocation where = htmlApplyLocationOutside; if ( ppElementApplied ) *ppElementApplied = NULL; if ( !pElemApply ) { hr = E_INVALIDARG; goto Cleanup; } if (!pDoc->IsOwnerOf(pElemApply)) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(pElemApply->QueryInterface ( CLSID_CElement, (void**) &pElement )); if (hr) goto Cleanup; ENUMFROMSTRING(htmlApplyLocation, bstrWhere, (long *)&where); // No scoped elements cannot be applied as they cannot have children! // Nor can the root element, nor can you apply something outside a root if ( pElement->IsNoScope() || pElement->Tag() == ETAG_ROOT || ( Tag() == ETAG_ROOT && where == htmlApplyLocationOutside ) ) { hr = E_INVALIDARG; goto Cleanup; } // Get src ptrs hr = THR(EnsureInMarkup()); if (hr) goto Cleanup; hr = THR(mkptrStart.MoveAdjacentToElement(this, where ? ELEM_ADJ_BeforeBegin : ELEM_ADJ_AfterBegin)); if (hr) goto Cleanup; hr = THR(mkptrEnd.MoveAdjacentToElement(this, where ? ELEM_ADJ_AfterEnd : ELEM_ADJ_BeforeEnd)); if (hr) goto Cleanup; // Surgically remove the elem to be applied if in a markup. if (pElement->IsInMarkup()) { hr = THR(pDoc->RemoveElement(pElement, MUS_DOMOPERATION)); if ( hr ) goto Cleanup; } hr = THR(pDoc->InsertElement ( pElement, &mkptrStart, &mkptrEnd, MUS_DOMOPERATION )); if (hr) goto Cleanup; if ( ppElementApplied ) hr = THR(pElemApply->QueryInterface ( IID_IHTMLElement, (void**) ppElementApplied )); Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::removeNode (VARIANT_BOOL fDeep, IHTMLDOMNode **ppNodeRemoved) { HRESULT hr = S_OK; // Pull element out of the tree if ( ppNodeRemoved ) *ppNodeRemoved = NULL; Assert( Tag() != ETAG_ROOT ); if ( fDeep ) { hr = THR(RemoveDOMNodeHelper ( Doc(), this, NULL )); if ( hr ) goto Cleanup; } else if (IsInMarkup()) { // Surgical removal hr = THR(Doc()->RemoveElement ( this, MUS_DOMOPERATION ) ); if ( hr ) goto Cleanup; } if ( ppNodeRemoved ) { hr = THR(QueryInterface(IID_IHTMLDOMNode, (void**)ppNodeRemoved)); } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::replaceNode(IHTMLDOMNode *pNodeReplace, IHTMLDOMNode **ppNodeReplaced) { HRESULT hr; CDOMTextNode *pNewTextNode = NULL; CElement *pNewElement = NULL; CDoc *pDoc = Doc(); if ( ppNodeReplaced ) *ppNodeReplaced = NULL; Assert( Tag() != ETAG_ROOT ); if ( !pNodeReplace ) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(CrackDOMNode((IUnknown*)pNodeReplace, &pNewTextNode, &pNewElement, GetWindowedMarkupContext() )); if ( hr ) goto Cleanup; Assert(IsRootOnlyIfDocument(pNodeReplace, pNewElement)); hr = THR(ReplaceDOMNodeHelper ( pDoc, this, NULL, pNewElement, pNewTextNode )); if ( hr ) goto Cleanup; if ( ppNodeReplaced ) { hr = THR(QueryInterface(IID_IHTMLDOMNode, (void**)ppNodeReplaced)); } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::swapNode(IHTMLDOMNode *pNodeSwap, IHTMLDOMNode **ppNodeSwapped) { CElement * pSwapElement = NULL; CDOMTextNode * pSwapText = NULL; CDoc * pDoc = Doc(); HRESULT hr; if ( ppNodeSwapped ) *ppNodeSwapped = NULL; Assert( Tag() != ETAG_ROOT ); if ( !pNodeSwap ) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(CrackDOMNode((IUnknown*)pNodeSwap, &pSwapText, &pSwapElement, GetWindowedMarkupContext() )); if ( hr ) goto Cleanup; Assert(IsRootOnlyIfDocument(pNodeSwap, pSwapElement)); hr = THR (SwapDOMNodeHelper ( pDoc, this, NULL, pSwapElement, pSwapText )); if ( hr ) goto Cleanup; if ( ppNodeSwapped ) { hr = THR(QueryInterface(IID_IHTMLDOMNode, (void**)ppNodeSwapped)); } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::insertAdjacentElement(BSTR bstrWhere, IHTMLElement *pElemInsert, IHTMLElement **ppElementInserted) { HRESULT hr; htmlAdjacency where; ELEMENT_ADJACENCY adj; CDoc *pDoc = Doc(); CMarkupPointer mkptrTarget(pDoc); CElement *pElement = NULL; if (ppElementInserted) *ppElementInserted = NULL; if (!pElemInsert) { hr = E_INVALIDARG; goto Cleanup; } if (!pDoc->IsOwnerOf( pElemInsert )) { hr = E_INVALIDARG; goto Cleanup; } hr = THR(ENUMFROMSTRING(htmlAdjacency, bstrWhere, (long *)&where)); if (hr) goto Cleanup; hr = THR(pElemInsert->QueryInterface(CLSID_CElement, (void **)&pElement)); if (hr) goto Cleanup; // Can't insert a root, can't insert outside of root if( pElement->Tag() == ETAG_ROOT || ( Tag() == ETAG_ROOT && ( where == htmlAdjacencyBeforeBegin || where == htmlAdjacencyAfterEnd ) ) ) { hr = E_INVALIDARG; goto Cleanup; } switch (where) { case htmlAdjacencyBeforeBegin: default: adj = ELEM_ADJ_BeforeBegin; break; case htmlAdjacencyAfterBegin: adj = ELEM_ADJ_AfterBegin; break; case htmlAdjacencyBeforeEnd: adj = ELEM_ADJ_BeforeEnd; break; case htmlAdjacencyAfterEnd: adj = ELEM_ADJ_AfterEnd; break; } // Get target ptr hr = THR(EnsureInMarkup()); if (hr) goto Cleanup; hr = THR(mkptrTarget.MoveAdjacentToElement(this, adj)); if (hr) goto Cleanup; // Move src -> target hr = THR(InsertDOMNodeHelper(pElement, NULL, &mkptrTarget)); if (hr) goto Cleanup; if ( ppElementInserted ) { *ppElementInserted = pElemInsert; (*ppElementInserted)->AddRef(); } Cleanup: RRETURN(SetErrorInfo(hr)); } static HRESULT SetAdjacentTextPointer ( CElement *pElem, htmlAdjacency where, MARKUP_CONTEXT_TYPE *pContext, CMarkupPointer *pmkptrStart, long *plCharCount) { ELEMENT_ADJACENCY adj; BOOL fLeft; HRESULT hr; switch (where) { case htmlAdjacencyBeforeBegin: default: adj = ELEM_ADJ_BeforeBegin; fLeft = TRUE; break; case htmlAdjacencyAfterBegin: adj = ELEM_ADJ_AfterBegin; fLeft = FALSE; break; case htmlAdjacencyBeforeEnd: adj = ELEM_ADJ_BeforeEnd; fLeft = TRUE; break; case htmlAdjacencyAfterEnd: adj = ELEM_ADJ_AfterEnd; fLeft = FALSE; break; } hr = THR(pmkptrStart->MoveAdjacentToElement(pElem, adj)); if (hr) goto Cleanup; if ( fLeft ) { // Need to move the pointer to the start of the text hr = THR(pmkptrStart->Left ( TRUE, pContext, NULL, plCharCount, NULL, NULL )); if ( hr ) goto Cleanup; } else if ( plCharCount ) { // Need to do a non-moving Right to get the text length hr = THR(pmkptrStart->Right ( FALSE, pContext, NULL, plCharCount, NULL, NULL )); if ( hr ) goto Cleanup; } Cleanup: RRETURN(hr); } HRESULT CElement::getAdjacentText( BSTR bstrWhere, BSTR *pbstrText ) { HRESULT hr = S_OK; CMarkupPointer mkptrStart ( Doc() ); htmlAdjacency where; long lCharCount = -1; MARKUP_CONTEXT_TYPE context; hr = THR(ENUMFROMSTRING(htmlAdjacency, bstrWhere, (long *)&where)); if (hr) goto Cleanup; if ( !pbstrText ) goto Cleanup; *pbstrText = NULL; hr = THR(SetAdjacentTextPointer ( this, where, &context, &mkptrStart, &lCharCount )); if ( hr ) goto Cleanup; // Is there any text to return if ( context != CONTEXT_TYPE_Text || lCharCount == 0 ) goto Cleanup; // Alloc memory hr = FormsAllocStringLen ( NULL, lCharCount, pbstrText ); if ( hr ) goto Cleanup; // Read it into the buffer hr = THR(mkptrStart.Right( FALSE, &context, NULL, &lCharCount, *pbstrText, NULL)); if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::replaceAdjacentText( BSTR bstrWhere, BSTR bstrText, BSTR *pbstrText ) { HRESULT hr = S_OK; CMarkupPointer mkptrStart ( Doc() ); CMarkupPointer mkptrEnd ( Doc() ); htmlAdjacency where; long lCharCount = -1; MARKUP_CONTEXT_TYPE context; hr = THR(ENUMFROMSTRING(htmlAdjacency, bstrWhere, (long *)&where)); if (hr) goto Cleanup; if ( pbstrText ) { hr = THR (getAdjacentText(bstrWhere, pbstrText )); if ( hr ) goto Cleanup; } hr = THR(SetAdjacentTextPointer ( this, where, &context, &mkptrStart, &lCharCount )); if ( hr ) goto Cleanup; hr = THR(mkptrEnd.MoveToPointer ( &mkptrStart ) ); if ( hr ) goto Cleanup; if ( context == CONTEXT_TYPE_Text && lCharCount > 0 ) { hr = THR( mkptrEnd.Right ( TRUE, &context, NULL, &lCharCount, NULL, NULL )); if ( hr ) goto Cleanup; } hr = THR(Doc()->Remove ( &mkptrStart, &mkptrEnd, MUS_DOMOPERATION )); if ( hr ) goto Cleanup; hr = THR(mkptrStart.Doc()->InsertText( & mkptrStart, bstrText, -1, MUS_DOMOPERATION )); if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::get_canHaveChildren(VARIANT_BOOL *pvb) { *pvb = IsNoScope() ? VARIANT_FALSE : VARIANT_TRUE; return S_OK; } HRESULT CElement::get_ownerDocument(IDispatch **ppretdoc) { return OwnerDocHelper(ppretdoc, NULL, this); } HRESULT CElement::normalize() { HRESULT hr = S_OK; CDoc *pDoc = GetDocPtr(); CMarkupPointer mkpStart(pDoc); CMarkupPointer mkpEnd(pDoc); // Always positioned at just before the end of the element to normalize CMarkupPointer mkptxtend(pDoc); if(IsNoScope()) { goto Cleanup; } hr = THR(mkpStart.MoveAdjacentToElement(this, ELEM_ADJ_AfterBegin)); if (hr) goto Cleanup; hr = THR(mkpEnd.MoveAdjacentToElement(this, ELEM_ADJ_BeforeEnd)); if (hr) goto Cleanup; hr = THR(mkptxtend.MoveToPointer(&mkpStart)); if (hr) goto Cleanup; hr = THR(ScanText(pDoc, &mkpStart, &mkptxtend, &mkpEnd)); if( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } // Code for implementing IHTMLDOMNode for Document HRESULT CDocument::get_nodeType(long *pnodeType) { HRESULT hr = S_OK; if (!pnodeType) { hr = E_POINTER; goto Cleanup; } *pnodeType = _lnodeType; // Get the actual node type Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::get_parentNode(IHTMLDOMNode **pparentNode) { HRESULT hr = S_OK; if (!pparentNode) { hr = E_POINTER; goto Cleanup; } *pparentNode = NULL; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::hasChildNodes(VARIANT_BOOL *p) { return Markup()->Root()->hasChildNodes(p); } HRESULT CDocument::get_childNodes(IDispatch **ppChildCollection) { return Markup()->Root()->get_childNodes(ppChildCollection); } HRESULT CDocument::get_attributes(IDispatch **ppAttrCollection) { HRESULT hr = S_OK; if (!ppAttrCollection) { hr = E_POINTER; goto Cleanup; } *ppAttrCollection = NULL; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::insertBefore(IHTMLDOMNode *pNewChild, VARIANT refChild, IHTMLDOMNode **ppRetNode) { return Markup()->Root()->insertBefore(pNewChild, refChild, ppRetNode); } HRESULT CDocument::replaceChild(IHTMLDOMNode *pNewChild, IHTMLDOMNode *pOldChild, IHTMLDOMNode **ppRetNode) { return Markup()->Root()->replaceChild(pNewChild, pOldChild, ppRetNode); } HRESULT CDocument::removeChild(IHTMLDOMNode *pOldChild, IHTMLDOMNode **pRetNode) { return Markup()->Root()->removeChild(pOldChild, pRetNode); } HRESULT CDocument::cloneNode(VARIANT_BOOL fDeep, IHTMLDOMNode **ppNodeCloned) { HRESULT hr; CDoc * pDoc = Doc(); CMarkup * pMarkupTarget = NULL; CDocument * pDocument = NULL; *ppNodeCloned = NULL; hr = THR(pDoc->CreateMarkup(&pMarkupTarget, GetWindowedMarkupContext())); if (hr) goto Cleanup; hr = THR(pMarkupTarget->SetOrphanedMarkup(TRUE)); if( hr ) goto Cleanup; Assert(!pMarkupTarget->HasDocument()); hr = THR(pMarkupTarget->EnsureDocument(&pDocument)); if (hr) goto Cleanup; Assert(pDocument->_lnodeType == 9); pDocument->_lnodeType = 11; // document fragment if (fDeep) { CMarkupPointer mkptrStart ( pDoc ); CMarkupPointer mkptrEnd ( pDoc ); CMarkupPointer mkptrTarget ( pDoc ); // Get src ptrs hr = THR(Markup()->Root()->GetMarkupPtrRange(&mkptrStart, &mkptrEnd)); if (hr) goto Cleanup; // Get target ptr hr = THR(mkptrTarget.MoveToContainer(pMarkupTarget,TRUE)); if (hr) goto Cleanup; // Copy src -> target hr = THR(pDocument->Doc()->Copy(&mkptrStart, &mkptrEnd, &mkptrTarget, MUS_DOMOPERATION)); if (hr) goto Cleanup; } hr = THR(pDocument->QueryInterface(IID_IHTMLDOMNode, (void **)ppNodeCloned)); if (hr) goto Cleanup; Cleanup: // release extra markup lock if (pMarkupTarget) pMarkupTarget->Release(); RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::removeNode (VARIANT_BOOL fDeep, IHTMLDOMNode **ppNodeRemoved) { HRESULT hr = E_NOTIMPL; if (ppNodeRemoved) *ppNodeRemoved = NULL; RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::replaceNode(IHTMLDOMNode *pNodeReplace, IHTMLDOMNode **ppNodeReplaced) { HRESULT hr = E_NOTIMPL; if (ppNodeReplaced) *ppNodeReplaced = NULL; RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::swapNode(IHTMLDOMNode *pNodeSwap, IHTMLDOMNode **ppNodeSwapped) { HRESULT hr = E_NOTIMPL; if (ppNodeSwapped) *ppNodeSwapped = NULL; RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::appendChild(IHTMLDOMNode *pNewChild, IHTMLDOMNode **ppRetNode) { return Markup()->Root()->appendChild(pNewChild, ppRetNode); } HRESULT CDocument::get_nodeName(BSTR *pbstrNodeName) { HRESULT hr = S_OK; if (!pbstrNodeName) { hr = E_POINTER; goto Cleanup; } *pbstrNodeName = NULL; if(_lnodeType == 9) hr = THR(FormsAllocString ( _T("#document"), pbstrNodeName )); else { Assert(_lnodeType == 11); hr = THR(FormsAllocString ( _T("#document-fragment"), pbstrNodeName )); } if ( hr ) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::get_nodeValue(VARIANT *pvarValue) { HRESULT hr = S_OK; if (!pvarValue) { hr = E_POINTER; goto Cleanup; } pvarValue->vt = VT_NULL; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::put_nodeValue(VARIANT varValue) { HRESULT hr = S_OK; RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::get_firstChild ( IHTMLDOMNode **ppNode ) { return Markup()->Root()->get_firstChild(ppNode); } HRESULT CDocument::get_lastChild ( IHTMLDOMNode **ppNode ) { return Markup()->Root()->get_lastChild(ppNode); } HRESULT CDocument::get_previousSibling ( IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; if (!ppNode) { hr = E_POINTER; goto Cleanup; } *ppNode = NULL; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::get_nextSibling ( IHTMLDOMNode **ppNode ) { HRESULT hr = S_OK; if (!ppNode) { hr = E_POINTER; goto Cleanup; } *ppNode = NULL; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::get_ownerDocument(IDispatch **ppretdoc) { HRESULT hr = S_OK; CMarkup *pMarkup; CDocument *pDocument; if( !ppretdoc ) { hr = E_POINTER; goto Cleanup; } *ppretdoc = NULL; if(_lnodeType == 11) { pMarkup = GetWindowedMarkupContext(); Assert( pMarkup ); if(pMarkup->HasDocument()) { Assert( pMarkup ); pDocument = pMarkup->Document(); Assert(pDocument); Assert(pDocument->_lnodeType == 9); hr = THR(pDocument->QueryInterface(IID_IDispatch, (void **)ppretdoc)); if (hr) goto Cleanup; } } Cleanup: RRETURN(SetErrorInfo(hr)); } // Methods for implemention IHTMLDocument5 HRESULT CDocument::createAttribute(BSTR bstrAttrName, IHTMLDOMAttribute **ppAttribute) { HRESULT hr = S_OK; CAttribute *pAttribute = NULL; if(!ppAttribute) { hr = E_POINTER; goto Cleanup; } *ppAttribute = NULL; pAttribute = new CAttribute(NULL, DISPID_UNKNOWN, NULL, this); if (!pAttribute) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR(pAttribute->_cstrName.SetBSTR(bstrAttrName)); if (hr) goto Cleanup; hr = THR(pAttribute->PrivateQueryInterface(IID_IHTMLDOMAttribute, (void **)ppAttribute)); if (hr) goto Cleanup; Cleanup: if (pAttribute) pAttribute->Release(); RRETURN(SetErrorInfo(hr)); } HRESULT CElement::getAttributeNode(BSTR bstrName, IHTMLDOMAttribute **ppAttribute) { HRESULT hr; AAINDEX aaIdx = AA_IDX_UNKNOWN; CAttribute *pAttribute = NULL; DISPID dispid; PROPERTYDESC *pPropDesc; if (!ppAttribute) { hr = E_POINTER; goto Cleanup; } if (!bstrName || !*bstrName) { hr = E_INVALIDARG; goto Cleanup; } *ppAttribute = NULL; hr = THR(GetIndexHelper(bstrName, &aaIdx, NULL, &dispid, &pPropDesc, this, 0)); if (DISP_E_UNKNOWNNAME == hr) { hr = S_OK; goto Cleanup; } if (aaIdx == AA_IDX_UNKNOWN) { // No Attr Node, create new pAttribute = new CAttribute(pPropDesc, dispid, this); if (!pAttribute) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR(pAttribute->_cstrName.SetBSTR(bstrName)); if (hr) goto Cleanup; hr = THR(AddUnknownObject(dispid, (IUnknown *)(IPrivateUnknown *)pAttribute, CAttrValue::AA_DOMAttribute)); if (hr) goto Cleanup; } else { IUnknown *pUnk; hr = THR(GetUnknownObjectAt(aaIdx, &pUnk)); if (hr) goto Cleanup; pAttribute = (CAttribute *)pUnk; } Assert(pAttribute); hr = THR(pAttribute->QueryInterface(IID_IHTMLDOMAttribute, (void **)ppAttribute)); if (hr) goto Cleanup; Cleanup: if (pAttribute) pAttribute->Release(); RRETURN(SetErrorInfo(hr)); } HRESULT CElement::setAttributeNode(IHTMLDOMAttribute *pAttrIn, IHTMLDOMAttribute **ppAttribute) { HRESULT hr = S_OK; CAttribute *pAttribute; AAINDEX aaIdx; AAINDEX vaaIdx; DISPID dispid; PROPERTYDESC *pPropDesc = NULL; if (!ppAttribute) { hr = E_POINTER; goto Cleanup; } if (!pAttrIn) { hr = E_INVALIDARG; goto Cleanup; } *ppAttribute = NULL; hr = THR(pAttrIn->QueryInterface(CLSID_CAttribute, (void **)&pAttribute)); if (hr) goto Cleanup; if (pAttribute->_pElem) { // In use error. hr = E_INVALIDARG; goto Cleanup; } Assert((LPTSTR)(pAttribute->_cstrName)); Assert(!pAttribute->_pElem); Assert(!pAttribute->_pPropDesc); Assert(pAttribute->_dispid == DISPID_UNKNOWN); hr = THR(RemoveAttrHelper(pAttribute->_cstrName, &pPropDesc, &dispid, &aaIdx, &vaaIdx, this, ppAttribute, fdexNameEnsure)); if (hr) goto Cleanup; pAttribute->_pPropDesc = pPropDesc; pAttribute->_pElem = this; pAttribute->_dispid = dispid; SubAddRef(); // Attr Node already exists? if (aaIdx == AA_IDX_UNKNOWN) { // No, set new one passed in hr = THR(AddUnknownObject(dispid, (IUnknown *)(IPrivateUnknown *)pAttribute, CAttrValue::AA_DOMAttribute)); if (hr) goto Cleanup; if (!pPropDesc) { hr = THR(UpdateDomAttrCollection(FALSE, dispid)); if (hr) goto Cleanup; } } else { // Yes, replace it with passed in attr node CAttrArray *pAA = *GetAttrArray(); VARIANT var; V_VT(&var) = VT_UNKNOWN; V_UNKNOWN(&var) = (IUnknown *)(IPrivateUnknown *)pAttribute; Assert(pAA); hr = THR(pAA->SetAt(aaIdx, &var)); if (hr) goto Cleanup; } // Need to set the new value now.. if (!pAttribute->_varValue.IsEmpty()) { hr = THR(PutNodeValueHelper(pAttribute, vaaIdx, pAttribute->_varValue)); if (hr) goto Cleanup; hr = THR(pAttribute->_varValue.Clear()); if (hr) goto Cleanup; } else { // Passed in Attr node doesn't have a value set yet if (vaaIdx != AA_IDX_UNKNOWN) { // But there is an existing value for this attr name, remove it. DeleteAt(vaaIdx); } // set default value of expando node to "undefined" if (!pPropDesc) { CVariant var; // initialized to VT_EMPTY to return undefined hr = THR(AddVariant(dispid, &var, CAttrValue::AA_Expando)); if (hr) goto Cleanup; } } Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::removeAttributeNode(IHTMLDOMAttribute *pAttrRemove, IHTMLDOMAttribute **ppAttribute) { HRESULT hr = S_OK; CAttribute *pAttribute; if (!ppAttribute) { hr = E_POINTER; goto Cleanup; } *ppAttribute = NULL; if(!pAttrRemove) goto Cleanup; hr = THR(pAttrRemove->QueryInterface(CLSID_CAttribute, (void **)&pAttribute)); if (hr) goto Cleanup; hr = THR(RemoveAttributeNode(pAttribute->_cstrName, ppAttribute)); if (hr) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CElement::RemoveAttributeNode(LPTSTR pchAttrName, IHTMLDOMAttribute **ppAttribute) { HRESULT hr = S_OK; BOOL fUpdateDOMAttrColl = FALSE; CAttribute *pAttrNew = NULL; AAINDEX aaIdx; AAINDEX vaaIdx; DISPID dispid; PROPERTYDESC *pPropDesc; hr = THR(RemoveAttrHelper(pchAttrName, &pPropDesc, &dispid, &aaIdx, &vaaIdx, this, ppAttribute, 0)); if (hr) goto Cleanup; // remove attrNode from this element's AA if it exists if (aaIdx != AA_IDX_UNKNOWN) { DeleteAt(aaIdx); fUpdateDOMAttrColl = TRUE; } if (vaaIdx != AA_IDX_UNKNOWN) { // There is an existing value for this attr name, remove it. DeleteAt(vaaIdx); fUpdateDOMAttrColl = TRUE; } if (pPropDesc) { // All non-expando attrs have a default value so replace removed node with new one. Assert(!IsExpandoDISPID(dispid)); pAttrNew = new CAttribute(pPropDesc, dispid, this); if (!pAttrNew) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = THR(pAttrNew->_cstrName.Set(pchAttrName)); if (hr) goto Cleanup; hr = THR(AddUnknownObject(dispid, (IUnknown *)(IPrivateUnknown *)pAttrNew, CAttrValue::AA_DOMAttribute)); if (hr) goto Cleanup; } else if (fUpdateDOMAttrColl) { Assert(!pPropDesc); hr = THR(UpdateDomAttrCollection(TRUE, dispid)); if (hr) goto Cleanup; } Cleanup: if (pAttrNew) pAttrNew->Release(); RRETURN(hr); } HRESULT CDocument::createComment(BSTR data, IHTMLDOMNode **ppRetNode) { HRESULT hr = S_OK; CCommentElement *pelComment = NULL; if(!ppRetNode) { hr = E_POINTER; goto Cleanup; } pelComment = new CCommentElement(ETAG_RAW_COMMENT, Doc()); if(!pelComment) { hr = E_OUTOFMEMORY; goto Cleanup; } pelComment->_fAtomic = TRUE; hr = THR(pelComment->_cstrText.Set(_T("<!--"), 4)); if( hr ) goto Cleanup; hr = THR(pelComment->_cstrText.Append(data)); if( hr ) goto Cleanup; hr = THR(pelComment->_cstrText.Append(_T("-->"), 3)); if( hr ) goto Cleanup; hr = THR(pelComment->SetWindowedMarkupContextPtr(GetWindowedMarkupContext())); if( hr ) goto Cleanup; pelComment->GetWindowedMarkupContextPtr()->SubAddRef(); hr = THR(pelComment->PrivateQueryInterface(IID_IHTMLDOMNode, (void **)ppRetNode)); if( hr ) goto Cleanup; Cleanup: if(pelComment) pelComment->Release(); RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::get_doctype(IHTMLDOMNode **ppnode) { HRESULT hr = S_OK; if(!ppnode) { hr = E_POINTER; goto Cleanup; } *ppnode = NULL; Cleanup: RRETURN(SetErrorInfo(hr)); } HRESULT CDocument::get_implementation(IHTMLDOMImplementation **ppimplementation) { HRESULT hr = S_OK; CDoc *pDoc = Doc(); CDOMImplementation **pdomimpl = &pDoc->_pdomImplementation; if(!ppimplementation) { hr = E_POINTER; goto Cleanup; } if(!*pdomimpl) { *pdomimpl = new CDOMImplementation(pDoc); if(!*pdomimpl) { hr = E_OUTOFMEMORY; goto Cleanup; } } hr = THR((*pdomimpl)->QueryInterface(IID_IHTMLDOMImplementation, (void **)ppimplementation)); if(hr) goto Cleanup; Cleanup: RRETURN(SetErrorInfo(hr)); } // DOMImplementation const CBase::CLASSDESC CDOMImplementation::s_classdesc = { &CLSID_HTMLDOMImplementation, // _pclsid 0, // _idrBase #ifndef NO_PROPERTY_PAGE NULL, // _apClsidPages #endif // NO_PROPERTY_PAGE NULL, // _pcpi 0, // _dwFlags &IID_IHTMLDOMImplementation, // _piidDispinterface &s_apHdlDescs, // _apHdlDesc }; MtDefine(CDOMImplementation, Mem, "CDOMImplementation") CDOMImplementation::CDOMImplementation(CDoc *pDoc) { _pDoc = pDoc; _pDoc->SubAddRef(); } void CDOMImplementation::Passivate() { _pDoc->SubRelease(); CBase::Passivate(); } HRESULT CDOMImplementation::PrivateQueryInterface(REFIID iid, void **ppv) { *ppv = NULL; switch (iid.Data1) { QI_INHERITS((IPrivateUnknown *)this, IUnknown) QI_INHERITS(this, IHTMLDOMImplementation) QI_TEAROFF_DISPEX(this, NULL) } if (!*ppv) RRETURN(E_NOINTERFACE); ((IUnknown *) *ppv)->AddRef(); return S_OK; } HRESULT CDOMImplementation::hasFeature(BSTR bstrFeature, VARIANT version, VARIANT_BOOL* pfHasFeature) { HRESULT hr = S_OK; BSTR bstrVersion = NULL; if(!pfHasFeature) { hr = E_POINTER; goto Cleanup; } *pfHasFeature = VB_FALSE; switch (V_VT(&version)) { case VT_BSTR: bstrVersion = V_BSTR(&version); break; case VT_NULL: case VT_ERROR: case VT_EMPTY: break; default: hr = E_INVALIDARG; goto Cleanup; } if(!_tcsicmp(bstrFeature, _T("HTML"))) { if(bstrVersion && *bstrVersion) { if(!_tcsicmp(bstrVersion, _T("1.0"))) *pfHasFeature = VB_TRUE; } else *pfHasFeature = VB_TRUE; } Cleanup: RRETURN(SetErrorInfo(hr)); }
24.57157
184
0.561684
[ "object" ]
5d236743f75875e1a63d811a8547a8c53d203177
303
cxx
C++
ants/lib/WRAP_DenoiseImage.cxx
xemio/ANTsPy
ef610318e217bb04d3850d480c2e51df695d56c0
[ "Apache-2.0" ]
338
2017-09-01T06:47:54.000Z
2022-03-31T12:11:46.000Z
ants/lib/WRAP_DenoiseImage.cxx
xemio/ANTsPy
ef610318e217bb04d3850d480c2e51df695d56c0
[ "Apache-2.0" ]
306
2017-08-30T20:05:07.000Z
2022-03-31T16:20:44.000Z
ants/lib/WRAP_DenoiseImage.cxx
xemio/ANTsPy
ef610318e217bb04d3850d480c2e51df695d56c0
[ "Apache-2.0" ]
115
2017-09-08T11:53:17.000Z
2022-03-27T05:53:39.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "antscore/DenoiseImage.h" namespace py = pybind11; int DenoiseImage( std::vector<std::string> instring ) { return ants::DenoiseImage(instring, NULL); } PYBIND11_MODULE(DenoiseImage, m) { m.def("DenoiseImage", &DenoiseImage); }
17.823529
53
0.729373
[ "vector" ]
5d23f740806c6ae732b2a28e8633860b1c9e107a
30,029
cc
C++
pdb/src/pipeline/headers/ComputePlan.cc
SeraphL/plinycompute
7788bc2b01d83f4ff579c13441d0ba90734b54a2
[ "Apache-2.0" ]
3
2019-05-04T05:17:30.000Z
2020-02-21T05:01:59.000Z
pdb/src/pipeline/headers/ComputePlan.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
3
2020-02-20T19:50:46.000Z
2020-06-25T14:31:51.000Z
pdb/src/pipeline/headers/ComputePlan.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
5
2019-02-19T23:17:24.000Z
2020-08-03T01:08:04.000Z
#include <utility> /***************************************************************************** * * * Copyright 2018 Rice University * * * * 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 "ComputePlan.h" #include "executors/FilterExecutor.h" #include "executors/FlattenExecutor.h" #include "executors/UnionExecutor.h" #include "executors/HashOneExecutor.h" #include "AtomicComputationClasses.h" #include "lambdas/EqualsLambda.h" #include "JoinCompBase.h" #include "AggregateCompBase.h" #include "AggregationPipeline.h" #include "NullProcessor.h" #include "Lexer.h" #include "Parser.h" #include "StringIntPair.h" #include "JoinBroadcastPipeline.h" extern int yydebug; namespace pdb { ComputePlan::ComputePlan(LogicalPlanPtr myPlan) : myPlan(std::move(myPlan)) {} ComputeSourcePtr ComputePlan::getComputeSource(AtomicComputationPtr &sourceAtomicComputation, const PDBAbstractPageSetPtr &inputPageSet, std::map<ComputeInfoType, ComputeInfoPtr> &params, uint64_t chunkSize, uint64_t workerID) { // now we get the name of the actual computation object that corresponds to the producer of this tuple set std::string producerName = sourceAtomicComputation->getComputationName(); // get a reference to the computations of the logical plan auto &allComps = myPlan->getComputations(); // if we are a join (shuffle join source) we need to have separate logic to handle that, otherwise just return a regular source if(sourceAtomicComputation->getAtomicComputationTypeID() != ApplyJoinTypeID) { // our source is a normal source and not a join source, so we just grab it from the computation return myPlan->getNode(producerName).getComputation().getComputeSource(inputPageSet, chunkSize, workerID, params); } // cast the join computation auto *joinComputation = (ApplyJoin *) sourceAtomicComputation.get(); // grab the join arguments JoinArgumentsPtr joinArgs = std::dynamic_pointer_cast<JoinArguments>(params[ComputeInfoType::JOIN_ARGS]); if(joinArgs == nullptr) { throw runtime_error("Join pipeline run without hash tables!"); } // figure out if the source is the left or right side auto shuffleJoinArgs = std::dynamic_pointer_cast<ShuffleJoinArg>(params[ComputeInfoType::SHUFFLE_JOIN_ARG]); if(!shuffleJoinArgs->swapLeftAndRightSide) { AtomicComputationPtr leftAtomicComp = allComps.getProducingAtomicComputation(joinComputation->getInput().getSetName()); AtomicComputationPtr rightAtomicComp = allComps.getProducingAtomicComputation(joinComputation->getRightInput().getSetName()); bool needsToSwapSides = false; // do we have the appropriate join arguments? if not throw an exception auto it = joinArgs->hashTables.find(rightAtomicComp->getOutput().getSetName()); if(it == joinArgs->hashTables.end()) { throw runtime_error("Hash table for the output set," + rightAtomicComp->getOutput().getSetName() + "not found!"); } // init the RHS source auto rhsSource = ((JoinCompBase *) &myPlan->getNode(joinComputation->getComputationName()).getComputation())->getRHSShuffleJoinSource(rightAtomicComp->getOutput(), joinComputation->getRightInput(), joinComputation->getRightProjection(), it->second->hashTablePageSet, myPlan, chunkSize, workerID); // init the compute source for the join return ((JoinCompBase *) &myPlan->getNode(joinComputation->getComputationName()).getComputation())->getJoinedSource(joinComputation->getProjection(), // this tells me how the join tuple of the LHS is layed out rightAtomicComp->getOutput(), // this gives the specification of the RHS tuple joinComputation->getRightInput(), // this gives the location of the RHS hash joinComputation->getRightProjection(), // this gives the projection of the RHS tuple rhsSource, // the RHS source that gives us the tuples inputPageSet, // the LHS page set myPlan, needsToSwapSides, chunkSize, workerID); } else { AtomicComputationPtr rightAtomicComp = allComps.getProducingAtomicComputation(joinComputation->getInput().getSetName()); AtomicComputationPtr leftAtomicComp = allComps.getProducingAtomicComputation(joinComputation->getRightInput().getSetName()); bool needsToSwapSides = true; // do we have the appropriate join arguments? if not throw an exception auto it = joinArgs->hashTables.find(rightAtomicComp->getOutput().getSetName()); if(it == joinArgs->hashTables.end()) { throw runtime_error("Hash table for the output set," + rightAtomicComp->getOutput().getSetName() + " not found!"); } // init the RHS source auto rhsSource = ((JoinCompBase *) &myPlan->getNode(joinComputation->getComputationName()).getComputation())->getRHSShuffleJoinSource(rightAtomicComp->getOutput(), joinComputation->getInput(), joinComputation->getProjection(), it->second->hashTablePageSet, myPlan, chunkSize, workerID); // init the compute source for the join return ((JoinCompBase *) &myPlan->getNode(joinComputation->getComputationName()).getComputation())->getJoinedSource(joinComputation->getRightProjection(), // this tells me how the join tuple of the LHS is layed out rightAtomicComp->getOutput(), // this gives the specification of the RHS tuple joinComputation->getInput(), // this gives the location of the RHS hash joinComputation->getProjection(), // this gives the projection of the RHS tuple rhsSource, // the RHS source that gives us the tuples inputPageSet, // the LHS page set myPlan, needsToSwapSides, chunkSize, workerID); } } std::tuple<TupleSpec, TupleSpec, TupleSpec> ComputePlan::getSinkSpecifier(AtomicComputationPtr &targetAtomicComp, std::string &targetComputationName) { // get a reference to the computations of the logical plan auto &allComps = myPlan->getComputations(); // and get the schema for the output TupleSet objects that it is supposed to produce TupleSpec &targetSpec = targetAtomicComp->getOutput(); // and get the projection for this guy const auto &consumers = allComps.getConsumingAtomicComputations(targetSpec.getSetName()); /// TODO this whole part needs to be rewritten TupleSpec targetProjection = targetSpec; TupleSpec targetAttsToOpOn = targetSpec; for (auto &a : consumers) { if (a->getComputationName() == targetComputationName) { // we found the consuming computation if (targetSpec == a->getInput()) { targetProjection = a->getProjection(); //added following to merge join code if (targetComputationName.find("JoinComp") == std::string::npos) { targetSpec = targetProjection; } targetAttsToOpOn = a->getInput(); break; } // the only way that the input to this guy does not match targetSpec is if he is a join, which has two inputs if (a->getAtomicComputationType() != std::string("JoinSets")) { exit(1); } // get the join and make sure it matches auto *myGuy = (ApplyJoin *) a.get(); if (!(myGuy->getRightInput() == targetSpec)) { exit(1); } targetProjection = myGuy->getRightProjection(); targetAttsToOpOn = myGuy->getRightInput(); } } // return the result containing (targetSpec, targetAttsToOpOn, targetProjection) return std::move(make_tuple(targetSpec, targetAttsToOpOn, targetProjection)); } ComputeSinkPtr ComputePlan::getComputeSink(AtomicComputationPtr &targetAtomicComp, std::string& targetComputationName, std::map<ComputeInfoType, ComputeInfoPtr> &params, size_t numNodes, size_t numProcessingThreads) { // returns the input specifier auto specifier = getSinkSpecifier(targetAtomicComp, targetComputationName); // now we have the list of computations, and so it is time to build the pipeline... start by building a compute sink return myPlan->getNode(targetComputationName).getComputation().getComputeSink(std::get<0>(specifier), std::get<1>(specifier), std::get<2>(specifier), numProcessingThreads * numNodes, params, myPlan); } PipelinePtr ComputePlan::assemblePipeline(const std::string& sourceTupleSetName, const PDBAnonymousPageSetPtr &outputPageSet, ComputeSourcePtr &computeSource, ComputeSinkPtr &computeSink, const PageProcessorPtr &processor, std::map<ComputeInfoType, ComputeInfoPtr> &params, std::vector<AtomicComputationPtr> &pipelineComputations, size_t numNodes, size_t numProcessingThreads, uint64_t workerID) { // make the pipeline std::shared_ptr<Pipeline> returnVal = std::make_shared<Pipeline>(outputPageSet, computeSource, computeSink, processor); // add the operations to the pipeline AtomicComputationPtr lastOne = myPlan->getComputations().getProducingAtomicComputation(sourceTupleSetName); for (auto &a : pipelineComputations) { // if we have a filter, then just go ahead and create it if (a->getAtomicComputationType() == "Filter") { // create a filter executor returnVal->addStage(std::make_shared<FilterExecutor>(lastOne->getOutput(), a->getInput(), a->getProjection())); // if we had an apply, go ahead and find it and add it to the pipeline } else if (a->getAtomicComputationType() == "Apply") { // create an executor for the apply lambda returnVal->addStage(myPlan->getNode(a->getComputationName()). getLambda(((ApplyLambda *) a.get())->getLambdaToApply())->getExecutor(lastOne->getOutput(), a->getInput(), a->getProjection())); } else if(a->getAtomicComputationType() == "Union") { // get the union auto u = (Union *) a.get(); // check if we are pipelining the right input if (lastOne->getOutput().getSetName() == u->getRightInput().getSetName()) { returnVal->addStage(std::make_shared<UnionExecutor>(lastOne->getOutput(), u->getRightInput())); } else { returnVal->addStage(std::make_shared<UnionExecutor>(lastOne->getOutput(), u->getInput())); } } else if (a->getAtomicComputationType() == "HashLeft") { // create an executor for left hasher returnVal->addStage(myPlan->getNode(a->getComputationName()). getLambda(((HashLeft *) a.get())->getLambdaToApply())->getLeftHasher(lastOne->getOutput(), a->getInput(), a->getProjection())); } else if (a->getAtomicComputationType() == "HashRight") { // create an executor for the right hasher returnVal->addStage(myPlan->getNode(a->getComputationName()). getLambda(((HashLeft *) a.get())->getLambdaToApply())->getRightHasher(lastOne->getOutput(), a->getInput(), a->getProjection())); } else if (a->getAtomicComputationType() == "HashOne") { returnVal->addStage(std::make_shared<HashOneExecutor>(lastOne->getOutput(), a->getInput(), a->getProjection())); } else if (a->getAtomicComputationType() == "Flatten") { returnVal->addStage(std::make_shared<FlattenExecutor>(lastOne->getOutput(), a->getInput(), a->getProjection())); } else if (a->getAtomicComputationType() == "JoinSets") { // join is weird, because there are two inputs... auto &myComp = (JoinCompBase &) myPlan->getNode(a->getComputationName()).getComputation(); auto *myJoin = (ApplyJoin *) (a.get()); // grab the join arguments JoinArgumentsPtr joinArgs = std::dynamic_pointer_cast<JoinArguments>(params[ComputeInfoType::JOIN_ARGS]); if(joinArgs == nullptr) { throw runtime_error("Join pipeline run without hash tables!"); } // check if we are pipelining the right input if (lastOne->getOutput().getSetName() == myJoin->getRightInput().getSetName()) { // do we have the appropriate join arguments? if not throw an exception auto it = joinArgs->hashTables.find(myJoin->getInput().getSetName()); if (it == joinArgs->hashTables.end()) { throw runtime_error("Hash table for the output set," + a->getOutput().getSetName() + "not found!"); } // if we are pipelining the right input, then we don't need to switch left and right inputs returnVal->addStage(myComp.getExecutor(true, myJoin->getProjection(), lastOne->getOutput(), myJoin->getRightInput(), myJoin->getRightProjection(), it->second, numNodes, numProcessingThreads, workerID, *this)); } else { // do we have the appropriate join arguments? if not throw an exception auto it = joinArgs->hashTables.find(myJoin->getRightInput().getSetName()); if (it == joinArgs->hashTables.end()) { throw runtime_error("Hash table for the output set," + a->getOutput().getSetName() + "not found!"); } // if we are pipelining the right input, then we don't need to switch left and right inputs returnVal->addStage(myComp.getExecutor(false, myJoin->getRightProjection(), lastOne->getOutput(), myJoin->getInput(), myJoin->getProjection(), it->second, numNodes, numProcessingThreads, workerID, *this)); } } else if(a->getAtomicComputationType() == "WriteSet") { // skip this one std::cout << "We are skipping a write set this is essentially a NOOP\n"; } else { std::cout << "This is bad... found an unexpected computation type (" << a->getAtomicComputationType() << ") inside of a pipeline.\n"; } lastOne = a; } return std::move(returnVal); } bool ComputePlan::findPipelineComputations(const LogicalPlanPtr& myPlan, std::vector<AtomicComputationPtr> &listSoFar, const std::string &targetTupleSetName) { // see if the guy at the end of the list is indeed the target if (listSoFar.back()->getOutputName() == targetTupleSetName) { // in this case, we have the complete list of computations return true; } // get all of the guys who consume the dude on the end of the list std::vector<AtomicComputationPtr> &nextOnes = myPlan->getComputations().getConsumingAtomicComputations(listSoFar.back()->getOutputName()); // and try to put each of the next computations on the end of the list, and recursively search for (auto &a : nextOnes) { // see if the next computation was on the path to the target listSoFar.push_back(a); if (findPipelineComputations(myPlan, listSoFar, targetTupleSetName)) { // it was! So we are done return true; } // we couldn't find the target listSoFar.pop_back(); } // if we made it here, we could not find the target return false; } LogicalPlanPtr &ComputePlan::getPlan() { return myPlan; } PipelinePtr ComputePlan::buildPipeline(const std::string& sourceTupleSetName, const std::string& targetTupleSetName, const PDBAbstractPageSetPtr &inputPageSet, const PDBAnonymousPageSetPtr &outputPageSet, std::map<ComputeInfoType, ComputeInfoPtr> &params, size_t numNodes, size_t numProcessingThreads, uint64_t chunkSize, uint64_t workerID) { // get all of the computations AtomicComputationList &allComps = myPlan->getComputations(); /// 0. Figure out the compute source // get the atomic computation of the source auto sourceAtomicComputation = allComps.getProducingAtomicComputation(sourceTupleSetName); // and get the schema for the output TupleSet objects that it is supposed to produce TupleSpec &origSpec = sourceAtomicComputation->getOutput(); // figure out the source ComputeSourcePtr computeSource = getComputeSource(sourceAtomicComputation, inputPageSet, params, chunkSize, workerID); /// 1. Find all the computations in the pipeline // now we have to do a DFS. This vector will store all of the computations we've found so far std::vector<AtomicComputationPtr> listSoFar; // and this list stores the computations that we still need to process std::vector<AtomicComputationPtr> &nextOnes = myPlan->getComputations().getConsumingAtomicComputations(origSpec.getSetName()); // now, see if each of the next guys can get us to the target tuple set bool gotIt = false; for (auto &a : nextOnes) { listSoFar.push_back(a); // see if the next computation was on the path to the target if (findPipelineComputations(myPlan, listSoFar, targetTupleSetName)) { gotIt = true; break; } // we couldn't find the target listSoFar.pop_back(); } // see if we could not find a path if (!gotIt) { std::cerr << "This is bad. Could not find a path from source computation to sink computation.\n"; exit(1); } /// 2. Figure out the sink // find the target atomic computation auto targetAtomicComp = allComps.getProducingAtomicComputation(targetTupleSetName); // find the target real PDBComputation auto targetComputationName = targetAtomicComp->getComputationName(); // if the write set is in the pipeline remove it since it is basically a noop if(targetAtomicComp->getAtomicComputationType() == "WriteSet") { // pop it! listSoFar.pop_back(); targetAtomicComp = listSoFar.back(); } // get the compute sink auto computeSink = getComputeSink(targetAtomicComp, targetComputationName, params, numNodes, numProcessingThreads); // do we have a processor provided auto it = params.find(ComputeInfoType::PAGE_PROCESSOR); PageProcessorPtr processor = it != params.end() ? dynamic_pointer_cast<PageProcessor>(it->second) : make_shared<NullProcessor>(); /// 3. Assemble the pipeline // assemble the whole pipeline return std::move(assemblePipeline(sourceTupleSetName, outputPageSet, computeSource, computeSink, processor, params, listSoFar, numNodes, numProcessingThreads, workerID)); } PipelinePtr ComputePlan::buildAggregationPipeline(const std::string &targetTupleSetName, const PDBAbstractPageSetPtr &inputPageSet, const PDBAnonymousPageSetPtr &outputPageSet, uint64_t workerID) { // get all of the computations AtomicComputationList &allComps = myPlan->getComputations(); // find the target atomic computation auto targetAtomicComp = allComps.getProducingAtomicComputation(targetTupleSetName); // find the target real PDBComputation auto targetComputationName = targetAtomicComp->getComputationName(); // grab the aggregation combiner Handle<AggregateCompBase> agg = unsafeCast<AggregateCompBase>(myPlan->getNode(targetComputationName).getComputationHandle()); auto combiner = agg->getAggregationHashMapCombiner(workerID); return std::make_shared<pdb::AggregationPipeline>(workerID, outputPageSet, inputPageSet, combiner); } PipelinePtr ComputePlan::buildBroadcastJoinPipeline(const string &targetTupleSetName, const PDBAbstractPageSetPtr &inputPageSet, const PDBAnonymousPageSetPtr &outputPageSet, uint64_t numThreads, uint64_t numNodes, uint64_t workerID) { // get all of the computations AtomicComputationList &allComps = myPlan->getComputations(); // find the target atomic computation auto targetAtomicComp = allComps.getProducingAtomicComputation(targetTupleSetName); // find the target real PDBComputation auto targetComputationName = targetAtomicComp->getComputationName(); // and get the schema for the output TupleSet objects that it is supposed to produce TupleSpec &targetSpec = targetAtomicComp->getOutput(); // and get the projection for this guy std::vector<AtomicComputationPtr> &consumers = allComps.getConsumingAtomicComputations(targetSpec.getSetName()); TupleSpec targetProjection; TupleSpec targetAttsToOpOn; for (auto &a : consumers) { if (a->getComputationName() == targetComputationName) { // we found the consuming computation if (targetSpec == a->getInput()) { targetProjection = a->getProjection(); //added following to merge join code if (targetComputationName.find("JoinComp") == std::string::npos) { targetSpec = targetProjection; } targetAttsToOpOn = a->getInput(); break; } // the only way that the input to this guy does not match targetSpec is if he is a join, which has two inputs if (a->getAtomicComputationType() != std::string("JoinSets")) { exit(1); } // get the join and make sure it matches auto *myGuy = (ApplyJoin *) a.get(); if (!(myGuy->getRightInput() == targetSpec)) { exit(1); } targetProjection = myGuy->getRightProjection(); targetAttsToOpOn = myGuy->getRightInput(); } } // get the join computation Handle<JoinCompBase> joinComp = unsafeCast<JoinCompBase>(myPlan->getNode(targetComputationName).getComputationHandle()); // get the BroadcastJoin pipeline merger auto merger = joinComp->getComputeMerger(targetSpec, targetAttsToOpOn, targetProjection, workerID, numThreads, numNodes, myPlan); // build the BroadcastJoin pipelines return std::make_shared<pdb::JoinBroadcastPipeline>(workerID, outputPageSet, inputPageSet, merger); } PageProcessorPtr ComputePlan::getProcessorForJoin(const std::string &tupleSetName, size_t numNodes, size_t numProcessingThreads, vector<PDBPageQueuePtr> &pageQueues, PDBBufferManagerInterfacePtr bufferManager) { // get all of the computations AtomicComputationList &allComps = myPlan->getComputations(); // auto joinComputation = allComps.getProducingAtomicComputation(tupleSetName); TupleSpec &targetSpec = joinComputation->getOutput(); // find the target atomic computation std::vector<AtomicComputationPtr> &consumers = allComps.getConsumingAtomicComputations(targetSpec.getSetName()); // TupleSpec targetProjection; for (auto &a : consumers) { // if (targetSpec == a->getInput()) { // get the projection targetProjection = a->getProjection(); break; } // get the join and make sure it matches auto *myGuy = (ApplyJoin *) a.get(); if (!(myGuy->getRightInput() == targetSpec)) { throw runtime_error(""); } targetProjection = myGuy->getRightProjection(); } // return the processor return ((JoinCompBase*) &myPlan->getNode(joinComputation->getComputationName()).getComputation())->getShuffleJoinProcessor(numNodes, numProcessingThreads, pageQueues, bufferManager, targetProjection, myPlan); } }
50.384228
218
0.540311
[ "object", "vector" ]
5d24a3225fbba6b1052d57552712d2954c410603
7,858
hpp
C++
viennashe/postproc/displacement_current.hpp
FelipeSenra/viennashe-dev
1b42f01b0826322c0b49a6fcf08fc0db5946e21f
[ "MIT" ]
3
2020-05-07T14:38:52.000Z
2021-05-30T09:43:18.000Z
viennashe/postproc/displacement_current.hpp
FelipeSenra/viennashe-dev
1b42f01b0826322c0b49a6fcf08fc0db5946e21f
[ "MIT" ]
1
2021-05-02T13:50:52.000Z
2021-05-03T03:49:51.000Z
viennashe/postproc/displacement_current.hpp
FelipeSenra/viennashe-dev
1b42f01b0826322c0b49a6fcf08fc0db5946e21f
[ "MIT" ]
3
2020-05-07T14:39:07.000Z
2021-05-08T12:15:26.000Z
#ifndef VIENNASHE_UTIL_POSTPROC_DISPLACEMENT_CURRENT_HPP #define VIENNASHE_UTIL_POSTPROC_DISPLACEMENT_CURRENT_HPP /* ============================================================================ Copyright (c) 2011-2014, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaSHE - The Vienna Spherical Harmonics Expansion Boltzmann Solver ----------------- http://viennashe.sourceforge.net/ License: MIT (X11), see file LICENSE in the base directory =============================================================================== */ // std #include <iostream> #include <fstream> #include <vector> // viennagrid #include "viennagrid/mesh/mesh.hpp" #include "viennagrid/algorithm/volume.hpp" #include "viennagrid/algorithm/inner_prod.hpp" // viennashe #include "viennashe/physics/constants.hpp" #include "viennashe/physics/physics.hpp" #include "viennashe/materials/all.hpp" #include "viennashe/util/checks.hpp" #include "viennashe/util/misc.hpp" #include "viennashe/log/log.hpp" #include "viennashe/util/dual_box_flux.hpp" #include "viennashe/util/misc.hpp" #include "viennashe/she/postproc/macroscopic.hpp" #include "viennashe/accessors.hpp" #include "viennashe/postproc/electric_field.hpp" /** @file viennashe/postproc/displacement_current.hpp @brief Computes the electric field from a potential */ namespace viennashe { namespace detail { // TODO: Revive /** @brief An accessor to the displacement current along edges */ /* template < typename DeviceType, typename PotentialAccessorType, typename OldPotentialAccessorType > struct displacement_current_on_edge { private: typedef typename DeviceType::mesh_type MeshType; typedef typename viennagrid::result_of::point<MeshType>::type PointType; public: typedef typename viennagrid::result_of::vertex<MeshType>::type VertexType; typedef typename viennagrid::result_of::edge<MeshType>::type EdgeType; displacement_current_on_edge(DeviceType const & device, PotentialAccessorType const & potential, OldPotentialAccessorType const & old_potential, double rtime ) : device_(device), potential_(potential), old_potential_(old_potential), rtime_(rtime) { } double operator()(EdgeType const & edge) const { typedef viennashe::util::no_contact_filter<DeviceType> PotentialFilterType; if(rtime_ <= 0) return 0; PotentialFilterType potential_filter(device_); viennashe::permittivity_accessor<DeviceType> permittivity(device_); viennashe::detail::electric_field_on_facet<DeviceType, PotentialAccessorType> efield_new(device_, potential_); viennashe::detail::electric_field_on_facet<DeviceType, PotentialAccessorType> efield_old(device_, old_potential_); const double A = util::effective_voronoi_interface(edge, potential_filter); if (A == 0) return 0; // safety check const double eps = util::effective_weighted_voronoi_interface(edge, potential_filter, permittivity) / A; // (sum_i A_i * eps_i) / (sum_i A_i) ... to get the average eps const double Dmag_new = efield_new(edge) * eps; const double Dmag_old = efield_old(edge) * eps; const double current_density = rtime_ * ( Dmag_new - Dmag_old ); return current_density; } // operator() private: DeviceType const & device_; PotentialAccessorType const & potential_; OldPotentialAccessorType const & old_potential_; double rtime_; }; // displacement_current_on_edge */ } // namespace detail /** @brief An accessor to the displacement current on edges and vertices */ /* template < typename DeviceType, typename PotentialAccessorType, typename OldPotentialAccessorType > struct displacement_current_wrapper { private: typedef typename DeviceType::mesh_type MeshType; typedef typename viennagrid::result_of::point<MeshType>::type PointType; public: typedef typename viennagrid::result_of::vertex<MeshType> ::type VertexType; typedef typename viennagrid::result_of::edge<MeshType> ::type EdgeType; typedef std::vector<double> value_type; displacement_current_wrapper(DeviceType const & device, PotentialAccessorType const & potential, OldPotentialAccessorType const & old_potential, double rtime ) : _device(device), _potential(potential), _old_potential(old_potential), _rtime(rtime) { } double operator()(EdgeType const & edge) const { viennashe::detail::displacement_current_on_edge<DeviceType, PotentialAccessorType, OldPotentialAccessorType> eval(_device, _potential, _old_potential, _rtime); return eval(edge); } value_type operator()(VertexType const & vertex) const { typedef typename viennagrid::result_of::const_edge_range<VertexType>::type EdgeOnVertexContainer; typedef viennashe::util::no_contact_filter<DeviceType> PotentialFilterType; PotentialFilterType poisson_filter(_device); viennashe::detail::displacement_current_on_edge<DeviceType, PotentialAccessorType, OldPotentialAccessorType> edge_eval(_device, _potential, _old_potential, _rtime); std::vector<double> Jd(3); Jd[0] = 0; Jd[1] = 0; Jd[2] = 0; viennashe::util::value_holder_functor<PointType> result; EdgeOnVertexContainer edges_on_vertex(vertex, _device.mesh()); viennashe::util::dual_box_flux_to_vertex(vertex, edges_on_vertex, result, edge_eval, poisson_filter, poisson_filter); for (std::size_t i=0; i < (PointType::dim) ; ++i) Jd[i] = result()[i]; return Jd; } // operator() private: DeviceType const & _device; PotentialAccessorType const & _potential; OldPotentialAccessorType const & _old_potential; double _rtime; }; // displacement_current_wrapper */ /** @brief Convenience function for writing the displacement current to the mesh. * * @param device The device (includes a ViennaGrid mesh) on which simulation is carried out * @param rtime 1.0/dt * @param potential The quantity accessor for the potential of the current time step * @param old_potential The quantity accessor for the potential of the old time step * @param quantity_name String identifying the current density */ /* template <typename DeviceType, typename PotentialAccessor, typename OldPotentialAccessorType, typename ContainerType> void write_displacement_current_to_container(DeviceType const & device, PotentialAccessor const & potential, PotentialAccessor const & old_potential, double rtime, ContainerType & container) { displacement_current_wrapper<DeviceType, PotentialAccessor, OldPotentialAccessorType> Jd(device, potential, old_potential, rtime); viennashe::she::write_macroscopic_quantity_to_container(device, Jd, container); }*/ } // viennashe #endif
37.066038
176
0.634767
[ "mesh", "vector" ]