blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
c2a78756d5bf413472c37153bbeba6a8a6cc8567
57523e0fbd707ff1a42b230656feb0f2cf601707
/service/switch-partitioning/SwitchEquivFinder.cpp
c50db0c0a389228bdd25a9033ee71d27c349acf0
[ "MIT" ]
permissive
jiangtao89/redex
4b41a96569a7f1909c344d8ea0183ba0f6258d15
38821967b0b83125e33c28469c03c04a548b4032
refs/heads/master
2023-07-10T06:58:52.488304
2023-06-28T17:49:57
2023-06-28T17:49:57
103,086,020
0
0
null
null
null
null
UTF-8
C++
false
false
23,241
cpp
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "SwitchEquivFinder.h" #include <algorithm> #include <queue> #include <vector> #include "ConstantPropagationAnalysis.h" #include "ReachingDefinitions.h" #include "SourceBlocks.h" #include "StlUtil.h" #include "Trace.h" namespace { // Return true if any of the sources of `insn` are `reg`. bool has_src(IRInstruction* insn, reg_t reg) { for (size_t i = 0; i < insn->srcs_size(); ++i) { if (insn->src(i) == reg) { return true; } } return false; } bool equals(const SwitchEquivFinder::InstructionSet& a, const SwitchEquivFinder::InstructionSet& b) { if (a.size() != b.size()) { return false; } const auto& has_equivalent = [&b](const std::pair<reg_t, IRInstruction*>& it) { const auto& search = b.find(it.first); if (search != b.end()) { bool just_one_null = (search->second == nullptr) != (it.second == nullptr); if (just_one_null) { return false; } bool both_null = search->second == nullptr && it.second == nullptr; if (both_null || *search->second == *it.second) { return true; } } return false; }; for (auto it = a.begin(); it != a.end(); ++it) { if (!has_equivalent(*it)) { return false; } } return true; } // NOTE: instructions here may need to be relocated to leaf blocks. See // copy_extra_loads_to_leaf_block below and keep that functionality up to date // with this check. bool is_valid_load_for_nonleaf(IROpcode op) { return opcode::is_a_literal_const(op) || op == OPCODE_CONST_CLASS || opcode::is_move_result_pseudo_object(op); } // Return true if this block is a leaf. // Any block that is not part of the if/switch tree is considered a leaf. bool is_leaf(cfg::ControlFlowGraph* cfg, cfg::Block* b, reg_t reg) { // non-leaf nodes only have GOTO and BRANCH outgoing edges if (cfg->get_succ_edge_if(b, [](const cfg::Edge* e) { return e->type() == cfg::EDGE_GHOST || e->type() == cfg::EDGE_THROW; }) != nullptr) { return true; } const auto& last = b->get_last_insn(); if (last == b->end()) { // No instructions in this block => can't be part of the switching logic => // must be a leaf return true; } for (const auto& mie : InstructionIterable(b)) { auto insn = mie.insn; auto op = insn->opcode(); if (!(is_valid_load_for_nonleaf(op) || opcode::is_branch(op))) { // non-leaf nodes only have const and branch instructions return true; } if (insn->has_dest() && (insn->dest() == reg || (insn->dest_is_wide() && insn->dest() + 1 == reg))) { // Overwriting the switching reg marks the end of the switch construct return true; } } auto last_insn = last->insn; auto last_op = last_insn->opcode(); if (opcode::is_branch(last_op) && has_src(last_insn, reg)) { // The only non-leaf block is one that branches on the switching reg return false; } // Any other block must be a leaf return true; } // For the leaf, check if the non-leaf predecessor block contributes to any // extra loads. This is a check so that if this leaf is one of multiple that has // the same case, we can determine if dropping the later (in execution order) // would erroneously lose track of some surviving/relevant load. bool pred_creates_extra_loads(const SwitchEquivFinder::ExtraLoads& extra_loads, cfg::Block* leaf) { // There is probably a more convenient way to do this, but this condition // being hit should be quite rare (probably doesn't matter this is loopy). std::unordered_set<IRInstruction*> insns; for (const auto& [b, map] : extra_loads) { for (const auto& [reg, insn] : map) { insns.emplace(insn); } } for (auto e : leaf->preds()) { auto block = e->src(); for (auto it = block->begin(); it != block->end(); it++) { if (it->type == MFLOW_OPCODE && insns.count(it->insn) > 0) { return true; } } } return false; } /* * Checks possible ConstantValue domains for if they are known/supported for * switching over, and returns the key. */ class key_creating_visitor : public boost::static_visitor<SwitchEquivFinder::SwitchingKey> { public: key_creating_visitor() {} SwitchEquivFinder::SwitchingKey operator()( const SignedConstantDomain& dom) const { if (dom.is_top() || dom.get_constant() == boost::none) { return SwitchEquivFinder::DefaultCase{}; } // It's safe to cast down to 32 bits because long values can't be used in // switch statements. return static_cast<int32_t>(*dom.get_constant()); } SwitchEquivFinder::SwitchingKey operator()( const ConstantClassObjectDomain& dom) const { if (dom.is_top() || dom.get_constant() == boost::none) { return SwitchEquivFinder::DefaultCase{}; } return *dom.get_constant(); } template <typename Domain> SwitchEquivFinder::SwitchingKey operator()(const Domain&) const { return SwitchEquivFinder::DefaultCase{}; } }; } // namespace std::ostream& operator<<(std::ostream& os, const SwitchEquivFinder::DefaultCase&) { return os << "DEFAULT"; } // All DefaultCase structs should be considered equal. bool operator<(const SwitchEquivFinder::DefaultCase&, const SwitchEquivFinder::DefaultCase&) { return false; } namespace cp = constant_propagation; SwitchEquivFinder::SwitchEquivFinder( cfg::ControlFlowGraph* cfg, const cfg::InstructionIterator& root_branch, reg_t switching_reg, uint32_t leaf_duplication_threshold, std::shared_ptr<constant_propagation::intraprocedural::FixpointIterator> fixpoint_iterator, DuplicateCaseStrategy duplicates_strategy) : m_cfg(cfg), m_root_branch(root_branch), m_switching_reg(switching_reg), m_leaf_duplication_threshold(leaf_duplication_threshold), m_fixpoint_iterator(std::move(fixpoint_iterator)), m_duplicates_strategy(duplicates_strategy) { { // make sure the input is well-formed auto insn = m_root_branch->insn; auto op = insn->opcode(); always_assert(opcode::is_branch(op)); always_assert(has_src(insn, m_switching_reg)); } const auto& leaves = find_leaves(); if (leaves.empty()) { m_extra_loads.clear(); m_success = false; return; } find_case_keys(leaves); } // Starting from the branch instruction, find all reachable branch // instructions (with no intervening leaf blocks) that also have `reg` as a // source (and without `reg` being overwritten) // // While we're searching for the leaf blocks, keep track of any constant loads // that occur between the root branch and the leaf block. Put those in // `m_extra_loads`. std::vector<cfg::Edge*> SwitchEquivFinder::find_leaves() { std::vector<cfg::Edge*> leaves; // Traverse the tree in an depth first order so that the extra loads are // tracked in the same order that they will be executed at runtime std::unordered_map<cfg::Block*, bool> block_to_is_leaf; auto block_is_leaf = [&](cfg::Block* b) { auto search = block_to_is_leaf.find(b); if (search != block_to_is_leaf.end()) { return search->second; } auto ret = is_leaf(m_cfg, b, m_switching_reg); block_to_is_leaf[b] = ret; return ret; }; std::function<bool(cfg::Block*, InstructionSet, const std::vector<SourceBlock*>&)> recurse; std::vector<std::pair<cfg::Edge*, cfg::Block*>> edges_to_move; std::unordered_map<cfg::Block*, std::vector<SourceBlock*>> source_blocks_to_move; recurse = [&](cfg::Block* b, const InstructionSet& loads, const std::vector<SourceBlock*>& source_blocks_in) { // `loads` represents the state of the registers after evaluating `b`. std::vector<cfg::Edge*> ordered_edges(b->succs()); // NOTE: To maintain proper order of duplicated cases, non leafs successors // will be encountered first. std::stable_sort(ordered_edges.begin(), ordered_edges.end(), [&](const cfg::Edge* a, const cfg::Edge* b) { return !block_is_leaf(a->target()) && block_is_leaf(b->target()); }); for (cfg::Edge* succ : ordered_edges) { cfg::Block* next = succ->target(); uint16_t count = ++m_visit_count[next]; if (count > next->preds().size()) { // Infinite loop. Bail TRACE(SWITCH_EQUIV, 2, "Failure Reason: Detected loop"); TRACE(SWITCH_EQUIV, 3, "%s", SHOW(*m_cfg)); return false; } auto source_blocks_out = std::ref(source_blocks_in); if (block_is_leaf(next)) { leaves.push_back(succ); auto& source_blocks_vec = source_blocks_to_move[succ->target()]; source_blocks_vec.insert(source_blocks_vec.end(), source_blocks_in.begin(), source_blocks_in.end()); const auto& pair = m_extra_loads.emplace(next, loads); bool already_there = !pair.second; if (already_there) { // There are multiple ways to reach this leaf. Make sure the extra // loads are consistent. const auto& it = pair.first; const InstructionSet& existing_loads = it->second; if (!::equals(existing_loads, loads)) { if (next->num_opcodes() < m_leaf_duplication_threshold) { // A switch cannot represent this control flow graph unless we // duplicate this leaf. See the comment on // m_leaf_duplication_theshold for more details. always_assert(m_cfg->editable()); cfg::Block* copy = m_cfg->duplicate_block(next); edges_to_move.emplace_back(succ, copy); m_extra_loads.emplace(copy, loads); } else { TRACE(SWITCH_EQUIV, 2, "Failure Reason: divergent entry states"); TRACE(SWITCH_EQUIV, 3, "B%zu in %s", next->id(), SHOW(*m_cfg)); return false; } } } } else { boost::optional<InstructionSet> next_loads; std::vector<SourceBlock*> next_source_blocks; for (const auto& mie : *next) { if (mie.type == MFLOW_SOURCE_BLOCK) { if (&source_blocks_out.get() == &source_blocks_in) { next_source_blocks = source_blocks_in; source_blocks_out = next_source_blocks; } next_source_blocks.push_back(mie.src_block.get()); continue; } if (mie.type != MFLOW_OPCODE) { continue; } // A chain of if-else blocks loads constants into register to do the // comparisons, however, the leaf blocks may also use those registers, // so this function finds any loads that occur in non-leaf blocks that // lead to `leaf`. auto insn = mie.insn; auto op = insn->opcode(); if (is_valid_load_for_nonleaf(op)) { if (next_loads == boost::none) { // Copy loads here because we only want these loads to propagate // to successors of `next`, not any other successors of `b` next_loads = loads; } if (insn->has_dest()) { // Overwrite any previous mapping for this dest register. (*next_loads)[insn->dest()] = insn; if (insn->dest_is_wide()) { // And don't forget to clear out the upper register of wide // loads. (*next_loads)[insn->dest() + 1] = nullptr; } } } } bool success = false; if (next_loads != boost::none) { success = recurse(next, *next_loads, source_blocks_out.get()); } else { success = recurse(next, loads, source_blocks_out.get()); } if (!success) { return false; } } } return true; }; const auto& bail = [&leaves, this, &edges_to_move]() { // While traversing the CFG, we may have duplicated case blocks (see the // comment on m_leaf_duplication_threshold for more details). If we did not // successfully find a switch equivalent here, we need to remove those // blocks. std::vector<cfg::Block*> blocks_to_remove; for (const auto& pair : edges_to_move) { cfg::Block* copy = pair.second; blocks_to_remove.push_back(copy); } m_cfg->remove_blocks(blocks_to_remove); leaves.clear(); return leaves; }; bool success = recurse(m_root_branch.block(), {}, {}); if (!success) { return bail(); } normalize_extra_loads(block_to_is_leaf); if (!m_extra_loads.empty()) { // Make sure there are no other ways to reach the leaf nodes. If there were // other ways to reach them, m_extra_loads would be incorrect. for (const auto& block_and_count : m_visit_count) { cfg::Block* b = block_and_count.first; uint16_t count = block_and_count.second; if (b->preds().size() > count) { TRACE(SWITCH_EQUIV, 2, "Failure Reason: Additional ways to reach blocks"); TRACE(SWITCH_EQUIV, 3, " B%zu has %zu preds but was hit %d times in \n%s", b->id(), b->preds().size(), count, SHOW(*m_cfg)); return bail(); } } } success = move_edges(edges_to_move); if (!success) { return bail(); } for (auto& [blk, source_blocks] : source_blocks_to_move) { auto it_insert = source_blocks::find_first_block_insert_point(blk); for (auto source_block : source_blocks) { blk->insert_before(it_insert, std::make_unique<SourceBlock>(*source_block)); } } if (leaves.empty()) { TRACE(SWITCH_EQUIV, 2, "Failure Reason: No leaves found"); TRACE(SWITCH_EQUIV, 3, "%s", SHOW(*m_cfg)); } return leaves; } bool SwitchEquivFinder::move_edges( const std::vector<std::pair<cfg::Edge*, cfg::Block*>>& edges_to_move) { for (const auto& pair : edges_to_move) { cfg::Edge* edge = pair.first; cfg::Block* orig = edge->target(); for (cfg::Edge* orig_succ : orig->succs()) { always_assert_log(orig_succ != nullptr, "B%zu in %s", orig->id(), SHOW(*m_cfg)); if (orig_succ->type() == cfg::EDGE_GOTO && orig_succ->target()->starts_with_move_result()) { // Two blocks can't share a single move-result-psuedo TRACE(SWITCH_EQUIV, 2, "Failure Reason: Can't share move-result-pseudo"); TRACE(SWITCH_EQUIV, 3, "%s", SHOW(*m_cfg)); return false; } } } std::vector<cfg::Block*> blocks_to_remove; for (const auto& pair : edges_to_move) { cfg::Edge* edge = pair.first; cfg::Block* orig = edge->target(); cfg::Block* copy = pair.second; const auto& copy_loads = m_extra_loads.find(copy); const auto& orig_loads = m_extra_loads.find(orig); const auto& have_copy_loads = copy_loads != m_extra_loads.end(); const auto& have_orig_loads = orig_loads != m_extra_loads.end(); bool just_one_null = have_copy_loads != have_orig_loads; bool both_null = !have_copy_loads && !have_orig_loads; if (!just_one_null && (both_null || ::equals(copy_loads->second, orig_loads->second))) { // When we normalized the extra loads, the copy and original may have // converged to the same state. We don't need the duplicate block anymore // in this case. blocks_to_remove.push_back(copy); continue; } // copy on purpose so we can alter in the loop // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) const auto orig_succs = orig->succs(); for (cfg::Edge* orig_succ : orig_succs) { cfg::Edge* copy_succ = new cfg::Edge(*orig_succ); m_cfg->add_edge(copy_succ); m_cfg->set_edge_source(copy_succ, copy); } m_cfg->set_edge_target(edge, copy); } m_cfg->remove_blocks(blocks_to_remove); return true; } // Before this function, m_extra_loads is overly broad // * Remove loads that are never used outside the if-else chain blocks // * Remove empty lists of loads from the map (possibly emptying the map) void SwitchEquivFinder::normalize_extra_loads( const std::unordered_map<cfg::Block*, bool>& block_to_is_leaf) { // collect the extra loads std::unordered_set<IRInstruction*> extra_loads; for (const auto& [b, is_leaf] : block_to_is_leaf) { if (is_leaf) { continue; } for (const auto& mie : InstructionIterable(b)) { if (is_valid_load_for_nonleaf(mie.insn->opcode())) { extra_loads.insert(mie.insn); } } } // Use ReachingDefinitions to find the loads that are used outside the if-else // chain blocks std::unordered_set<IRInstruction*> used_defs; reaching_defs::FixpointIterator fixpoint_iter(*m_cfg); fixpoint_iter.run(reaching_defs::Environment()); for (cfg::Block* block : m_cfg->blocks()) { auto search = block_to_is_leaf.find(block); if (search != block_to_is_leaf.end() && !search->second) { continue; } reaching_defs::Environment defs_in = fixpoint_iter.get_entry_state_at(block); if (defs_in.is_bottom()) { continue; } for (const auto& mie : InstructionIterable(block)) { auto insn = mie.insn; for (size_t i = 0; i < insn->srcs_size(); ++i) { auto src = insn->src(i); const auto& defs = defs_in.get(src); always_assert_log(!defs.is_top(), "Undefined register v%u", src); for (IRInstruction* def : defs.elements()) { if (extra_loads.count(def)) { used_defs.insert(def); } } } fixpoint_iter.analyze_instruction(insn, &defs_in); } } // Remove loads that aren't used outside the if-else chain blocks for (auto& block_and_insns : m_extra_loads) { InstructionSet& insns = block_and_insns.second; std20::erase_if(insns, [&used_defs](auto& p) { return used_defs.count(p.second) == 0; }); } // Remove empty instruction lists from `m_extra_loads` (possibly emptying it) std20::erase_if(m_extra_loads, [](auto& p) { return p.second.empty(); }); } cp::intraprocedural::FixpointIterator& SwitchEquivFinder::get_analyzed_cfg() { if (!m_fixpoint_iterator) { m_fixpoint_iterator = std::make_shared<cp::intraprocedural::FixpointIterator>(*m_cfg, Analyzer()); m_fixpoint_iterator->run(ConstantEnvironment()); } return *m_fixpoint_iterator; } // Use a sparta analysis to find the value of reg at the beginning of each leaf // block void SwitchEquivFinder::find_case_keys(const std::vector<cfg::Edge*>& leaves) { // We use the fixpoint iterator to infer the values of registers at different // points in the program. Especially `m_switching_reg`. auto& fixpoint = get_analyzed_cfg(); // return true on success // return false on failure (there was a conflicting entry already in the map) const auto& insert = [this](const SwitchingKey& key, cfg::Block* b) { const auto& pair = m_key_to_case.emplace(key, b); const auto& it = pair.first; bool already_there = !pair.second; if (already_there && it->second != b) { if (m_duplicates_strategy == NOT_ALLOWED) { TRACE(SWITCH_EQUIV, 2, "Failure Reason: Divergent key to block mapping."); TRACE(SWITCH_EQUIV, 3, "%s", SHOW(*m_cfg)); return false; } else if (m_duplicates_strategy == EXECUTION_ORDER) { if (pred_creates_extra_loads(m_extra_loads, it->second)) { TRACE(SWITCH_EQUIV, 2, "Failure Reason: Divergent key to block mapping with extra " "loads."); TRACE(SWITCH_EQUIV, 3, "%s", SHOW(*m_cfg)); return false; } TRACE(SWITCH_EQUIV, 2, "Updating key to block mapping for duplicate case; B%zu will be " "supplanted by B%zu.", it->second->id(), b->id()); it->second = b; } else { not_reached(); } } return true; }; // returns the value of `m_switching_reg` if the leaf is reached via this edge const auto& get_case_key = [this, &fixpoint](cfg::Edge* edge_to_leaf) -> SwitchingKey { // Get the inferred value of m_switching_reg at the end of `edge_to_leaf` // but before the beginning of the leaf block because we would lose the // information by merging all the incoming edges. auto env = fixpoint.get_exit_state_at(edge_to_leaf->src()); env = fixpoint.analyze_edge(edge_to_leaf, env); const auto& val = env.get(m_switching_reg); return ConstantValue::apply_visitor(key_creating_visitor(), val); }; for (cfg::Edge* edge_to_leaf : leaves) { const auto& case_key = get_case_key(edge_to_leaf); bool success = insert(case_key, edge_to_leaf->target()); if (!success) { // If we didn't insert into result for this leaf node, abort the entire // operation because we don't want to present incomplete information about // the possible successors m_key_to_case.clear(); m_extra_loads.clear(); m_success = false; return; } } m_success = true; } std::vector<cfg::Block*> SwitchEquivFinder::visited_blocks() const { std::vector<cfg::Block*> result; result.reserve(1 + m_visit_count.size()); result.emplace_back(m_root_branch.block()); for (auto entry : m_visit_count) { result.emplace_back(entry.first); } return result; } size_t SwitchEquivEditor::copy_extra_loads_to_leaf_block( const SwitchEquivFinder::ExtraLoads& extra_loads, cfg::ControlFlowGraph* cfg, cfg::Block* leaf) { size_t changes = 0; auto push_front = [&](IRInstruction* insn) { auto copy = new IRInstruction(*insn); TRACE(SWITCH_EQUIV, 4, "adding %s to B%zu", SHOW(copy), leaf->id()); changes++; leaf->push_front(copy); }; const auto& loads_for_this_leaf = extra_loads.find(leaf); if (loads_for_this_leaf != extra_loads.end()) { for (const auto& register_and_insn : loads_for_this_leaf->second) { IRInstruction* insn = register_and_insn.second; if (insn != nullptr) { // null instruction pointers are used to signify the upper half of // a wide load. push_front(insn); if (opcode::is_move_result_pseudo_object(insn->opcode())) { auto primary_it = cfg->primary_instruction_of_move_result(cfg->find_insn(insn)); push_front(primary_it->insn); } } } } return changes; } size_t SwitchEquivEditor::copy_extra_loads_to_leaf_blocks( const SwitchEquivFinder& finder, cfg::ControlFlowGraph* cfg) { size_t result = 0; const auto& extra_loads = finder.extra_loads(); for (const auto& pair : finder.key_to_case()) { result += copy_extra_loads_to_leaf_block(extra_loads, cfg, pair.second); } return result; }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
c6bfb77fb1afdbdc7c9bb44b2eb92a659ed3b70e
aecf4944523b50424831f8af3debef67e3163b97
/xrLC/OpenMesh/Tools/Decimater/ModNormalFlippingT.hh
6a4f81f69cb50b0df42050048ea4f244ca27b322
[]
no_license
xrLil-Batya/gitxray
bc8c905444e40c4da5d77f69d03b41d5b9cec378
58aaa5185f7a682b8cf5f5f376a2e5b6ca16fed4
refs/heads/main
2023-03-31T07:43:57.500002
2020-12-12T21:12:25
2020-12-12T21:12:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,165
hh
//============================================================================= // // OpenMesh // Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen // www.openmesh.org // //----------------------------------------------------------------------------- // // License // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published // by the Free Software Foundation, version 2. // // 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // //----------------------------------------------------------------------------- // // $Revision: 1.14 $ // $Date: 2004/01/12 17:36:30 $ // //============================================================================= /** \file ModNormalFlippingT.hh */ //============================================================================= // // CLASS ModNormalFlipping // //============================================================================= #ifndef OPENMESH_DECIMATER_MODNORMALFLIPPING_HH #define OPENMESH_DECIMATER_MODNORMALFLIPPING_HH //== INCLUDES ================================================================= #include <OpenMesh/Tools/Decimater/ModBaseT.hh> //== NAMESPACES =============================================================== namespace OpenMesh { // BEGIN_NS_OPENMESH namespace Decimater { // BEGIN_NS_DECIMATER //== CLASS DEFINITION ========================================================= /** Decimating module to avoid flipping of faces. * * This module can be used only as a binary module. The criterion * of allowing/disallowing the collapse is the angular deviation between * the face normal of the orignal faces and normals of the faces after the * collapse. The collapse will pass the test, if the deviation is below * a given threshold. */ template <typename DecimaterT> class ModNormalFlippingT : public ModBaseT< DecimaterT > { public: DECIMATING_MODULE( ModNormalFlippingT, DecimaterT, NormalFlipping ); public: /// Constructor ModNormalFlippingT( DecimaterT &_dec) : Base(_dec, true) { set_max_normal_deviation( 90.0f ); } ~ModNormalFlippingT() { } public: /** Compute collapse priority due to angular deviation of face normals * before and after a collapse. * * -# Compute for each adjacent face of \c _ci.v0 the face * normal if the collpase would be executed. * * -# Prevent the collapse, if the angle between the original and the * new normal is below a given threshold. * * \param _ci The collapse description * \return LEGAL_COLLAPSE or ILLEGAL_COLLAPSE * * \see set_max_normal_deviation() */ float collapse_priority(const CollapseInfo& _ci) { // simulate collapse mesh().set_point(_ci.v0, _ci.p1); // check for flipping normals typename Mesh::ConstVertexFaceIter vf_it(mesh(), _ci.v0); typename Mesh::FaceHandle fh; typename Mesh::Scalar c(1.0); for (; vf_it; ++vf_it) { fh = vf_it.handle(); if (fh != _ci.fl && fh != _ci.fr) { typename Mesh::Normal n1 = mesh().normal(fh); typename Mesh::Normal n2 = mesh().calc_face_normal(fh); c = dot(n1, n2); if (c < min_cos_) break; } } // undo simulation changes mesh().set_point(_ci.v0, _ci.p0); return float( (c < min_cos_) ? ILLEGAL_COLLAPSE : LEGAL_COLLAPSE ); } public: /// get normal deviation float max_normal_deviation() const { return max_deviation_ / M_PI * 180.0; } /// \deprecated float normal_deviation() const { return max_normal_deviation(); } /** Set normal deviation * * Set the maximum angular deviation of the orignal normal and the new * normal in degrees. */ void set_max_normal_deviation(float _f) { max_deviation_ = _f / 180.0 * M_PI; min_cos_ = cos(max_deviation_); } /// \deprecated void set_normal_deviation(float _f) { set_max_normal_deviation(_f); } private: // hide this method void set_binary(bool _b) {} private: // maximum normal deviation double max_deviation_, min_cos_; }; //============================================================================= } // END_NS_DECIMATER } // END_NS_OPENMESH //============================================================================= #endif // OPENACG_MODNORMALFLIPPING_HH defined //=============================================================================
[ "oles@localhost" ]
oles@localhost
10cef97d99142a4d34aa1632c31a48c8036dcc36
e44b5fa1188f2e9f7b6da850fc3dfef7560bfd93
/sublime code/ec-99-c.cpp
45dfcb1ce0415c50edcb87aa2f7dd29f3730c34b
[]
no_license
nikhil-03/c-codes
94555df1de4d5ebac89bf8c1139148f3fb213dfa
7a215e5bf8e14cce4753dc9cfff0b67c0c24cb20
refs/heads/main
2023-05-03T14:05:03.736929
2021-05-27T08:03:33
2021-05-27T08:03:33
368,955,044
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int #define V vector<ll> #define VV vector<vector<ll>> #define M map<ll,ll> #define pb push_back // int gcd(int a,int b) // { // if(b==0)return a; // return gcd(b,a%b); // } void solve() { int x,y; cin>>x>>y; cout<<x-1<<" "<<y; } int main() { int t; cin>>t; while(t--) { solve(); cout<<endl; } }
[ "nikhilprakash2012@gmail.com" ]
nikhilprakash2012@gmail.com
b34d84636c59a67fd80cca0688eaa9ecb6ff230a
77686049af3fccb13febcc95f70fa77176a13be3
/adobe_platform_libraries/test/sentences/subject_concept.hpp
e2efc8f0eef8b02e919a59a312828f4e2fc8ac5c
[]
no_license
sehe/legacy
c02dc53f51e3d22ca876064840d6157636c195c4
c9507c867999c2f9492449bcf0811ef7f4391998
refs/heads/master
2020-12-30T19:11:11.898443
2013-08-22T23:34:13
2013-08-22T23:34:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,548
hpp
/* Copyright 2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /**************************************************************************************************/ #ifndef ADOBE_SENTENCES_SUBJECT_CONCEPT_HPP #define ADOBE_SENTENCES_SUBJECT_CONCEPT_HPP /**************************************************************************************************/ #include <boost/concept_check.hpp> #include <boost/ref.hpp> #include <adobe/any_regular.hpp> /*************************************************************************************************/ namespace adobe { /*************************************************************************************************/ #ifdef ADOBE_HAS_CPLUS0X_CONCEPTS /*************************************************************************************************/ auto concept SubjectConcept<typename Subject> //: RegularConcept<Subject> -- Subjects not yet regular : std::CopyConstructible<Subject> { template subject_type; subject_type project(Subject& v) const; }; /*************************************************************************************************/ auto concept SubjectMFConcept<typename Subject> //: RegularConcept<Subject> -- Subjects not yet regular : std::CopyConstructible<Subject> { template subject_type = Subject::subject_type; subject_type Subject::project(model_type value) const; }; /*************************************************************************************************/ template <SubjectMFConcept T> concept_map SubjectConcept<T> { typedef SubjectMFConcept<T>::subject_type subject_type; inline subject_type project(T& v) const { return v.project(); } }; /*************************************************************************************************/ template <SubjectConcept T> concept_map SubjectConcept<boost::reference_wrapper<T> > { typedef SubjectConcept<T>::subject_type subject_type; inline subject_type project(boost::reference_wrapper<T>& r) const { return SubjectConcept<T>::project(static_cast<const T&>(r)); } }; /*************************************************************************************************/ #else /*************************************************************************************************/ template <class Subject> struct subject_type { typedef typename boost::unwrap_reference<Subject>::type::subject_type type; }; /*************************************************************************************************/ #ifndef ADOBE_SENTENCES_DIRECT_OBJECT_CONCEPT_HPP template <class S> // S models Subject inline typename subject_type<S>::type project(const S& v) { return v.project(); } #endif /*************************************************************************************************/ template <class T> struct SubjectConcept { typedef typename subject_type<T>::type subject_type; static subject_type project(const T& subject) { using adobe::project; // pick up default version which looks for member functions return project(subject); // unqualified to allow user versions } // Concept checking: //use pointers since not required to be default constructible T* t; void constraints() { // refinement of: // boost::function_requires<RegularConcept<T> >(); // not yet, Subjects not yet regular // boost::function_requires<boost::CopyConstructibleConcept<T> >(); // associated types: typedef subject_type associated_type; // operations: using adobe::project; // pick up default version which looks for member functions project(*t); } }; template <class T> struct SubjectConcept<boost::reference_wrapper<T> > : SubjectConcept<T> { void constraints() { //boost concept check lib gets confused on VC8 without this SubjectConcept<T>::constraints(); } }; /*************************************************************************************************/ // ADOBE_HAS_CPLUS0X_CONCEPTS #endif /*************************************************************************************************/ } //namespace adobe /**************************************************************************************************/ // ADOBE_SENTENCES_SUBJECT_CONCEPT_HPP #endif /**************************************************************************************************/
[ "sparent@adobe.com" ]
sparent@adobe.com
0deb0a45c677b1531f24f395d1f989d66fb98bbc
56f569bed3693f9c045dea5c801dd67e5a942a54
/src/examples/robot_simulation_models/turtlebot3_model/aruco_ros/aruco_ros/src/simple_single.cpp
5be3c25975142889e80e97f516af6e3241613c50
[]
no_license
dtbinh/Hybrid-ASP-Planning
be58732be4d15d5d4dd0c8153d65578926a1d6be
ad57c98fa4e0bab1457d7690bfe669efbf7b527a
refs/heads/main
2023-09-04T04:14:39.520930
2021-11-06T10:06:36
2021-11-06T10:06:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,774
cpp
#include <iostream> #include <aruco/aruco.h> #include <aruco/cvdrawingutils.h> #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <aruco_ros/aruco_ros_utils.h> #include <tf/transform_broadcaster.h> #include <tf/transform_listener.h> #include <visualization_msgs/Marker.h> #include <dynamic_reconfigure/server.h> #include <aruco_ros/ArucoThresholdConfig.h> #include <aruco_msgs/CheckActionEffect.h> #include <actionlib/client/simple_action_client.h> #include <geometry_msgs/PoseStamped.h> #include <aruco_msgs/CheckActionEffect.h> using namespace aruco; class ArucoSimple { private: cv::Mat inImage; cv::Mat actionDetectInImage; ros::Time action_curr_stamp; aruco::CameraParameters camParam; tf::StampedTransform rightToLeft; bool useRectifiedImages; MarkerDetector mDetector; vector<Marker> markers; ros::Subscriber cam_info_sub; bool cam_info_received; image_transport::Publisher image_pub; image_transport::Publisher debug_pub; ros::Publisher pose_pub; ros::Publisher transform_pub; ros::Publisher position_pub; ros::Publisher marker_pub; //rviz visualization marker ros::Publisher pixel_pub; std::string marker_frame; std::string camera_frame; std::string reference_frame; double marker_size; int marker_id; bool rotate_marker_axis_; ros::NodeHandle nh; image_transport::ImageTransport it; image_transport::Subscriber image_sub, action_check_sub; tf::TransformListener _tfListener; dynamic_reconfigure::Server<aruco_ros::ArucoThresholdConfig> dyn_rec_server; public: bool action_effect_achieved; bool aruco_detected; public: ArucoSimple(ros::NodeHandle& nh) : cam_info_received(false), nh("~"), it(nh) { std::string refinementMethod; nh.param<std::string>("corner_refinement", refinementMethod, "LINES"); if ( refinementMethod == "SUBPIX" ) mDetector.setCornerRefinementMethod(aruco::MarkerDetector::SUBPIX); else if ( refinementMethod == "HARRIS" ) mDetector.setCornerRefinementMethod(aruco::MarkerDetector::HARRIS); else if ( refinementMethod == "NONE" ) mDetector.setCornerRefinementMethod(aruco::MarkerDetector::NONE); else mDetector.setCornerRefinementMethod(aruco::MarkerDetector::LINES); //Print parameters of aruco marker detector: ROS_INFO_STREAM("Corner refinement method: " << mDetector.getCornerRefinementMethod()); ROS_INFO_STREAM("Threshold method: " << mDetector.getThresholdMethod()); double th1, th2; mDetector.getThresholdParams(th1, th2); ROS_INFO_STREAM("Threshold method: " << " th1: " << th1 << " th2: " << th2); float mins, maxs; mDetector.getMinMaxSize(mins, maxs); ROS_INFO_STREAM("Marker size min: " << mins << " max: " << maxs); ROS_INFO_STREAM("Desired speed: " << mDetector.getDesiredSpeed()); image_sub = it.subscribe("/image", 1, &ArucoSimple::image_callback, this); action_check_sub = it.subscribe("/image", 1, &ArucoSimple::action_check_image_callback, this); cam_info_sub = nh.subscribe("/camera_info", 1, &ArucoSimple::cam_info_callback, this); image_pub = it.advertise("result", 1); debug_pub = it.advertise("debug", 1); pose_pub = nh.advertise<geometry_msgs::PoseStamped>("pose", 100); transform_pub = nh.advertise<geometry_msgs::TransformStamped>("transform", 100); position_pub = nh.advertise<geometry_msgs::Vector3Stamped>("position", 100); marker_pub = nh.advertise<visualization_msgs::Marker>("marker", 10); pixel_pub = nh.advertise<geometry_msgs::PointStamped>("pixel", 10); nh.param<double>("marker_size", marker_size, 0.05); nh.param<int>("marker_id", marker_id, 300); nh.param<std::string>("reference_frame", reference_frame, ""); nh.param<std::string>("camera_frame", camera_frame, ""); nh.param<std::string>("marker_frame", marker_frame, ""); nh.param<bool>("image_is_rectified", useRectifiedImages, true); nh.param<bool>("rotate_marker_axis", rotate_marker_axis_, true); ROS_ASSERT(camera_frame != "" && marker_frame != ""); if ( reference_frame.empty() ) reference_frame = camera_frame; ROS_INFO("Aruco node started with marker size of %f m and marker id to track: %d", marker_size, marker_id); ROS_INFO("Aruco node will publish pose to TF with %s as parent and %s as child.", reference_frame.c_str(), marker_frame.c_str()); dyn_rec_server.setCallback(boost::bind(&ArucoSimple::reconf_callback, this, _1, _2)); action_effect_achieved = false; aruco_detected = false; } bool GoToActionEffectCheck(aruco_msgs::CheckActionEffect::Request &req, aruco_msgs::CheckActionEffect::Response &res) { std::cout << "Before: GoToActionEffectCheck response: " << req.aruco_id << std::endl; aruco_detection(actionDetectInImage, action_curr_stamp); std::cout << "After: GoToActionEffectCheck response: " << action_effect_achieved << std::endl; res.detection_result = action_effect_achieved; return true; } bool getTransform(const std::string& refFrame, const std::string& childFrame, tf::StampedTransform& transform) { std::string errMsg; if ( !_tfListener.waitForTransform(refFrame, childFrame, ros::Time(0), ros::Duration(0.5), ros::Duration(0.01), &errMsg)) { ROS_ERROR_STREAM("Unable to get pose from TF: " << errMsg); return false; } else { try { _tfListener.lookupTransform( refFrame, childFrame, ros::Time(0), transform); //get latest available } catch ( const tf::TransformException& e) { ROS_ERROR_STREAM("Error in lookupTransform of " << childFrame << " in " << refFrame); return false; } } return true; } void aruco_detection(cv::Mat inImage, ros::Time curr_stamp) { action_effect_achieved = false; aruco_detected = false; static tf::TransformBroadcaster br; //detection results will go into "markers" markers.clear(); //Ok, let's detect mDetector.detect(inImage, markers, camParam, marker_size, false); //for each marker, draw info and its boundaries in the image for(size_t i=0; i<markers.size(); ++i) { // only publishing the selected marker if(markers[i].id == marker_id) { action_effect_achieved = true; aruco_detected = true; tf::Transform transform = aruco_ros::arucoMarker2Tf(markers[i], rotate_marker_axis_); tf::StampedTransform cameraToReference; cameraToReference.setIdentity(); if ( reference_frame != camera_frame ) { getTransform(reference_frame, camera_frame, cameraToReference); } transform = static_cast<tf::Transform>(cameraToReference) * static_cast<tf::Transform>(rightToLeft) * transform; tf::StampedTransform stampedTransform(transform, curr_stamp, reference_frame, marker_frame); br.sendTransform(stampedTransform); geometry_msgs::PoseStamped poseMsg; tf::poseTFToMsg(transform, poseMsg.pose); poseMsg.header.frame_id = reference_frame; poseMsg.header.stamp = curr_stamp; pose_pub.publish(poseMsg); geometry_msgs::TransformStamped transformMsg; tf::transformStampedTFToMsg(stampedTransform, transformMsg); transform_pub.publish(transformMsg); geometry_msgs::Vector3Stamped positionMsg; positionMsg.header = transformMsg.header; positionMsg.vector = transformMsg.transform.translation; position_pub.publish(positionMsg); geometry_msgs::PointStamped pixelMsg; pixelMsg.header = transformMsg.header; pixelMsg.point.x = markers[i].getCenter().x; pixelMsg.point.y = markers[i].getCenter().y; pixelMsg.point.z = 0; pixel_pub.publish(pixelMsg); //Publish rviz marker representing the ArUco marker patch visualization_msgs::Marker visMarker; visMarker.header = transformMsg.header; visMarker.id = 1; visMarker.type = visualization_msgs::Marker::CUBE; visMarker.action = visualization_msgs::Marker::ADD; visMarker.pose = poseMsg.pose; visMarker.scale.x = marker_size; visMarker.scale.y = 0.001; visMarker.scale.z = marker_size; visMarker.color.r = 1.0; visMarker.color.g = 0; visMarker.color.b = 0; visMarker.color.a = 1.0; visMarker.lifetime = ros::Duration(3.0); marker_pub.publish(visMarker); } // but drawing all the detected markers markers[i].draw(inImage,cv::Scalar(0,0,255),2); } //draw a 3d cube in each marker if there is 3d info if(camParam.isValid() && marker_size>0) { for(size_t i=0; i<markers.size(); ++i) { CvDrawingUtils::draw3dAxis(inImage, markers[i], camParam); } } } void action_check_image_callback(const sensor_msgs::ImageConstPtr& msg) { ros::Time curr_stamp = msg->header.stamp; cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8); actionDetectInImage = cv_ptr->image; action_curr_stamp = curr_stamp; } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s in action_check_image_callback", e.what()); return; } } void image_callback(const sensor_msgs::ImageConstPtr& msg) { if ((image_pub.getNumSubscribers() == 0) && (debug_pub.getNumSubscribers() == 0) && (pose_pub.getNumSubscribers() == 0) && (transform_pub.getNumSubscribers() == 0) && (position_pub.getNumSubscribers() == 0) && (marker_pub.getNumSubscribers() == 0) && (pixel_pub.getNumSubscribers() == 0)) { ROS_DEBUG("No subscribers, not looking for aruco markers"); return; } static tf::TransformBroadcaster br; if(cam_info_received) { ros::Time curr_stamp = msg->header.stamp; cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8); inImage = cv_ptr->image; // aruco_detected = false; // aruco_detection(inImage, curr_stamp); markers.clear(); mDetector.detect(inImage, markers, camParam, marker_size, false); for (size_t i = 0; i < markers.size(); ++i) { if (markers[i].id == marker_id) { aruco_detected = true; tf::Transform transform = aruco_ros::arucoMarker2Tf(markers[i], rotate_marker_axis_); tf::StampedTransform cameraToReference; cameraToReference.setIdentity(); if ( reference_frame != camera_frame ) { getTransform(reference_frame, camera_frame, cameraToReference); } transform = static_cast<tf::Transform>(cameraToReference) * static_cast<tf::Transform>(rightToLeft) * transform; tf::StampedTransform stampedTransform(transform, curr_stamp, reference_frame, marker_frame); br.sendTransform(stampedTransform); geometry_msgs::PoseStamped poseMsg; tf::poseTFToMsg(transform, poseMsg.pose); poseMsg.header.frame_id = reference_frame; poseMsg.header.stamp = curr_stamp; pose_pub.publish(poseMsg); std::cout << "poseMsg = " << poseMsg << std::endl; // std::string actionserver = "/rosoclingo"; // actionlib::SimpleActionClient<rosoclingo::ROSoClingoAction> rosoclingo_action_client_(actionserver, true); // rosoclingo_action_client_.waitForServer(); // rosoclingo::ROSoClingoGoal asp_request_goal; // std::vector<std::string> object_names; // object_names.push_back("box"); // asp_request_goal.request = "possibleOrientation(red,a1)"; // asp_request_goal.information = object_names; // rosoclingo_action_client_.sendGoal(asp_request_goal); geometry_msgs::TransformStamped transformMsg; tf::transformStampedTFToMsg(stampedTransform, transformMsg); transform_pub.publish(transformMsg); geometry_msgs::Vector3Stamped positionMsg; positionMsg.header = transformMsg.header; positionMsg.vector = transformMsg.transform.translation; position_pub.publish(positionMsg); geometry_msgs::PointStamped pixelMsg; pixelMsg.header = transformMsg.header; pixelMsg.point.x = markers[i].getCenter().x; pixelMsg.point.y = markers[i].getCenter().y; pixelMsg.point.z = 0; pixel_pub.publish(pixelMsg); //Publish rviz marker representing the ArUco marker patch visualization_msgs::Marker visMarker; visMarker.header = transformMsg.header; visMarker.id = 1; visMarker.type = visualization_msgs::Marker::CUBE; visMarker.action = visualization_msgs::Marker::ADD; visMarker.pose = poseMsg.pose; visMarker.scale.x = marker_size; visMarker.scale.y = 0.001; visMarker.scale.z = marker_size; visMarker.color.r = 1.0; visMarker.color.g = 0; visMarker.color.b = 0; visMarker.color.a = 1.0; visMarker.lifetime = ros::Duration(3.0); marker_pub.publish(visMarker); } markers[i].draw(inImage,cv::Scalar(0,0,255),2); } std::cout << "In aruco_single: topic result = " << aruco_detected << std::endl; if(camParam.isValid() && marker_size>0) { for(size_t i=0; i<markers.size(); ++i) { CvDrawingUtils::draw3dAxis(inImage, markers[i], camParam); } } if(image_pub.getNumSubscribers() > 0) { //show input with augmented information cv_bridge::CvImage out_msg; out_msg.header.stamp = curr_stamp; out_msg.encoding = sensor_msgs::image_encodings::RGB8; out_msg.image = inImage; image_pub.publish(out_msg.toImageMsg()); } if(debug_pub.getNumSubscribers() > 0) { //show also the internal image resulting from the threshold operation cv_bridge::CvImage debug_msg; debug_msg.header.stamp = curr_stamp; debug_msg.encoding = sensor_msgs::image_encodings::MONO8; debug_msg.image = mDetector.getThresholdedImage(); debug_pub.publish(debug_msg.toImageMsg()); } } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } } } // wait for one camerainfo, then shut down that subscriber void cam_info_callback(const sensor_msgs::CameraInfo &msg) { camParam = aruco_ros::rosCameraInfo2ArucoCamParams(msg, useRectifiedImages); // handle cartesian offset between stereo pairs // see the sensor_msgs/CamaraInfo documentation for details rightToLeft.setIdentity(); rightToLeft.setOrigin( tf::Vector3( -msg.P[3]/msg.P[0], -msg.P[7]/msg.P[5], 0.0)); cam_info_received = true; cam_info_sub.shutdown(); } void reconf_callback(aruco_ros::ArucoThresholdConfig &config, uint32_t level) { mDetector.setThresholdParams(config.param1,config.param2); if (config.normalizeImage) { ROS_WARN("normalizeImageIllumination is unimplemented!"); } } }; int main(int argc,char **argv) { ros::init(argc, argv, "aruco_simple"); ros::NodeHandle nh("~"); ArucoSimple node(nh); ros::ServiceServer action_effect_check_server = nh.advertiseService("action_effect_check", &ArucoSimple::GoToActionEffectCheck, &node); ros::spin(); return 0; }
[ "1024809808@qq.com" ]
1024809808@qq.com
b92ead3ae342bf7d6b8d105848f4a58ece9ab84d
5019700f6d59224177ff3524ad622d34604f542b
/unity_rtm_sdk/Projects/Windows/agoraRTMCWrapper/agoraRTMCWrapper/i_rtm_call_event_handler.cpp
7811e798a1e24b51a7a1e4ccc2d970e577ae4fb4
[ "MIT" ]
permissive
dujiepeng/Agora-Unity-RTM-SDK
f7632e49d636dbbfd3fd51282576c4e617168a48
0454dece7e3577fb3ba0675ff942e86b49a05e9e
refs/heads/master
2023-04-07T04:40:16.896677
2021-04-13T07:51:54
2021-04-13T07:51:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,066
cpp
// // i_rtm_call_event_handler.cpp // agoraRTMCWrapper // // Created by 张涛 on 2020/10/22. // Copyright © 2020 张涛. All rights reserved. // #include "i_rtm_call_event_handler.h" extern "C" { #define RTM_CALL_EVENT_HANDLER_PTR static_cast<agora::unity::RtmCallEventHandler *>(eventHandlerPtr); } AGORA_API void* i_rtm_call_event_handler_createEventHandler(int _index, agora::unity::FUNC_onLocalInvitationReceivedByPeer _onLocalInvitationReceivedByPeer, agora::unity::FUNC_onLocalInvitationCanceled _onLocalInvitationCanceled, agora::unity::FUNC_onLocalInvitationFailure _onLocalInvitationFailure, agora::unity::FUNC_onLocalInvitationAccepted _onLocalInvitationAccepted, agora::unity::FUNC_onLocalInvitationRefused _onLocalInvitationRefused, agora::unity::FUNC_onRemoteInvitationRefused _onRemoteInvitationRefused, agora::unity::FUNC_onRemoteInvitationAccepted _onRemoteInvitationAccepted, agora::unity::FUNC_onRemoteInvitationReceived _onRemoteInvitationReceived, agora::unity::FUNC_onRemoteInvitationFailure _onRemoteInvitationFailure, agora::unity::FUNC_onRemoteInvitationCanceled _onRemoteInvitationCanceled) { return new agora::unity::RtmCallEventHandler(_index, _onLocalInvitationReceivedByPeer, _onLocalInvitationCanceled, _onLocalInvitationFailure, _onLocalInvitationAccepted, _onLocalInvitationRefused, _onRemoteInvitationRefused, _onRemoteInvitationAccepted, _onRemoteInvitationReceived, _onRemoteInvitationFailure, _onRemoteInvitationCanceled); } AGORA_API void i_rtm_call_event_releaseEventHandler(void *eventHandlerPtr) { delete RTM_CALL_EVENT_HANDLER_PTR; eventHandlerPtr = nullptr; }
[ "zhangtao@agora.io" ]
zhangtao@agora.io
10f832f4a4d8f6ea682d91bafd1506cf437c75f7
7eb7c263634a40b7397727854346f703e2be5a63
/core/simulation/env/webots/krock/krock2_ros/controllers/Tem_controller/Utils/misc_math.hpp
45944de6004fa60a083be7910126af3e860c7413
[]
no_license
Iqra350/krock2_traversability
7b745d1664d9d14facc0d3fbff324bbaac2c391e
7dd5e03d768fd3218838417ac0f195b25a1b8efa
refs/heads/master
2022-07-17T04:59:35.529123
2019-09-02T14:07:40
2019-09-02T14:07:40
205,813,838
0
0
null
2022-06-21T22:42:16
2019-09-02T08:42:19
Jupyter Notebook
UTF-8
C++
false
false
1,982
hpp
/* PLEUROBOT UTILITIES */ #ifndef MISC_MATH_CPP #define MISC_MATH_CPP #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <net/if.h> #include <ifaddrs.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <arpa/inet.h> #include <stdlib.h> #include "eigen3/Eigen/Dense" #include "eigen3/Eigen/Geometry" #include <sys/time.h> #include <stdio.h> #include <sstream> #include <fstream> #include <string> #include <iostream> using namespace Eigen; using namespace std; // filtering double pt1(double u, double y, double T, double Ts); MatrixXd pt1_vec(MatrixXd u, MatrixXd y, double T, double Ts); // basic rotation matrices Matrix3d rotx(double ang); Matrix3d roty(double ang); Matrix3d rotz(double ang); /* Hermite spline */ MatrixXd hermiteSpline(Vector2d p0, Vector2d p1, Vector2d m0, Vector2d m1, MatrixXd t); /* Save acos */ double SafeAcos (double x); Vector3d projectOntoEllipsoid(Vector3d p, Vector3d e, Vector3d c); /* PID controller */ class PID { public: PID(double Kpin, double Kiin, double Kdin, double dt); PID(){}; PID& operator=( const PID& other ); double calc(double e); private: double Kp, Ki, Kd, Ts; // Gains double a, b, c; double ek1, ek2, uk1; // past values }; /* PIDvec controller */ class PIDvec { public: PIDvec(){}; void init(MatrixXd Kpin, MatrixXd Kiin, MatrixXd Kdin, MatrixXd Tdin, double lim, double dt); void init(double Kpin, double Kiin, double Kdin, double Tdin, double lim, double dt); PIDvec& operator=( const PIDvec& other ); MatrixXd calc(MatrixXd e); double calc(double e); void flush(); private: MatrixXd Kp, Ki, Kd, Td; // Gains double Ts; MatrixXd a, b, c, d, f, g; MatrixXd ek1, ek2, uk1, uk2; // past values double limit; }; class movAVG { public: movAVG(int dim, int span); MatrixXd calc(MatrixXd in); private: Matrix<double, Dynamic, Dynamic> old; int N, n; }; #endif
[ "noorsyen@gmail.com" ]
noorsyen@gmail.com
d637f68a416fe093d5cac543af98e4b369f6b578
04b1803adb6653ecb7cb827c4f4aa616afacf629
/services/video_capture/test/device_factory_provider_test.h
791fa804ab30480a871967200cbcea13c1e92c65
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
2,418
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_VIDEO_CAPTURE_VIDEO_CAPTURE_TEST_DEVICE_FACTORY_PROVIDER_TEST_H_ #define SERVICES_VIDEO_CAPTURE_VIDEO_CAPTURE_TEST_DEVICE_FACTORY_PROVIDER_TEST_H_ #include "base/macros.h" #include "base/test/mock_callback.h" #include "base/test/scoped_task_environment.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service.h" #include "services/service_manager/public/cpp/service_binding.h" #include "services/service_manager/public/cpp/test/test_service_manager.h" #include "services/video_capture/public/mojom/device_factory.mojom.h" #include "services/video_capture/public/mojom/device_factory_provider.mojom.h" #include "services/video_capture/public/mojom/virtual_device.mojom.h" #include "testing/gtest/include/gtest/gtest.h" namespace video_capture { class MockProducer; // Basic test fixture that sets up a connection to the fake device factory. class DeviceFactoryProviderTest : public testing::Test { public: DeviceFactoryProviderTest(); ~DeviceFactoryProviderTest() override; void SetUp() override; protected: struct SharedMemoryVirtualDeviceContext { SharedMemoryVirtualDeviceContext(mojom::ProducerRequest producer_request); ~SharedMemoryVirtualDeviceContext(); std::unique_ptr<MockProducer> mock_producer; mojom::SharedMemoryVirtualDevicePtr device; }; std::unique_ptr<SharedMemoryVirtualDeviceContext> AddSharedMemoryVirtualDevice(const std::string& device_id); mojom::TextureVirtualDevicePtr AddTextureVirtualDevice( const std::string& device_id); service_manager::Connector* connector() { return test_service_binding_.GetConnector(); } base::test::ScopedTaskEnvironment task_environment_; service_manager::TestServiceManager test_service_manager_; service_manager::Service test_service_; service_manager::ServiceBinding test_service_binding_; mojom::DeviceFactoryProviderPtr factory_provider_; mojom::DeviceFactoryPtr factory_; base::MockCallback<mojom::DeviceFactory::GetDeviceInfosCallback> device_info_receiver_; DISALLOW_COPY_AND_ASSIGN(DeviceFactoryProviderTest); }; } // namespace video_capture #endif // SERVICES_VIDEO_CAPTURE_VIDEO_CAPTURE_TEST_DEVICE_FACTORY_PROVIDER_TEST_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
121ecd020755407a162705a5b5695cacf5815461
f23b9a7c4f41a31a68bf2920fbf995d58aa5c780
/0_Project/firmware/handsfree_wheel_robot_ucosIII/src/main.cpp
ccd82f108d3832107e0fc6ad213df9c993075a96
[ "BSD-3-Clause" ]
permissive
trygas/OpenRE_remote
a296851b3a313e59f0afe706d0fde924b8d0f81d
19d19dacec5071f4cdf1c3b8789bd374c3600bb1
refs/heads/master
2021-05-11T04:04:16.145236
2018-01-19T07:42:01
2018-01-19T07:42:01
117,931,951
1
0
null
null
null
null
UTF-8
C++
false
false
9,443
cpp
/*********************************************************************************************************************** * Copyright (c) Hands Free Team. All rights reserved. * FileName: main.c * Contact: QQ Exchange Group -- 521037187 * Version: V2.0 * * LICENSING TERMS: * The Hands Free is licensed generally under a permissive 3-clause BSD license. * Contributions are requiredto be made under the same license. * * History: * <author> <time> <version> <desc> * mawenke 2015.10.1 V1.0 creat this file * * Description: ***********************************************************************************************************************/ #include "board.h" #include "os_include.h" #include "robot_control.h" #include "robot_model.h" #define START_TASK_PRIO 3 #define START_TASK_STK_SIZE 512 OS_TCB START_TASK_TCB; CPU_STK START_TASK_STK[START_TASK_STK_SIZE]; void start_task(void *p_arg); #define BSP_TASK_PRIO 4 #define BSP_TASK_STK_SIZE 256 OS_TCB BSP_TASK_TCB; CPU_STK BSP_TASK_STK[BSP_TASK_STK_SIZE]; void bsp_task(void *p_arg); #define MOTOR_TASK_PRIO 5 #define MOTOR_TASK_STK_SIZE 256 OS_TCB MOTOR_TASK_TCB; CPU_STK MOTOR_TASK_STK[MOTOR_TASK_STK_SIZE]; void motor_task(void *p_arg); #define ROBOT_WHEEL_TASK_PRIO 6 #define ROBOT_WHEEL_TASK_STK_SIZE 512 OS_TCB ROBOT_WHEEL_TASK_TCB; __attribute((aligned (8))) CPU_STK ROBOT_WHEEL_TASK_STK[ROBOT_WHEEL_TASK_STK_SIZE]; void robot_wheel_task(void *p_arg); #define IMU_TASK_PRIO 7 #define IMU_TASK_STK_SIZE 256 OS_TCB IMU_TASK_TCB; CPU_STK IMU_TASK_STK[IMU_TASK_STK_SIZE]; void imu_task(void *p_arg); #define HF_LINK_TASK_PRIO 8 #define HF_LINK_TASK_STK_SIZE 256 OS_TCB HF_LINK_TASK_TCB; CPU_STK HF_LINK_TASK_STK[HF_LINK_TASK_STK_SIZE]; void hf_link_task(void *p_arg); int main(void) { OS_ERR err; CPU_SR_ALLOC(); Board *board = Board::getInstance(); board->boardBasicInit(); RobotModel robot_model; RobotAbstract robot; robot.para = robot_model; RobotControl *robot_control_p = RobotControl::getInstance(); robot_control_p->init(&robot); HFLink hf_link_pc_node(&robot , 0x11 , 0x01 , (unsigned char)USART_PC); robot_control_p->setHFLinkNodePointer(&hf_link_pc_node); SBUS sbus(USART_SBUS); robot_control_p->setSBUSRemotePointer(&sbus); printf("app start \r\n"); OSInit(&err); OS_CRITICAL_ENTER();//进入临界区 //Create start task OSTaskCreate((OS_TCB * )&START_TASK_TCB, //任务控制块 (CPU_CHAR * )"start task", //任务名字 (OS_TASK_PTR )start_task, //任务函数 (void * )0, //传递给任务函数的参数 (OS_PRIO )START_TASK_PRIO, //任务优先级 (CPU_STK * )&START_TASK_STK[0], //任务堆栈基地址 (CPU_STK_SIZE)START_TASK_STK_SIZE/10, //任务堆栈深度限位 (CPU_STK_SIZE)START_TASK_STK_SIZE, //任务堆栈大小 (OS_MSG_QTY )0, //任务内部消息队列能够接收的最大消息数目,为0时禁止接收消息 (OS_TICK )0, //当使能时间片轮转时的时间片长度,为0时为默认长度, (void * )0, //用户补充的存储区 (OS_OPT )OS_OPT_TASK_STK_CHK|OS_OPT_TASK_STK_CLR, //任务选项 (OS_ERR * )&err); //存放该函数错误时的返回值 OS_CRITICAL_EXIT(); //退出临界区 OSStart(&err); //开启UCOSIII while(1); } void start_task(void *p_arg) { OS_ERR err; CPU_SR_ALLOC(); p_arg = p_arg; CPU_Init(); #if OS_CFG_STAT_TASK_EN > 0u OSStatTaskCPUUsageInit(&err); //统计任务 #endif #ifdef CPU_CFG_INT_DIS_MEAS_EN //如果使能了测量中断关闭时间 CPU_IntDisMeasMaxCurReset(); #endif #if OS_CFG_SCHED_ROUND_ROBIN_EN //当使用时间片轮转的时候 //使能时间片轮转调度功能,时间片长度为1个系统时钟节拍 OSSchedRoundRobinCfg(DEF_ENABLED,1,&err); #endif OS_CRITICAL_ENTER(); OSTaskCreate((OS_TCB * )&BSP_TASK_TCB, (CPU_CHAR * )"bsp task", (OS_TASK_PTR )bsp_task, (void * )0, (OS_PRIO )BSP_TASK_PRIO, (CPU_STK * )&BSP_TASK_STK[0], (CPU_STK_SIZE)BSP_TASK_STK_SIZE/10, (CPU_STK_SIZE)BSP_TASK_STK_SIZE, (OS_MSG_QTY )0, (OS_TICK )0, (void * )0, (OS_OPT )OS_OPT_TASK_STK_CHK|OS_OPT_TASK_STK_CLR, (OS_ERR * )&err); OSTaskCreate((OS_TCB * )&MOTOR_TASK_TCB, (CPU_CHAR * )"motor task", (OS_TASK_PTR )motor_task, (void * )0, (OS_PRIO )MOTOR_TASK_PRIO, (CPU_STK * )&MOTOR_TASK_STK[0], (CPU_STK_SIZE)MOTOR_TASK_STK_SIZE/10, (CPU_STK_SIZE)MOTOR_TASK_STK_SIZE, (OS_MSG_QTY )0, (OS_TICK )0, (void * )0, (OS_OPT )OS_OPT_TASK_STK_CHK|OS_OPT_TASK_STK_CLR, (OS_ERR * )&err); OSTaskCreate((OS_TCB * )&ROBOT_WHEEL_TASK_TCB, (CPU_CHAR * )"robot_wheel task", (OS_TASK_PTR )robot_wheel_task, (void * )0, (OS_PRIO )ROBOT_WHEEL_TASK_PRIO, (CPU_STK * )&ROBOT_WHEEL_TASK_STK[0], (CPU_STK_SIZE)ROBOT_WHEEL_TASK_STK_SIZE/10, (CPU_STK_SIZE)ROBOT_WHEEL_TASK_STK_SIZE, (OS_MSG_QTY )0, (OS_TICK )0, (void * )0, (OS_OPT )OS_OPT_TASK_STK_CHK|OS_OPT_TASK_STK_CLR, (OS_ERR * )&err); OSTaskCreate((OS_TCB * )&IMU_TASK_TCB, (CPU_CHAR * )"imu task", (OS_TASK_PTR )imu_task, (void * )0, (OS_PRIO )IMU_TASK_PRIO, (CPU_STK * )&IMU_TASK_STK[0], (CPU_STK_SIZE)IMU_TASK_STK_SIZE/10, (CPU_STK_SIZE)IMU_TASK_STK_SIZE, (OS_MSG_QTY )0, (OS_TICK )0, (void * )0, (OS_OPT )OS_OPT_TASK_STK_CHK|OS_OPT_TASK_STK_CLR, (OS_ERR * )&err); OSTaskCreate((OS_TCB * )&HF_LINK_TASK_TCB, (CPU_CHAR * )"hf_link task", (OS_TASK_PTR )hf_link_task, (void * )0, (OS_PRIO )HF_LINK_TASK_PRIO, (CPU_STK * )&HF_LINK_TASK_STK[0], (CPU_STK_SIZE)HF_LINK_TASK_STK_SIZE/10, (CPU_STK_SIZE)HF_LINK_TASK_STK_SIZE, (OS_MSG_QTY )0, (OS_TICK )0, (void * )0, (OS_OPT )OS_OPT_TASK_STK_CHK|OS_OPT_TASK_STK_CLR, (OS_ERR * )&err); OS_TaskSuspend((OS_TCB*)&START_TASK_TCB,&err); //挂起开始任务 OS_CRITICAL_EXIT(); } void bsp_task(void *p_arg) { OS_ERR err; p_arg = p_arg; float bsp_task_i=0; Board *board = Board::getInstance(); while(1) { bsp_task_i++; board->boardBasicCall(); // need time stm32f1 35us if(bsp_task_i >= 5) { bsp_task_i=0; board->setLedState(0,2); } OSTimeDlyHMSM(0,0,0,10,OS_OPT_TIME_HMSM_STRICT,&err); //delay 10ms 100hz } } void motor_task(void *p_arg) { OS_ERR err; p_arg = p_arg; RobotControl *robot_control_p = RobotControl::getInstance(); while(1) { robot_control_p->motor_top.motorTopCall(); //motor speed control OSTimeDlyHMSM(0,0,0,20,OS_OPT_TIME_HMSM_STRICT,&err); //delay 20ms 50hz } } void robot_wheel_task(void *p_arg) { OS_ERR err; //CPU_SR_ALLOC(); p_arg = p_arg; RobotControl *robot_control_p = RobotControl::getInstance(); while(1) { robot_control_p->call(); // OS_CRITICAL_ENTER(); // printf("battery_voltage = %.4f cpu_usage = %.4f cpu_temperature = %.4f\r\n", // board.battery_voltage , board.cpu_usage , board.cpu_temperature // ); // OS_CRITICAL_EXIT(); OSTimeDlyHMSM(0,0,0,50,OS_OPT_TIME_HMSM_STRICT,&err); //delay 50ms 20hz } } void imu_task(void *p_arg) { OS_ERR err; //CPU_SR_ALLOC(); p_arg = p_arg; while(1) { //imu.topCall(); OSTimeDly(1,OS_OPT_TIME_PERIODIC,&err); //OSTimeDlyHMSM(0,0,0,1,OS_OPT_TIME_HMSM_STRICT,&err); //delay 1ms 1000hz } } void hf_link_task(void *p_arg) { OS_ERR err; p_arg = p_arg; RobotControl *robot_control_p = RobotControl::getInstance(); Board *board = Board::getInstance(); while(1) { if(board->usartDeviceReadData(robot_control_p->hf_link_node_device)->emptyCheck() == 0){ robot_control_p->hf_link_node->byteAnalysisCall( board->usartDeviceReadData( robot_control_p->hf_link_node_device)->getData() ); } else { OSTimeDlyHMSM(0,0,0,5,OS_OPT_TIME_HMSM_STRICT,&err); //delay 5ms 200hz } } }
[ "315261982@qq.com" ]
315261982@qq.com
6bb725cf1e8c27006ea72ad1759b848d7822046a
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/core/scoring/dssp/StrandPairing.hh
74841e156fcce4df3b4a25d0d80309a618b819df
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
6,513
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. // @brief // @author olange: ported from original bblum-rosetta++ version $ #ifndef INCLUDED_core_scoring_dssp_StrandPairing_HH #define INCLUDED_core_scoring_dssp_StrandPairing_HH // Unit Headers #include <core/scoring/dssp/StrandPairing.fwd.hh> #include <core/scoring/dssp/PairingsList.fwd.hh> // Project Headers #include <core/types.hh> #include <core/pose/Pose.fwd.hh> // Utility headers #include <utility/pointer/ReferenceCount.hh> #include <utility/pointer/owning_ptr.hh> // ObjexxFCL Headers #include <ObjexxFCL/FArray2.fwd.hh> // C++ headers #include <string> #include <utility/exit.hh> #include <utility/vector1.hh> namespace core { namespace scoring { namespace dssp { ////////////////////////////////////////////////////////////////// // StrandPairing // This class encapsulates a pairing between two beta strands. // It is designed to be initialized with a single residue-residue // pairing and then extended, residue by residue, along the // strands. It MUST be extended sequentially along the length // of the strands. It can accomodate beta bulges of length at // most 1 on one strand and 4 on the other (inspired by dssp // guidelines). ////////////////////////////////////////////////////////////////// class StrandPairing { typedef utility::vector1< core::Size > SizeList; public: StrandPairing(); StrandPairing(core::Size res1, core::Size res2, bool antiparallel, core::Size pleating); ~StrandPairing(); core::Size operator==(const StrandPairing &rhs) const; // core::Size operator!=(const StrandPairing &rhs) const; core::Size operator<(const StrandPairing &rhs) const; core::Size size() const { return end1_ - begin1_ + 1; } core::Size begin1() const { return begin1_; } core::Size end1() const { return end1_; } bool range_check() const; core::Size contact_order() const; core::Size get_register() const; void get_all_register_and_bulges( SizeList& regs, SizeList& bulges ) const; std::size_t hash_value() const; bool contains(core::Size res) const; bool is_bulge(core::Size res) const; bool is_ladder() const; core::Size get_pair(core::Size res)const ; bool check_pleat() const; core::Size get_pleating(core::Size res)const ; bool extend(core::Size res, core::Size res2, bool antiparallel, core::Size pleating); void extend_to(core::Size res); bool antiparallel() const; bool has_pairing( core::scoring::dssp::Pairing const& ) const; bool has_common_pairing( StrandPairing const& other ) const; bool paired( core::Size res1, core::Size res2, bool anti ) const; void get_beta_pairs( core::scoring::dssp::PairingList& ) const; bool merge( StrandPairing const& other, bool domerge = false); bool mergeable( StrandPairing const& other ) const; void show_internals( std::ostream& out ) const; bool valid_ends() const; friend std::ostream & operator<<(std::ostream & out, StrandPairing const & sp); friend std::istream & operator>>( std::istream &in, StrandPairing &sp ); static core::Size BIG_BULGE_LIMIT; static core::Size SMALL_BULGE_LIMIT; private: //@brief first pairing of antipar. strand is begin1_ --> end2_ // last pairing of antipar. strand is end1_ --> begin2_ // hence strand1 goes from begin1-->end1 and strand2 goes from begin2-->end2 core::Size begin1_, end1_, begin2_, end2_; // vector listing which residues are paired to the residues // in strand 1. 0 indicates beta bulge (unpaired). // one entry for pos begin1_...end1_ std::vector<core::Size> pairing1; std::vector<core::Size> pleating1; // similar to pairing1 but for strand 2. std::vector<core::Size> pairing2; //bool pleat_weird; bool antipar_; }; std::ostream & operator<<(std::ostream & out, StrandPairing const& sp); ////////////////////////////////////////////////////////////////// // StrandPairingSet // This class maintains a set of strand pairings and provides // access functions to determine whether a particular residue // participates in any of them, and in what capacity. // ////////////////////////////////////////////////////////////////// class StrandPairingSet : public utility::pointer::ReferenceCount { typedef utility::vector1< StrandPairing > StrandPairings; typedef StrandPairings::iterator iterator; public: typedef StrandPairings::const_iterator const_iterator; StrandPairingSet() {}; StrandPairingSet( ObjexxFCL::FArray2_float const& hbonds, float threshold, core::pose::Pose const& ); StrandPairingSet( core::pose::Pose const&, core::Real threshold = -0.5 ); StrandPairingSet( core::scoring::dssp::PairingList const& ); virtual ~StrandPairingSet(); //void add_decoy( core::Size dec ); bool check_pleat() const; char dssp_state( core::Size res ) const; char featurizer_state( core::Size res ) const; bool paired( core::Size res1, core::Size res2, bool antiparallel ) const; bool has_pairing( core::scoring::dssp::Pairing const& ) const; bool has_pairing( StrandPairing const& ) const; void get_beta_pairs( core::scoring::dssp::PairingList& ) const; bool merge( const StrandPairingSet &other, bool domerge = false ); friend std::ostream & operator<<(std::ostream & out, const StrandPairingSet &sp); friend std::istream & operator>>(std::istream & is, StrandPairingSet &sp); const_iterator begin() const { return pairings_.begin(); } const_iterator end() const { return pairings_.end(); } Size size() const { return pairings_.size(); } StrandPairing const& strand_pairing( Size i ) const { runtime_assert( i <= pairings_.size() ); return pairings_[ i ]; } void push_back( StrandPairing const& sp ) { pairings_.push_back( sp ); } private: void add_pairing( core::Size res1, core::Size res2, bool antiparallel, core::Size pleating ); void add_pairing( core::scoring::dssp::Pairing const& pairing ); void selfmerge(); void compute( ObjexxFCL::FArray2_float const& hbonds, float threshold, core::pose::Pose const& ); StrandPairings pairings_; }; std::ostream & operator<<(std::ostream & out, const StrandPairingSet &sp); } } } #endif
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
fecd72d233c4ca7f7bd5ed7fc9fc62d6ec600c55
7a9dec211cacc3def4c1e47a9c2050fe88c3d0ed
/Obstacle Detction/main.cpp
c69bd493efeeab992004c650b951bec3f9335842
[]
no_license
songsong1996/Capstone-Project-Obstacle-Avoidance-Strategy
948c9709753adbc2ee944f49029d82c48d31b4e1
74dd22a8505d6e9a732d74be2c9b6a78eef1d71f
refs/heads/master
2021-04-02T17:47:38.694379
2020-03-18T19:42:56
2020-03-18T19:42:56
248,300,715
0
0
null
null
null
null
UTF-8
C++
false
false
8,095
cpp
// // Created by songsong on 19-4-16. // #include<librealsense2/rs.hpp> #include<librealsense2/rsutil.h> #include"align_depth_color.h" // OpenCV #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <unistd.h> #include "contours_processor.h" #include<iostream> using namespace cv; using namespace std; int main(int argc, char **argv) { const char* depth_win="depth_Image"; namedWindow(depth_win,WINDOW_AUTOSIZE); const char* color_win="color_Image"; namedWindow(color_win,WINDOW_AUTOSIZE); const char* top_win="top_View"; namedWindow(top_win,WINDOW_AUTOSIZE); //深度图像颜色map rs2::colorizer c; // Helper to colorize depth images //创建数据管道 rs2::pipeline pipe; rs2::config pipe_config; pipe_config.enable_stream(RS2_STREAM_DEPTH,640,480,RS2_FORMAT_Z16,30); pipe_config.enable_stream(RS2_STREAM_COLOR,640,480,RS2_FORMAT_BGR8,30); //start()函数返回数据管道的profile rs2::pipeline_profile profile = pipe.start(pipe_config); //定义一个变量去转换深度到距离 float depth_clipping_distance = 1.f; //声明数据流 auto depth_stream=profile.get_stream(RS2_STREAM_DEPTH).as<rs2::video_stream_profile>(); auto color_stream=profile.get_stream(RS2_STREAM_COLOR).as<rs2::video_stream_profile>(); //获取内参 auto intrinDepth=depth_stream.get_intrinsics(); auto intrinColor=color_stream.get_intrinsics(); //直接获取从深度摄像头坐标系到彩色摄像头坐标系的欧式变换矩阵 auto extrinDepth2Color=depth_stream.get_extrinsics_to(color_stream); // int ii=0; // while(ii==0) int ii=0; Mat previous_depth,previous_color,present_depth,present_color,previous,present; match new_folder=match(); if(getWindowProperty(depth_win,WND_PROP_VISIBLE )&&getWindowProperty(color_win,WND_PROP_VISIBLE )) { //ii++; //堵塞程序直到新的一帧捕获 rs2::frameset frameset = pipe.wait_for_frames(); //取深度图和彩色图 rs2::frame color_frame = frameset.get_color_frame();//processed.first(align_to); rs2::frame depth_frame = frameset.get_depth_frame(); rs2::frame depth_frame_4_show = frameset.get_depth_frame().apply_filter(c); //获取宽高 const int depth_w=depth_frame.as<rs2::video_frame>().get_width(); const int depth_h=depth_frame.as<rs2::video_frame>().get_height(); const int color_w=color_frame.as<rs2::video_frame>().get_width(); const int color_h=color_frame.as<rs2::video_frame>().get_height(); Mat depth_image(Size(depth_w,depth_h), CV_16U,(void*)depth_frame.get_data(),Mat::AUTO_STEP); Mat depth_image_4_show(Size(depth_w,depth_h), CV_8UC3,(void*)depth_frame_4_show.get_data(),Mat::AUTO_STEP); Mat color_image(Size(color_w,color_h), CV_8UC3,(void*)color_frame.get_data(),Mat::AUTO_STEP); // Mat depth_image=imread("/home/songsong/Documents/private/Graduation-design/codes/Intelrealsense/1/data/t1_Depth.png",IMREAD_UNCHANGED ); // Mat color_image=imread("/home/songsong/Documents/private/Graduation-design/codes/Intelrealsense/1/data/t1_Color.png",IMREAD_COLOR ); // depth_image.convertTo(depth_image,CV_16U ); // color_image.convertTo(color_image,CV_8UC3); // // cvtColor(depth_image,depth_image,CV_16U); // cvtColor(color_image,color_image,CV_8UC3); //实现深度图对齐到彩色图 Mat result=align_Depth2Color(depth_image,color_image,profile); result=SmoothImage(result); Mat top_view= depth_top(result,600,result.cols,0,result.rows); // PointCloud::Ptr pointcloud= image2PointCloud( color_image, depth_image, camera_intrinsic ); Mat depth1_tp,depth2_tp; depth1_tp=stressDepth(depth_image); depth2_tp=stressDepth(result); //显示 imshow(depth_win,depth1_tp); imshow(color_win,color_image); imshow("result",depth2_tp); imshow(top_win,top_view); waitKey(100); // sleep(1000); } while (getWindowProperty(depth_win,WND_PROP_VISIBLE )&&getWindowProperty(color_win,WND_PROP_VISIBLE )) // Application still alive? { //ii++; //堵塞程序直到新的一帧捕获 rs2::frameset frameset = pipe.wait_for_frames(); //取深度图和彩色图 rs2::frame color_frame = frameset.get_color_frame();//processed.first(align_to); rs2::frame depth_frame = frameset.get_depth_frame(); rs2::frame depth_frame_4_show = frameset.get_depth_frame().apply_filter(c); //获取宽高 const int depth_w=depth_frame.as<rs2::video_frame>().get_width(); const int depth_h=depth_frame.as<rs2::video_frame>().get_height(); const int color_w=color_frame.as<rs2::video_frame>().get_width(); const int color_h=color_frame.as<rs2::video_frame>().get_height(); Mat depth_image(Size(depth_w,depth_h), CV_16U,(void*)depth_frame.get_data(),Mat::AUTO_STEP); Mat depth_image_4_show(Size(depth_w,depth_h), CV_8UC3,(void*)depth_frame_4_show.get_data(),Mat::AUTO_STEP); Mat color_image(Size(color_w,color_h), CV_8UC3,(void*)color_frame.get_data(),Mat::AUTO_STEP); // Mat depth_image=imread("/home/songsong/Documents/private/Graduation-design/codes/Intelrealsense/1/data/t1_Depth.png",IMREAD_UNCHANGED ); // Mat color_image=imread("/home/songsong/Documents/private/Graduation-design/codes/Intelrealsense/1/data/t1_Color.png",IMREAD_COLOR ); // depth_image.convertTo(depth_image,CV_16U ); // color_image.convertTo(color_image,CV_8UC3); // // cvtColor(depth_image,depth_image,CV_16U); // cvtColor(color_image,color_image,CV_8UC3); //实现深度图对齐到彩色图 Mat result=align_Depth2Color(depth_image,color_image,profile); result=SmoothImage(result); Mat top_view= depth_top(result,600,result.cols,0,result.rows); // PointCloud::Ptr pointcloud= image2PointCloud( color_image, depth_image, camera_intrinsic ); Mat depth1_tp,depth2_tp; depth1_tp=stressDepth(depth_image); depth2_tp=stressDepth(result); //显示 // imshow(depth_win,depth1_tp); // imshow(color_win,color_image); // imshow("result",depth2_tp); // imshow(top_win,top_view); // waitKey(100); // sleep(1000); top_view.copyTo(present); color_image.copyTo(present_color); depth2_tp.copyTo(present_depth); Mat match_result; if(ii>30) { match_result = new_folder.match_contours2(previous, previous_color, previous_depth, present, present_color, present_depth); bool tpp=new_folder.if_stop; std::cout<<"if_stop "<<tpp<<endl; if(ii%2==0) { imwrite("../data/color_draw/"+to_string(ii/2)+".png",new_folder.color_draw); imwrite("../data/depth_draw/"+to_string(ii/2)+".png",new_folder.depth_draw); imwrite("../data/match_result/"+to_string(ii/2)+".png",match_result); } imshow(depth_win,depth1_tp); imshow(color_win,new_folder.color_draw); imshow("result",new_folder.depth_draw); imshow(top_win,top_view); imshow("match", match_result); waitKey(100); } top_view.copyTo(previous); color_image.copyTo(previous_color); depth2_tp.copyTo(previous_depth); ii++; // if(ii%2==0) // { // imwrite("../data/color/"+to_string(ii/5)+".png",color_image); // imwrite("../data/top_view/"+to_string(ii/5)+".png",top_view); // imwrite("../data/depth/"+to_string(ii/5)+".png",depth2_tp); // } } return 0; }
[ "songhuiyu_2008@126.com" ]
songhuiyu_2008@126.com
92aca7408988ba4dc3870f3078d929b978ebcf35
550b2d7001c741e3e16be49094f3d44433bb8337
/cef/cefclient/browser/root_window_manager.h
e6260b9bc56885394e729c0d9f29a6d53843cc35
[]
no_license
ShelleyLake/QCefKits
1d8d96183baad8296c3e601a5b6ee50954b1dbe9
d507b5896ffc1843d2a6a88689b9ad72f77f99a0
refs/heads/main
2023-06-05T06:29:41.661993
2021-06-29T13:31:12
2021-06-29T13:31:12
381,505,123
1
0
null
2021-06-29T21:49:39
2021-06-29T21:49:39
null
UTF-8
C++
false
false
5,457
h
// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #ifndef CEF_TESTS_CEFCLIENT_BROWSER_ROOT_WINDOW_MANAGER_H_ #define CEF_TESTS_CEFCLIENT_BROWSER_ROOT_WINDOW_MANAGER_H_ #pragma once #include <set> #include "include/base/cef_scoped_ptr.h" #include "include/cef_command_line.h" #include "include/cef_request_context_handler.h" #include "browser/image_cache.h" #include "browser/root_window.h" #include "browser/temp_window.h" namespace client { // Used to create/manage RootWindow instances. The methods of this class can be // called from any browser process thread unless otherwise indicated. class RootWindowManager : public RootWindow::Delegate { public: // If |terminate_when_all_windows_closed| is true quit the main message loop // after all windows have closed. explicit RootWindowManager(bool terminate_when_all_windows_closed); // Create a new top-level native window. This method can be called from // anywhere. scoped_refptr<RootWindow> CreateRootWindow(const RootWindowConfig& config); // Create a new native popup window. // If |with_controls| is true the window will show controls. // If |with_osr| is true the window will use off-screen rendering. // This method is called from ClientHandler::CreatePopupWindow() to // create a new popup or DevTools window. Must be called on the UI thread. scoped_refptr<RootWindow> CreateRootWindowAsPopup( bool with_controls, bool with_osr, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, CefRefPtr<CefClient>& client, CefBrowserSettings& settings); // Create a new top-level native window to host |extension|. // If |with_controls| is true the window will show controls. // If |with_osr| is true the window will use off-screen rendering. // This method can be called from anywhere. scoped_refptr<RootWindow> CreateRootWindowAsExtension( CefRefPtr<CefExtension> extension, const CefRect& source_bounds, CefRefPtr<CefWindow> parent_window, const base::Closure& close_callback, bool with_controls, bool with_osr); // Returns true if a window hosting |extension| currently exists. Must be // called on the main thread. bool HasRootWindowAsExtension(CefRefPtr<CefExtension> extension); // Returns the RootWindow associated with the specified browser ID. Must be // called on the main thread. scoped_refptr<RootWindow> GetWindowForBrowser(int browser_id) const; // Returns the currently active/foreground RootWindow. May return NULL. Must // be called on the main thread. scoped_refptr<RootWindow> GetActiveRootWindow() const; // Returns the currently active/foreground browser. May return NULL. Safe to // call from any thread. CefRefPtr<CefBrowser> GetActiveBrowser() const; // Close all existing windows. If |force| is true onunload handlers will not // be executed. void CloseAllWindows(bool force); // Manage the set of loaded extensions. RootWindows will be notified via the // OnExtensionsChanged method. void AddExtension(CefRefPtr<CefExtension> extension); bool request_context_per_browser() const { return request_context_per_browser_; } private: // Allow deletion via scoped_ptr only. friend struct base::DefaultDeleter<RootWindowManager>; ~RootWindowManager(); void OnRootWindowCreated(scoped_refptr<RootWindow> root_window); void NotifyExtensionsChanged(); // RootWindow::Delegate methods. CefRefPtr<CefRequestContext> GetRequestContext( RootWindow* root_window) OVERRIDE; scoped_refptr<ImageCache> GetImageCache() OVERRIDE; void OnTest(RootWindow* root_window, int test_id) OVERRIDE; void OnExit(RootWindow* root_window) OVERRIDE; void OnRootWindowDestroyed(RootWindow* root_window) OVERRIDE; void OnRootWindowActivated(RootWindow* root_window) OVERRIDE; void OnBrowserCreated(RootWindow* root_window, CefRefPtr<CefBrowser> browser) OVERRIDE; void CreateExtensionWindow(CefRefPtr<CefExtension> extension, const CefRect& source_bounds, CefRefPtr<CefWindow> parent_window, const base::Closure& close_callback, bool with_osr) OVERRIDE; void CleanupOnUIThread(); const bool terminate_when_all_windows_closed_; bool request_context_per_browser_; bool request_context_shared_cache_; // Existing root windows. Only accessed on the main thread. typedef std::set<scoped_refptr<RootWindow>> RootWindowSet; RootWindowSet root_windows_; // The currently active/foreground RootWindow. Only accessed on the main // thread. scoped_refptr<RootWindow> active_root_window_; // The currently active/foreground browser. Access is protected by // |active_browser_lock_; mutable base::Lock active_browser_lock_; CefRefPtr<CefBrowser> active_browser_; // Singleton window used as the temporary parent for popup browsers. scoped_ptr<TempWindow> temp_window_; CefRefPtr<CefRequestContext> shared_request_context_; // Loaded extensions. Only accessed on the main thread. ExtensionSet extensions_; scoped_refptr<ImageCache> image_cache_; DISALLOW_COPY_AND_ASSIGN(RootWindowManager); }; } // namespace client #endif // CEF_TESTS_CEFCLIENT_BROWSER_ROOT_WINDOW_MANAGER_H_
[ "570740+panuins@users.noreply.github.com" ]
570740+panuins@users.noreply.github.com
5b3e71f0b10952adeb0930bedfc332cd749d0ad9
bf77530823a99308521e894d2382fd99f8d55183
/Heist/Source/Heist/Interaction/Interactable.cpp
4ee621986ba4ea9638c18c4c3b8a285f9dccc709
[]
no_license
WhileFalseStudios/HeistGame
ac8bd9123fc1efd74e6f729fb6307de045eecf78
ce8a6fc3d3b3e62f1ca7e1bd1336caed347f0cff
refs/heads/master
2021-08-22T12:01:52.182492
2017-11-28T03:53:08
2017-11-28T03:53:08
109,351,744
0
0
null
null
null
null
UTF-8
C++
false
false
138
cpp
#include "Interactable.h" UInteractable::UInteractable(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { }
[ "valax321@gmail.com" ]
valax321@gmail.com
386b316c71195860843aa1eef877f8a3a9170872
21ef0be38fad85edb2259e1f2804de97da49f69a
/src/masternode.cpp
15a93a687315e6ebd00e9ba1020c1ff519a7c8b5
[ "MIT" ]
permissive
mantisnetwork/MANTISCoin
2fa39fa170d09e534b10a9e4ed93b54a40e23110
9e477a70aa7c76f5650b713ef90f80c1b0221ac6
refs/heads/master
2023-03-13T00:20:00.370063
2021-03-03T09:25:05
2021-03-03T09:25:05
325,512,895
2
0
null
null
null
null
UTF-8
C++
false
false
27,665
cpp
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2020 The PIVX developers // Copyright (c) 2020 The MANTIS Coin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode.h" #include "addrman.h" #include "init.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "netbase.h" #include "sync.h" #include "util.h" #include "wallet/wallet.h" // keep track of the scanning errors I've seen std::map<uint256, int> mapSeenMasternodeScanningErrors; // cache block hashes as we calculate them std::map<int64_t, uint256> mapCacheBlockHashes; //Get the last hash that matches the modulus given. Processed in reverse order bool GetBlockHash(uint256& hash, int nBlockHeight) { const CBlockIndex* tipIndex = GetChainTip(); if (!tipIndex || !tipIndex->nHeight) return false; if (nBlockHeight == 0) nBlockHeight = tipIndex->nHeight; if (mapCacheBlockHashes.count(nBlockHeight)) { hash = mapCacheBlockHashes[nBlockHeight]; return true; } int nBlocksAgo = 0; if (nBlockHeight > 0) nBlocksAgo = (tipIndex->nHeight + 1) - nBlockHeight; if (nBlocksAgo < 0) return false; const CBlockIndex* BlockReading = tipIndex; int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nBlocksAgo) { hash = BlockReading->GetBlockHash(); mapCacheBlockHashes[nBlockHeight] = hash; return true; } n++; if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return false; } CMasternode::CMasternode() : CSignedMessage() { LOCK(cs); vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyMasternode = CPubKey(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); unitTest = false; allowFreeTx = true; protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; } CMasternode::CMasternode(const CMasternode& other) : CSignedMessage(other) { LOCK(cs); vin = other.vin; addr = other.addr; pubKeyCollateralAddress = other.pubKeyCollateralAddress; pubKeyMasternode = other.pubKeyMasternode; activeState = other.activeState; sigTime = other.sigTime; lastPing = other.lastPing; unitTest = other.unitTest; allowFreeTx = other.allowFreeTx; protocolVersion = other.protocolVersion; nLastDsq = other.nLastDsq; nScanningErrorCount = other.nScanningErrorCount; nLastScanningErrorBlockHeight = other.nLastScanningErrorBlockHeight; lastTimeChecked = 0; } uint256 CMasternode::GetSignatureHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << nMessVersion; ss << addr; ss << sigTime; ss << pubKeyCollateralAddress; ss << pubKeyMasternode; ss << protocolVersion; return ss.GetHash(); } std::string CMasternode::GetStrMessage() const { return (addr.ToString() + std::to_string(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyMasternode.GetID().ToString() + std::to_string(protocolVersion) ); } // // When a new masternode broadcast is sent, update our information // bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb) { if (mnb.sigTime > sigTime) { pubKeyMasternode = mnb.pubKeyMasternode; pubKeyCollateralAddress = mnb.pubKeyCollateralAddress; sigTime = mnb.sigTime; vchSig = mnb.vchSig; protocolVersion = mnb.protocolVersion; addr = mnb.addr; lastTimeChecked = 0; int nDoS = 0; if (mnb.lastPing.IsNull() || (!mnb.lastPing.IsNull() && mnb.lastPing.CheckAndUpdate(nDoS, false))) { lastPing = mnb.lastPing; mnodeman.mapSeenMasternodePing.insert(std::make_pair(lastPing.GetHash(), lastPing)); } return true; } return false; } // // Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // uint256 CMasternode::CalculateScore(int mod, int64_t nBlockHeight) { { LOCK(cs_main); if (!chainActive.Tip()) return UINT256_ZERO; } uint256 hash; uint256 aux = vin.prevout.hash + vin.prevout.n; if (!GetBlockHash(hash, nBlockHeight)) { LogPrint(BCLog::MASTERNODE,"CalculateScore ERROR - nHeight %d - Returned 0\n", nBlockHeight); return UINT256_ZERO; } CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << hash; uint256 hash2 = ss.GetHash(); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << hash; ss2 << aux; uint256 hash3 = ss2.GetHash(); uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); return r; } void CMasternode::Check(bool forceCheck) { if (ShutdownRequested()) return; // todo: add LOCK(cs) but be careful with the AcceptableInputs() below that requires cs_main. if (!forceCheck && (GetTime() - lastTimeChecked < MASTERNODE_CHECK_SECONDS)) return; lastTimeChecked = GetTime(); //once spent, stop doing the checks if (activeState == MASTERNODE_VIN_SPENT) return; if (!IsPingedWithin(MASTERNODE_REMOVAL_SECONDS)) { activeState = MASTERNODE_REMOVE; return; } if (!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) { activeState = MASTERNODE_EXPIRED; return; } if(lastPing.sigTime - sigTime < MASTERNODE_MIN_MNP_SECONDS){ activeState = MASTERNODE_PRE_ENABLED; return; } if (!unitTest) { CValidationState state; CMutableTransaction tx = CMutableTransaction(); CScript dummyScript; dummyScript << ToByteVector(pubKeyCollateralAddress) << OP_CHECKSIG; CTxOut vout = CTxOut((GetMNCollateral() - 0.01) * COIN, dummyScript); tx.vin.push_back(vin); tx.vout.push_back(vout); { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { activeState = MASTERNODE_VIN_SPENT; return; } } } activeState = MASTERNODE_ENABLED; // OK } int64_t CMasternode::SecondsSincePayment() { CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); int64_t sec = (GetAdjustedTime() - GetLastPaid()); int64_t month = 60 * 60 * 24 * 30; if (sec < month) return sec; //if it's less than 30 days, give seconds CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // return some deterministic value for unknown/unpaid but force it to be more than 30 days old return month + hash.GetCompact(false); } int64_t CMasternode::GetLastPaid() { const CBlockIndex* BlockReading = GetChainTip(); if (BlockReading == nullptr) return false; CScript mnpayee; mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // use a deterministic offset to break a tie -- 2.5 minutes int64_t nOffset = hash.GetCompact(false) % 150; int nMnCount = mnodeman.CountEnabled() * 1.25; int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nMnCount) { return 0; } n++; if (masternodePayments.mapMasternodeBlocks.count(BlockReading->nHeight)) { /* Search for this payee, with at least 2 votes. This will aid in consensus allowing the network to converge on the same payees quickly, then keep the same schedule. */ if (masternodePayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) { return BlockReading->nTime + nOffset; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return 0; } bool CMasternode::IsValidNetAddr() { // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().IsRegTestNet() || (IsReachable(addr) && addr.IsRoutable()); } bool CMasternode::IsInputAssociatedWithPubkey() const { CScript payee; payee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); CTransaction txVin; uint256 hash; if(GetTransaction(vin.prevout.hash, txVin, hash, true)) { for (CTxOut out : txVin.vout) { if (out.nValue == GetMNCollateral() * COIN && out.scriptPubKey == payee) return true; } } return false; } CMasternodeBroadcast::CMasternodeBroadcast() : CMasternode() { } CMasternodeBroadcast::CMasternodeBroadcast(CService newAddr, CTxIn newVin, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int protocolVersionIn) : CMasternode() { vin = newVin; addr = newAddr; pubKeyCollateralAddress = pubKeyCollateralAddressNew; pubKeyMasternode = pubKeyMasternodeNew; protocolVersion = protocolVersionIn; } CMasternodeBroadcast::CMasternodeBroadcast(const CMasternode& mn) : CMasternode(mn) { } bool CMasternodeBroadcast::Create(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline) { CTxIn txin; CPubKey pubKeyCollateralAddressNew; CKey keyCollateralAddressNew; CPubKey pubKeyMasternodeNew; CKey keyMasternodeNew; //need correct blocks to send ping if (!fOffline && !masternodeSync.IsBlockchainSynced()) { strErrorRet = "Sync in progress. Must wait until sync is complete to start Masternode"; LogPrint(BCLog::MASTERNODE,"CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!CMessageSigner::GetKeysFromSecret(strKeyMasternode, keyMasternodeNew, pubKeyMasternodeNew)) { strErrorRet = strprintf("Invalid masternode key %s", strKeyMasternode); LogPrint(BCLog::MASTERNODE,"CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } std::string strError; if (!pwalletMain->GetMasternodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex, strError)) { strErrorRet = strError; // GetMasternodeVinAndKeys logs this error. Only returned for GUI error notification. LogPrint(BCLog::MASTERNODE,"CMasternodeBroadcast::Create -- %s\n", strprintf("Could not allocate txin %s:%s for masternode %s", strTxHash, strOutputIndex, strService)); return false; } int nPort; int nDefaultPort = Params().GetDefaultPort(); std::string strHost; SplitHostPort(strService, nPort, strHost); if (nPort == 0) nPort = nDefaultPort; CService _service(LookupNumeric(strHost.c_str(), nPort)); // The service needs the correct default port to work properly if (!CheckDefaultPort(_service, strErrorRet, "CMasternodeBroadcast::Create")) return false; return Create(txin, _service, keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet); } bool CMasternodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string& strErrorRet, CMasternodeBroadcast& mnbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint(BCLog::MASTERNODE, "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyMasternodeNew.GetID() = %s\n", EncodeDestination(pubKeyCollateralAddressNew.GetID()), pubKeyMasternodeNew.GetID().ToString()); CMasternodePing mnp(txin); if (!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew)) { strErrorRet = strprintf("Failed to sign ping, masternode=%s", txin.prevout.hash.ToString()); LogPrint(BCLog::MASTERNODE,"CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } mnbRet = CMasternodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyMasternodeNew, PROTOCOL_VERSION); if (!mnbRet.IsValidNetAddr()) { strErrorRet = strprintf("Invalid IP address %s, masternode=%s", mnbRet.addr.ToStringIP (), txin.prevout.hash.ToString()); LogPrint(BCLog::MASTERNODE,"CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } mnbRet.lastPing = mnp; if (!mnbRet.Sign(keyCollateralAddressNew, pubKeyCollateralAddressNew)) { strErrorRet = strprintf("Failed to sign broadcast, masternode=%s", txin.prevout.hash.ToString()); LogPrint(BCLog::MASTERNODE,"CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } return true; } bool CMasternodeBroadcast::Sign(const CKey& key, const CPubKey& pubKey) { std::string strError = ""; nMessVersion = MessageVersion::MESS_VER_HASH; const std::string strMessage = GetSignatureHash().GetHex(); if (!CMessageSigner::SignMessage(strMessage, vchSig, key)) { return error("%s : SignMessage() (nMessVersion=%d) failed", __func__, nMessVersion); } if (!CMessageSigner::VerifyMessage(pubKey, vchSig, strMessage, strError)) { return error("%s : VerifyMessage() (nMessVersion=%d) failed, error: %s\n", __func__, nMessVersion, strError); } return true; } bool CMasternodeBroadcast::Sign(const std::string strSignKey) { CKey key; CPubKey pubkey; if (!CMessageSigner::GetKeysFromSecret(strSignKey, key, pubkey)) { return error("%s : Invalid strSignKey", __func__); } return Sign(key, pubkey); } bool CMasternodeBroadcast::CheckSignature() const { std::string strError = ""; std::string strMessage = ( nMessVersion == MessageVersion::MESS_VER_HASH ? GetSignatureHash().GetHex() : GetStrMessage() ); if(!CMessageSigner::VerifyMessage(pubKeyCollateralAddress, vchSig, strMessage, strError)) return error("%s : VerifyMessage (nMessVersion=%d) failed: %s", __func__, nMessVersion, strError); return true; } bool CMasternodeBroadcast::CheckDefaultPort(CService service, std::string& strErrorRet, const std::string& strContext) { int nDefaultPort = Params().GetDefaultPort(); if (service.GetPort() != nDefaultPort) { strErrorRet = strprintf("Invalid port %u for masternode %s, only %d is supported on %s-net.", service.GetPort(), service.ToString(), nDefaultPort, Params().NetworkIDString()); LogPrint(BCLog::MASTERNODE, "%s - %s\n", strContext, strErrorRet); return false; } return true; } bool CMasternodeBroadcast::CheckAndUpdate(int& nDos) { // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint(BCLog::MASTERNODE,"mnb - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString()); nDos = 1; return false; } // incorrect ping or its sigTime if(lastPing.IsNull() || !lastPing.CheckAndUpdate(nDos, false, true)) return false; if (protocolVersion < ActiveProtocol()) { LogPrint(BCLog::MASTERNODE,"mnb - ignoring outdated Masternode %s protocol version %d\n", vin.prevout.hash.ToString(), protocolVersion); return false; } CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); if (pubkeyScript.size() != 25) { LogPrint(BCLog::MASTERNODE,"mnb - pubkey the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(pubKeyMasternode.GetID()); if (pubkeyScript2.size() != 25) { LogPrint(BCLog::MASTERNODE,"mnb - pubkey2 the wrong size\n"); nDos = 100; return false; } if (!vin.scriptSig.empty()) { LogPrint(BCLog::MASTERNODE,"mnb - Ignore Not Empty ScriptSig %s\n", vin.prevout.hash.ToString()); return false; } std::string strError = ""; if (!CheckSignature()) { // don't ban for old masternodes, their sigs could be broken because of the bug nDos = protocolVersion < MIN_PEER_MNANNOUNCE ? 0 : 100; return error("%s : Got bad Masternode address signature", __func__); } if (Params().NetworkID() == CBaseChainParams::MAIN) { if (addr.GetPort() != 2611) return false; } else if (addr.GetPort() == 2611) return false; //search existing Masternode list, this is where we update existing Masternodes with new mnb broadcasts CMasternode* pmn = mnodeman.Find(vin); // no such masternode, nothing to update if (pmn == NULL) return true; // this broadcast is older or equal than the one that we already have - it's bad and should never happen // unless someone is doing something fishy // (mapSeenMasternodeBroadcast in CMasternodeMan::ProcessMessage should filter legit duplicates) if(pmn->sigTime >= sigTime) { return error("%s : Bad sigTime %d for Masternode %20s %105s (existing broadcast is at %d)", __func__, sigTime, addr.ToString(), vin.ToString(), pmn->sigTime); } // masternode is not enabled yet/already, nothing to update if (!pmn->IsEnabled()) return true; // mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below, // after that they just need to match if (pmn->pubKeyCollateralAddress == pubKeyCollateralAddress && !pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS)) { //take the newest entry LogPrint(BCLog::MASTERNODE,"mnb - Got updated entry for %s\n", vin.prevout.hash.ToString()); if (pmn->UpdateFromNewBroadcast((*this))) { pmn->Check(); if (pmn->IsEnabled()) Relay(); } masternodeSync.AddedMasternodeList(GetHash()); } return true; } bool CMasternodeBroadcast::CheckInputsAndAdd(int& nDoS) { // we are a masternode with the same vin (i.e. already activated) and this mnb is ours (matches our Masternode privkey) // so nothing to do here for us if (fMasterNode && activeMasternode.vin != nullopt && vin.prevout == activeMasternode.vin->prevout && pubKeyMasternode == activeMasternode.pubKeyMasternode) return true; // incorrect ping or its sigTime if(lastPing.IsNull() || !lastPing.CheckAndUpdate(nDoS, false, true)) return false; // search existing Masternode list CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { // nothing to do here if we already know about this masternode and it's enabled if (pmn->IsEnabled()) return true; // if it's not enabled, remove old MN first and continue else mnodeman.Remove(pmn->vin); } CValidationState state; CMutableTransaction tx = CMutableTransaction(); CScript dummyScript; dummyScript << ToByteVector(pubKeyCollateralAddress) << OP_CHECKSIG; CTxOut vout = CTxOut((GetMNCollateral() - 0.01) * COIN, dummyScript); tx.vin.push_back(vin); tx.vout.push_back(vout); int nChainHeight = 0; { TRY_LOCK(cs_main, lockMain); if (!lockMain) { // not mnb fault, let it to be checked again later mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); masternodeSync.mapSeenSyncMNB.erase(GetHash()); return false; } if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { //set nDos state.IsInvalid(nDoS); return false; } nChainHeight = chainActive.Height(); } LogPrint(BCLog::MASTERNODE, "mnb - Accepted Masternode entry\n"); if (pcoinsTip->GetCoinDepthAtHeight(vin.prevout, nChainHeight) < MASTERNODE_MIN_CONFIRMATIONS) { LogPrint(BCLog::MASTERNODE,"mnb - Input must have at least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS); // maybe we miss few blocks, let this mnb to be checked again later mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); masternodeSync.mapSeenSyncMNB.erase(GetHash()); return false; } // verify that sig time is legit in past // should be at least not earlier than block when 1000 MNTIS tx got MASTERNODE_MIN_CONFIRMATIONS uint256 hashBlock = UINT256_ZERO; CTransaction tx2; GetTransaction(vin.prevout.hash, tx2, hashBlock, true); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pMNIndex = (*mi).second; // block for 1000 MANTISCoin tx -> 1 confirmation CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + MASTERNODE_MIN_CONFIRMATIONS - 1]; // block where tx got MASTERNODE_MIN_CONFIRMATIONS if (pConfIndex->GetBlockTime() > sigTime) { LogPrint(BCLog::MASTERNODE,"mnb - Bad sigTime %d for Masternode %s (%i conf block is at %d)\n", sigTime, vin.prevout.hash.ToString(), MASTERNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime()); return false; } } LogPrint(BCLog::MASTERNODE,"mnb - Got NEW Masternode entry - %s - %lli \n", vin.prevout.hash.ToString(), sigTime); CMasternode mn(*this); mnodeman.Add(mn); // if it matches our Masternode privkey, then we've been remotely activated if (pubKeyMasternode == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION) { activeMasternode.EnableHotColdMasterNode(vin, addr); } bool isLocal = (addr.IsRFC1918() || addr.IsLocal()) && !Params().IsRegTestNet(); if (!isLocal) Relay(); return true; } void CMasternodeBroadcast::Relay() { CInv inv(MSG_MASTERNODE_ANNOUNCE, GetHash()); g_connman->RelayInv(inv); } uint256 CMasternodeBroadcast::GetHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << sigTime; ss << pubKeyCollateralAddress; return ss.GetHash(); } CMasternodePing::CMasternodePing() : CSignedMessage(), vin(), blockHash(), sigTime(GetAdjustedTime()) { } CMasternodePing::CMasternodePing(CTxIn& newVin) : CSignedMessage(), vin(newVin), sigTime(GetAdjustedTime()) { int nHeight; { LOCK(cs_main); nHeight = chainActive.Height(); if (nHeight > 12) blockHash = chainActive[nHeight - 12]->GetBlockHash(); } } uint256 CMasternodePing::GetHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; if (nMessVersion == MessageVersion::MESS_VER_HASH) ss << blockHash; ss << sigTime; return ss.GetHash(); } std::string CMasternodePing::GetStrMessage() const { return vin.ToString() + blockHash.ToString() + std::to_string(sigTime); } bool CMasternodePing::CheckAndUpdate(int& nDos, bool fRequireEnabled, bool fCheckSigTimeOnly) { if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint(BCLog::MNPING,"%s: Signature rejected, too far into the future %s\n", __func__, vin.prevout.hash.ToString()); nDos = 1; return false; } if (sigTime <= GetAdjustedTime() - 60 * 60) { LogPrint(BCLog::MNPING,"%s: Signature rejected, too far into the past %s - %d %d \n", __func__, vin.prevout.hash.ToString(), sigTime, GetAdjustedTime()); nDos = 1; return false; } // see if we have this Masternode CMasternode* pmn = mnodeman.Find(vin); const bool isMasternodeFound = (pmn != nullptr); const bool isSignatureValid = (isMasternodeFound && CheckSignature(pmn->pubKeyMasternode)); if(fCheckSigTimeOnly) { if (isMasternodeFound && !isSignatureValid) { nDos = 33; return false; } return true; } LogPrint(BCLog::MNPING, "%s: New Ping - %s - %s - %lli\n", __func__, GetHash().ToString(), blockHash.ToString(), sigTime); if (isMasternodeFound && pmn->protocolVersion >= ActiveProtocol()) { if (fRequireEnabled && !pmn->IsEnabled()) return false; // update only if there is no known ping for this masternode or // last ping was more then MASTERNODE_MIN_MNP_SECONDS-60 ago comparing to this one if (!pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS - 60, sigTime)) { if (!isSignatureValid) { nDos = 33; return false; } // Check if the ping block hash exists in disk BlockMap::iterator mi = mapBlockIndex.find(blockHash); if (mi == mapBlockIndex.end() || !(*mi).second) { LogPrint(BCLog::MNPING,"%s: ping block not in disk. Masternode %s block hash %s\n", __func__, vin.prevout.hash.ToString(), blockHash.ToString()); return false; } // Verify ping block hash in main chain and in the [ tip > x > tip - 24 ] range. { LOCK(cs_main); if (!chainActive.Contains((*mi).second) || (chainActive.Height() - (*mi).second->nHeight > 24)) { LogPrint(BCLog::MNPING,"%s: Masternode %s block hash %s is too old or has an invalid block hash\n", __func__, vin.prevout.hash.ToString(), blockHash.ToString()); // Do nothing here (no Masternode update, no mnping relay) // Let this node to be visible but fail to accept mnping return false; } } pmn->lastPing = *this; //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it CMasternodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) { mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = *this; } pmn->Check(true); if (!pmn->IsEnabled()) return false; LogPrint(BCLog::MNPING, "%s: Masternode ping accepted, vin: %s\n", __func__, vin.prevout.hash.ToString()); Relay(); return true; } LogPrint(BCLog::MNPING, "%s: Masternode ping arrived too early, vin: %s\n", __func__, vin.prevout.hash.ToString()); //nDos = 1; //disable, this is happening frequently and causing banned peers return false; } LogPrint(BCLog::MNPING, "%s: Couldn't find compatible Masternode entry, vin: %s\n", __func__, vin.prevout.hash.ToString()); return false; } void CMasternodePing::Relay() { CInv inv(MSG_MASTERNODE_PING, GetHash()); g_connman->RelayInv(inv); }
[ "75368675+mantisnetwork@users.noreply.github.com" ]
75368675+mantisnetwork@users.noreply.github.com
d553ee2314a0907ed6a35d209eeb2d080e0ad99f
c960fc3badd537e067ff4ba1ba54b70c23922b86
/Common/pyIsing.cpp
8d4b50933e832244906a3ae81d9664266631d754
[]
no_license
DropD/FS2012-CSP-Ex
414ae6833a010ec7ed6e2f7f6f4c096dccb4ec86
f7fa8bbee3f16f64e31f6d77a227925763fe5310
refs/heads/master
2021-01-10T21:59:32.114065
2012-05-18T15:14:40
2012-05-18T15:14:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,298
cpp
#include<boost/array.hpp> #include<boost/timer/timer.hpp> #include<boost/python.hpp> #include<fstream> #include<iostream> #include<sstream> #include "NDLattice_v2.hpp" #include "NDAlgorithm.hpp" #include "NDIterate.hpp" #include "random_msk.hpp" #include "Ising.hpp" typedef random_class<double, fibonacci> drng; typedef random_class<int, fibonacci> irng; typedef csp::Lattice<int, 3, csp::bounds::periodic, irng> Lattice_int3; typedef csp::ising::Ising<Lattice_int3, drng> Ising_int3; struct Parameters { double T_begin, T_end; int Tsteps, nsteps; }; struct pyIsing { boost::multi_array<double, 2> run(int L, Parameters par) { drng rdg; irng rig(0, L); Lattice_int3 lattice(L, 1, rig); Ising_int3 ising(lattice, par.T_begin, rdg); return ising.T_run(par.T_begin, par.T_end, par.Tsteps, par.nsteps); } }; using namespace boost::python; BOOST_PYTHON_MODULE_INIT(pyIsing) { //class_<irng> ir("irng", init<int, int>()); //class_<Lattice_int3> lattice("lattice", init<int, int, irng>()); //class_<Ising_int3> ising("ising", init<Lattice_int3, double>()); //ising.def("run", &Ising_int3::T_run); class_<Parameters> par("param"); class_<pyIsing> pI("pyIsing"); pI.def("run", &pyIsing::run); }
[ "r.haeuselmann@gmx.ch" ]
r.haeuselmann@gmx.ch
c9f02f4d5e905d6291ea857a8fe96d4a954fce1e
f13052b65bcce1b0504925b35ab2936cf4e1dafb
/contrib/IECoreArnold/include/IECoreArnold/MeshAlgo.h
2f2b3dc2fb16c139db3bc359fb8fb7903ae5cf82
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
hypothetical-inc/cortex
28f776b27e2781bbd8231c8525324dd490d22150
9ff166ce3ba1b6c25b0a307d9919f323b7a2d7df
refs/heads/master
2021-07-25T05:16:50.930659
2021-06-22T20:30:36
2021-06-22T20:30:36
111,314,367
2
1
NOASSERTION
2021-03-30T15:49:31
2017-11-19T16:55:57
C++
UTF-8
C++
false
false
2,450
h
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2016, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #ifndef IECOREARNOLD_MESHALGO_H #define IECOREARNOLD_MESHALGO_H #include "IECoreArnold/Export.h" #include "IECoreScene/MeshPrimitive.h" #include "ai.h" namespace IECoreArnold { namespace MeshAlgo { IECOREARNOLD_API AtNode *convert( const IECoreScene::MeshPrimitive *mesh, const std::string &nodeName, const AtNode *parentNode = nullptr ); IECOREARNOLD_API AtNode *convert( const std::vector<const IECoreScene::MeshPrimitive *> &samples, float motionStart, float motionEnd, const std::string &nodeName, const AtNode *parentNode = nullptr ); } // namespace MeshAlgo } // namespace IECoreArnold #endif // IECOREARNOLD_MESHALGO_H
[ "thehaddonyoof@gmail.com" ]
thehaddonyoof@gmail.com
c8d747860eabf9b2d164809bf2457679507fa31f
8f59413521ec816bb36bc368d004fa219d679ea9
/C++/ADT/AVLtree/AVLtree/main.cpp
ede0edab78488dc89b4a83157e21b236823012c0
[]
no_license
ivan-karavan/Homework
ffec6ff5b90625aeb8ab0e781ae84feebc8bcb08
3506f44381a59d33bd4e447a970deae81263a546
refs/heads/master
2021-01-10T20:38:26.487128
2015-08-26T14:59:38
2015-08-26T14:59:38
37,286,544
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
cpp
/* student: Perevoshchikov Ivan group: 202SE IDE: Visual Studio 2013 */ #include "AVLTree.h" #include <string> #include "MySpellChecker.h" using namespace std; class StringComparator { public: StringComparator(){} int operator()(std::string& a, std::string& b){ return a.compare(b); } }; class Comparator { public: Comparator() {} int operator() (int a, int b) { if (a == b) return 0; if (a > b) return 1; else return -1; } }; int main(int argc, char* argv[]) { setlocale(LC_ALL, "Russian"); string fileName; MySpellChecker* spell_cheker = new MySpellChecker(); cout << "Reading Dictionary file, please wait\n"; spell_cheker->readDictionaryFile(); cout << "Write name of file to read:\n"; cin >> fileName; while (!spell_cheker->readDocumentFile(fileName)) { cin >> fileName; } if (spell_cheker->isAVLTree()) { cout << "Builded trees are AVLTree\n"; } spell_cheker->compare(); system("pause"); delete spell_cheker; return 0; }
[ "ssvvpp@mail.ru" ]
ssvvpp@mail.ru
57ac9be55733f6856a32686b7b9db4910446ec8e
b3d8a69edab32cfa2e7c3475bc06b3c75d11d57b
/src/xodr/poly3.cpp
9ae26f16e4eb2a10b8346ba518e3591b7fe7907d
[ "MIT" ]
permissive
lievenvanderheide/hackatum
91dc6540bbe3b65bb9e8801475eff00b5b234658
f014ac63cd51e1a7e6221b0407b3d1d233286fcc
refs/heads/master
2020-09-03T19:27:49.467066
2019-11-04T16:27:11
2019-11-04T16:27:11
219,546,866
0
0
null
null
null
null
UTF-8
C++
false
false
2,528
cpp
#include "poly3.h" #include <algorithm> #include <cassert> #include <cmath> #include <functional> namespace aid { namespace sim { namespace xodr { namespace { template <typename TCompare> double extremeValueInInterval(const Poly3& poly, double startT, double endT) { assert(startT <= endT); constexpr double EPSILON = 1e-6; constexpr TCompare compare; double extreme = std::max(poly.eval(startT), poly.eval(endT), compare); // If this is actually a quadratic function if (std::abs(poly.d_) < EPSILON) { // If this is actually a linear function if (std::abs(poly.c_) < EPSILON) { return extreme; } double root = -poly.b_ / (2 * poly.c_); if (root < startT || root > endT) { return extreme; } return std::max(extreme, poly.eval(root), compare); } double derivDiscSq = 4 * poly.c_ * poly.c_ - 12 * poly.d_ * poly.b_; if (derivDiscSq > 0) { double derivativeDiscriminant = std::sqrt(derivDiscSq); double rootA = (derivativeDiscriminant - 2 * poly.c_) / (6 * poly.d_); double rootB = (-derivativeDiscriminant - 2 * poly.c_) / (6 * poly.d_); if (rootA > startT && rootA < endT) { extreme = std::max(extreme, poly.eval(rootA), compare); } if (rootB > startT && rootB < endT) { extreme = std::max(extreme, poly.eval(rootB), compare); } return extreme; } else if (derivDiscSq > -EPSILON) { double root = poly.c_ / (-3 * poly.d_); return std::max(extreme, poly.eval(root), compare); } return extreme; } } // namespace double Poly3::maxValueInInterval(double startT, double endT) const { return extremeValueInInterval<std::less<double>>(*this, startT, endT); } double Poly3::minValueInInterval(double startT, double endT) const { return extremeValueInInterval<std::greater<double>>(*this, startT, endT); } Poly3 Poly3::translate(double offset) const { Poly3 result; result.d_ = d_; result.c_ = (-3 * offset * d_ + c_); result.b_ = (3 * offset * offset * d_ - 2 * offset * c_ + b_); result.a_ = -offset * offset * offset * d_ + offset * offset * c_ - offset * b_ + a_; return result; } Poly3 Poly3::scale(double factor) const { Poly3 result = *this; result.b_ *= factor; result.c_ *= (factor * factor); result.d_ *= (factor * factor * factor); return result; } }}} // namespace aid::sim::xodr
[ "lieven.vanderheide@aid-driving.eu" ]
lieven.vanderheide@aid-driving.eu
4e76ab77d117afdd62de613caa2805a92fd75457
12d8a354ea0b96e7d89ea08f0276446df3bf6de8
/mono_camera/cali.cpp
a2dbdb492f2779a910eeda187030348f1707bd38
[ "MIT" ]
permissive
michaelczhou/calibration
54c3d99d1f7f7f4f8b68d301be0f5880538a0b49
583647064d7ec251c8eb71ce8644c4a266ad0b80
refs/heads/master
2020-03-20T23:46:29.198452
2018-06-19T11:14:10
2018-06-19T11:14:10
137,862,271
0
0
null
null
null
null
UTF-8
C++
false
false
8,317
cpp
#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <fstream> using namespace cv; using namespace std; void main() { ifstream fin("calibdata.txt"); /* 标定所用图像文件的路径 */ ofstream fout("caliberation_result.txt"); /* 保存标定结果的文件 */ //读取每一幅图像,从中提取出角点,然后对角点进行亚像素精确化 Mat img; //img = imread("left01.jpg"); //cout << "hello"; //imshow("XIAORUN", img); cout << "开始提取角点………………"; int image_count = 0; /* 图像数量 */ Size image_size; /* 图像的尺寸 */ Size board_size = Size(6, 9); /* 标定板上每行、列的角点数 */ vector<Point2f> image_points_buf; /* 缓存每幅图像上检测到的角点 */ vector<vector<Point2f>> image_points_seq; /* 保存检测到的所有角点 */ string filename; int count = -1;//用于存储角点个数。 while (getline(fin, filename)) { image_count++; // 用于观察检验输出 cout << "image_count = " << image_count << endl; /* 输出检验*/ cout << "-->count = " << count; Mat imageInput = imread(filename); //imshow("xiaorun", filename); if (image_count == 1) //读入第一张图片时获取图像宽高信息 { printf("hello"); image_size.width = imageInput.cols; image_size.height = imageInput.rows; cout << "image_size.width = " << image_size.width << endl; cout << "image_size.height = " << image_size.height << endl; } /* 提取角点 */ if (0 == findChessboardCorners(imageInput, board_size, image_points_buf)) { cout << "can not find chessboard corners!\n"; //找不到角点 printf("hello"); exit(1); } else { Mat view_gray; cvtColor(imageInput, view_gray, CV_RGB2GRAY); /* 亚像素精确化 */ find4QuadCornerSubpix(view_gray, image_points_buf, Size(11, 11)); //对粗提取的角点进行精确化 image_points_seq.push_back(image_points_buf); //保存亚像素角点 /* 在图像上显示角点位置 */ drawChessboardCorners(view_gray, board_size, image_points_buf, true); //用于在图片中标记角点 imshow("Camera Calibration", view_gray);//显示图片 //printf("world"); waitKey(500);//暂停0.5S } } int total = image_points_seq.size(); cout << "total = " << total << endl; int CornerNum = board_size.width*board_size.height; //每张图片上总的角点数 for (int ii = 0; ii<total; ii++) { if (0 == ii%CornerNum)// 24 是每幅图片的角点个数。此判断语句是为了输出 图片号,便于控制台观看 { int i = -1; i = ii / CornerNum; int j = i + 1; cout << "--> 第 " << j << "图片的数据 --> : " << endl; } if (0 == ii % 3) // 此判断语句,格式化输出,便于控制台查看 { cout << endl; } else { cout.width(10); } //输出所有的角点 cout << " -->" << image_points_seq[ii][0].x; cout << " -->" << image_points_seq[ii][0].y; } cout << "角点提取完成!\n"; //以下是摄像机标定 cout << "开始标定………………"; /*棋盘三维信息*/ Size square_size = Size(10, 10); /* 实际测量得到的标定板上每个棋盘格的大小 */ vector<vector<Point3f> > object_points; /* 保存标定板上角点的三维坐标 */ /*内外参数*/ //Mat cameraMatrix = Mat(3, 3, CV_32FC1, Scalar::all(0)); /* 摄像机内参数矩阵 */ Mat cameraMatrix = Mat(3, 3, CV_64F, Scalar::all(0)); /* 摄像机内参数矩阵 */ vector<int> point_counts; // 每幅图像中角点的数量 Mat distCoeffs = Mat(1, 5, CV_64F, Scalar::all(0)); /* 摄像机的5个畸变系数:k1,k2,p1,p2,k3 */ vector<Mat> tvecsMat; /* 每幅图像的旋转向量 */ vector<Mat> rvecsMat; /* 每幅图像的平移向量 */ /* 初始化标定板上角点的三维坐标 */ int i, j, t; for (t = 0; t<image_count; t++) { vector<Point3f> tempPointSet; for (i = 0; i<board_size.height; i++) { for (j = 0; j<board_size.width; j++) { Point3f realPoint; /* 假设标定板放在世界坐标系中z=0的平面上 */ realPoint.x = i*square_size.width; realPoint.y = j*square_size.height; realPoint.z = 0; tempPointSet.push_back(realPoint); } } object_points.push_back(tempPointSet); } /* 初始化每幅图像中的角点数量,假定每幅图像中都可以看到完整的标定板 */ for (i = 0; i<image_count; i++) { point_counts.push_back(board_size.width*board_size.height); } /* 开始标定 */ calibrateCamera(object_points, image_points_seq, image_size, cameraMatrix, distCoeffs, rvecsMat, tvecsMat, 0); cout << "标定完成!\n"; //对标定结果进行评价 cout << "开始评价标定结果………………\n"; double total_err = 0.0; /* 所有图像的平均误差的总和 */ double err = 0.0; /* 每幅图像的平均误差 */ vector<Point2f> image_points2; /* 保存重新计算得到的投影点 */ cout << "\t每幅图像的标定误差:\n"; fout << "每幅图像的标定误差:\n"; for (i = 0; i<image_count; i++) { vector<Point3f> tempPointSet = object_points[i]; /* 通过得到的摄像机内外参数,对空间的三维点进行重新投影计算,得到新的投影点 */ projectPoints(tempPointSet, rvecsMat[i], tvecsMat[i], cameraMatrix, distCoeffs, image_points2); /* 计算新的投影点和旧的投影点之间的误差*/ vector<Point2f> tempImagePoint = image_points_seq[i]; Mat tempImagePointMat = Mat(1, tempImagePoint.size(), CV_32FC2); Mat image_points2Mat = Mat(1, image_points2.size(), CV_32FC2); for (int j = 0; j < tempImagePoint.size(); j++) { image_points2Mat.at<Vec2f>(0, j) = Vec2f(image_points2[j].x, image_points2[j].y); tempImagePointMat.at<Vec2f>(0, j) = Vec2f(tempImagePoint[j].x, tempImagePoint[j].y); } err = norm(image_points2Mat, tempImagePointMat, NORM_L2); total_err += err /= point_counts[i]; std::cout << "第" << i + 1 << "幅图像的平均误差:" << err << "像素" << endl; fout << "第" << i + 1 << "幅图像的平均误差:" << err << "像素" << endl; } std::cout << "总体平均误差:" << total_err / image_count << "像素" << endl; fout << "总体平均误差:" << total_err / image_count << "像素" << endl << endl; std::cout << "评价完成!" << endl; //保存定标结果 std::cout << "开始保存定标结果………………" << endl; Mat rotation_matrix = Mat(3, 3, CV_32FC1, Scalar::all(0)); /* 保存每幅图像的旋转矩阵 */ fout << "相机内参数矩阵:" << endl; fout << cameraMatrix << endl << endl; fout << "畸变系数:\n"; fout << distCoeffs << endl << endl << endl; for (int i = 0; i<image_count; i++) { fout << "第" << i + 1 << "幅图像的旋转向量:" << endl; fout << tvecsMat[i] << endl; /* 将旋转向量转换为相对应的旋转矩阵 */ Rodrigues(tvecsMat[i], rotation_matrix); fout << "第" << i + 1 << "幅图像的旋转矩阵:" << endl; fout << rotation_matrix << endl; fout << "第" << i + 1 << "幅图像的平移向量:" << endl; fout << rvecsMat[i] << endl << endl; } std::cout << "完成保存" << endl; fout << endl; system("pause"); return; }
[ "1205464428@qq.com" ]
1205464428@qq.com
1f9537cbd482a89c3e5aa8bf63a70d0cb74c1599
34c81af880b0012bbe03d4fd99b3b012cacaf857
/V_Engine/ModuleInput.cpp
0e3af0862d23e97b75c19abbbb74da59e7713b5d
[]
no_license
Vulpem/V_Terrains
f8783f60fe437cc446add5db107cd2fc4814ebac
d680d2f0373a0a545bf27d68809b3f986e0bd96d
refs/heads/master
2021-07-16T07:37:50.461246
2018-11-26T15:38:44
2018-11-26T15:38:44
109,832,995
0
0
null
2018-03-07T12:53:52
2017-11-07T12:30:34
C
UTF-8
C++
false
false
4,187
cpp
#include "Globals.h" #include "Application.h" #include "ModuleInput.h" #include "ModuleRenderer3D.h" #include "ModuleWindow.h" #include "imGUI/imgui.h" #include "Imgui/imgui_impl_sdl_gl3.h" #define MAX_KEYS SDL_NUM_SCANCODES ModuleInput::ModuleInput() : Module() { m_keyboardStates = new KEY_STATE[MAX_KEYS + 1]; memset(m_keyboardStates, KEY_IDLE, sizeof(KEY_STATE) * MAX_KEYS); memset(m_mouseButtons, KEY_IDLE, sizeof(KEY_STATE) * MAX_MOUSE_BUTTONS); } // Destructor ModuleInput::~ModuleInput() { delete[] m_keyboardStates; } // Called before render is available bool ModuleInput::Init() { LOG("Init SDL input event system"); bool ret = true; SDL_Init(0); //SDL_ShowCursor(0); if(SDL_InitSubSystem(SDL_INIT_EVENTS) < 0) { LOG("SDL_EVENTS could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } m_lastDroppedFile[0] = '\0'; m_fileWasDropped = false; return ret; } // Called every draw update UpdateStatus ModuleInput::PreUpdate() { SDL_PumpEvents(); m_fileWasDropped = false; const Uint8* keys = SDL_GetKeyboardState(NULL); for(int i = 0; i < MAX_KEYS; ++i) { if(keys[i] == 1 && m_ignoreKeyboard == false) { if(m_keyboardStates[i] == KEY_IDLE) m_keyboardStates[i] = KEY_DOWN; else m_keyboardStates[i] = KEY_REPEAT; } else { if(m_keyboardStates[i] == KEY_REPEAT || m_keyboardStates[i] == KEY_DOWN) m_keyboardStates[i] = KEY_UP; else m_keyboardStates[i] = KEY_IDLE; } } Uint32 buttons = SDL_GetMouseState(&m_mouseX, &m_mouseY); m_mouseZ = 0; for(int i = 0; i < 5; ++i) { if(buttons & SDL_BUTTON(i) && m_ignoreMouse == false) { if(m_mouseButtons[i] == KEY_IDLE) m_mouseButtons[i] = KEY_DOWN; else m_mouseButtons[i] = KEY_REPEAT; } else { if(m_mouseButtons[i] == KEY_REPEAT || m_mouseButtons[i] == KEY_DOWN) m_mouseButtons[i] = KEY_UP; else m_mouseButtons[i] = KEY_IDLE; } } m_mouseMotionX = m_mouseMotionY = 0; SDL_Event e; while(SDL_PollEvent(&e)) { if (m_ignoreMouse == false) { switch (e.type) { case SDL_EventType::SDL_MOUSEWHEEL: { m_mouseZ = e.wheel.y; break; } case SDL_EventType::SDL_MOUSEMOTION: { if (m_captureMouse) { if (CaptureMouse(e)) { ImGui::GetIO().MousePos = ImVec2(-1, -1); ImGui::GetIO().MousePosPrev = ImVec2(-1, -1); } } m_mouseX = e.motion.x; m_mouseY = e.motion.y; m_mouseMotionX = e.motion.xrel; m_mouseMotionY = e.motion.yrel; break; } case SDL_EventType::SDL_DROPFILE: { strcpy_s(m_lastDroppedFile, e.drop.file); SDL_free(e.drop.file); m_fileWasDropped = true; LOG("Dropped %s", m_lastDroppedFile); break; } case SDL_EventType::SDL_QUIT: { return UpdateStatus::Stop; } case SDL_EventType::SDL_WINDOWEVENT: { if (e.window.event == SDL_WindowEventID::SDL_WINDOWEVENT_RESIZED) { App->OnScreenResize(e.window.data1, e.window.data2); } } } } ImGui_ImplSdlGL3_ProcessEvent(&e); } /*if (GetMouseButton(SDL_BUTTON_LEFT) == KEY_DOWN) { captureMouse = true; } else if (GetMouseButton(SDL_BUTTON_LEFT) == KEY_UP) { captureMouse = false; }*/ return UpdateStatus::Continue; } // Called before quitting void ModuleInput::OnDisable() { LOG("Quitting SDL input event subsystem"); SDL_QuitSubSystem(SDL_INIT_EVENTS); } bool ModuleInput::CaptureMouse(SDL_Event& e) { bool ret = false; float2 windowSize = App->m_window->GetWindowSize(); if (m_mouseX + e.motion.xrel >= windowSize.x) { SDL_WarpMouseInWindow(App->m_window->GetWindow(), 1, e.motion.y); e.motion.xrel = 0; ret = true; } else if (m_mouseX + e.motion.xrel <= 0) { SDL_WarpMouseInWindow(App->m_window->GetWindow(), windowSize.x - 1, e.motion.y); e.motion.xrel = 0; ret = true; } if (m_mouseY + e.motion.yrel >= windowSize.y) { SDL_WarpMouseInWindow(App->m_window->GetWindow(), e.motion.x, 1); e.motion.yrel = 0; ret = true; } else if (m_mouseY + e.motion.yrel <= 0) { SDL_WarpMouseInWindow(App->m_window->GetWindow(), e.motion.x, windowSize.y - 1); e.motion.yrel = 0; ret = true; } return ret; }
[ "davidher96@gmail.com" ]
davidher96@gmail.com
4b28404e49c83fa00e48637bf362a2365f8362d7
6409650a23f65136afd961206c2a8870e1f78c7e
/ConceptEngine/ConceptEngine/ConceptEngineRenderer/RenderLayer/RenderingCore.h
d051f1c88294f4ff57aadc753b8eb6a27c03de12
[ "MIT" ]
permissive
Ludaxord/ConceptEngine
830486b52a72e1fe7a4b821b4f725443ff180afe
16775bc9b518d4fd4c8bd32bb5f297223dfacbae
refs/heads/master
2023-08-16T11:33:00.694333
2021-10-07T21:11:00
2021-10-07T21:11:00
293,779,912
6
0
MIT
2021-08-16T20:33:47
2020-09-08T10:42:33
C++
UTF-8
C++
false
false
19,245
h
#pragma once #include "../CEDefinitions.h" #include "../Math/Color.h" enum class ECubeFace { PosX = 0, NegX = 1, PosY = 2, NegY = 3, PosZ = 4, NegZ = 5, }; inline uint32 GetCubeFaceIndex(ECubeFace CubeFace) { return static_cast<uint32>(CubeFace); } inline ECubeFace GetCubeFaceFromIndex(uint32 Index) { if (Index > GetCubeFaceIndex(ECubeFace::NegZ)) { return static_cast<ECubeFace>(-1); } else { return static_cast<ECubeFace>(Index); } } enum class EFormat { Unknown = 0, R32G32B32A32_Typeless = 1, R32G32B32A32_Float = 2, R32G32B32A32_Uint = 3, R32G32B32A32_Sint = 4, R32G32B32_Typeless = 5, R32G32B32_Float = 6, R32G32B32_Uint = 7, R32G32B32_Sint = 8, R16G16B16A16_Typeless = 9, R16G16B16A16_Float = 10, R16G16B16A16_Unorm = 11, R16G16B16A16_Uint = 12, R16G16B16A16_Snorm = 13, R16G16B16A16_Sint = 14, R32G32_Typeless = 15, R32G32_Float = 16, R32G32_Uint = 17, R32G32_Sint = 18, R10G10B10A2_Typeless = 23, R10G10B10A2_Unorm = 24, R10G10B10A2_Uint = 25, R11G11B10_Float = 26, R8G8B8A8_Typeless = 27, R8G8B8A8_Unorm = 28, R8G8B8A8_Unorm_SRGB = 29, R8G8B8A8_Uint = 30, R8G8B8A8_Snorm = 31, R8G8B8A8_Sint = 32, R16G16_Typeless = 33, R16G16_Float = 34, R16G16_Unorm = 35, R16G16_Uint = 36, R16G16_Snorm = 37, R16G16_Sint = 38, R32_Typeless = 39, D32_Float = 40, R32_Float = 41, R32_Uint = 42, R32_Sint = 43, R24G8_Typeless = 44, D24_Unorm_S8_Uint = 45, R24_Unorm_X8_Typeless = 46, X24_Typeless_G8_Uint = 47, R8G8_Typeless = 48, R8G8_Unorm = 49, R8G8_Uint = 50, R8G8_Snorm = 51, R8G8_Sint = 52, R16_Typeless = 53, R16_Float = 54, D16_Unorm = 55, R16_Unorm = 56, R16_Uint = 57, R16_Snorm = 58, R16_Sint = 59, R8_Typeless = 60, R8_Unorm = 61, R8_Uint = 62, R8_Snorm = 63, R8_Sint = 64, }; inline const char* ToString(EFormat Format) { switch (Format) { case EFormat::R32G32B32A32_Typeless: return "R32G32B32A32_Typeless"; case EFormat::R32G32B32A32_Float: return "R32G32B32A32_Float"; case EFormat::R32G32B32A32_Uint: return "R32G32B32A32_Uint"; case EFormat::R32G32B32A32_Sint: return "R32G32B32A32_Sint"; case EFormat::R32G32B32_Typeless: return "R32G32B32_Typeless"; case EFormat::R32G32B32_Float: return "R32G32B32_Float"; case EFormat::R32G32B32_Uint: return "R32G32B32_Uint"; case EFormat::R32G32B32_Sint: return "R32G32B32_Sint"; case EFormat::R16G16B16A16_Typeless: return "R16G16B16A16_Typeless"; case EFormat::R16G16B16A16_Float: return "R16G16B16A16_Float"; case EFormat::R16G16B16A16_Unorm: return "R16G16B16A16_Unorm"; case EFormat::R16G16B16A16_Uint: return "R16G16B16A16_Uint"; case EFormat::R16G16B16A16_Snorm: return "R16G16B16A16_Snorm"; case EFormat::R16G16B16A16_Sint: return "R16G16B16A16_Sint"; case EFormat::R32G32_Typeless: return "R32G32_Typeless"; case EFormat::R32G32_Float: return "R32G32_Float"; case EFormat::R32G32_Uint: return "R32G32_Uint"; case EFormat::R32G32_Sint: return "R32G32_Sint"; case EFormat::R10G10B10A2_Typeless: return "R10G10B10A2_Typeless"; case EFormat::R10G10B10A2_Unorm: return "R10G10B10A2_Unorm"; case EFormat::R10G10B10A2_Uint: return "R10G10B10A2_Uint"; case EFormat::R11G11B10_Float: return "R11G11B10_Float"; case EFormat::R8G8B8A8_Typeless: return "R8G8B8A8_Typeless"; case EFormat::R8G8B8A8_Unorm: return "R8G8B8A8_Unorm"; case EFormat::R8G8B8A8_Unorm_SRGB: return "R8G8B8A8_Unorm_SRGB"; case EFormat::R8G8B8A8_Uint: return "R8G8B8A8_Uint"; case EFormat::R8G8B8A8_Snorm: return "R8G8B8A8_Snorm"; case EFormat::R8G8B8A8_Sint: return "R8G8B8A8_Sint"; case EFormat::R16G16_Typeless: return "R16G16_Typeless"; case EFormat::R16G16_Float: return "R16G16_Float"; case EFormat::R16G16_Unorm: return "R16G16_Unorm"; case EFormat::R16G16_Uint: return "R16G16_Uint"; case EFormat::R16G16_Snorm: return "R16G16_Snorm"; case EFormat::R16G16_Sint: return "R16G16_Sint"; case EFormat::R32_Typeless: return "R32_Typeless"; case EFormat::D32_Float: return "D32_Float"; case EFormat::R32_Float: return "R32_Float"; case EFormat::R32_Uint: return "R32_Uint"; case EFormat::R32_Sint: return "R32_Sint"; case EFormat::R24G8_Typeless: return "R24G8_Typeless"; case EFormat::D24_Unorm_S8_Uint: return "D24_Unorm_S8_Uint"; case EFormat::R24_Unorm_X8_Typeless: return "R24_Unorm_X8_Typeless"; case EFormat::X24_Typeless_G8_Uint: return "X24_Typeless_G8_Uint"; case EFormat::R8G8_Typeless: return "R8G8_Typeless"; case EFormat::R8G8_Unorm: return "R8G8_Unorm"; case EFormat::R8G8_Uint: return "R8G8_Uint"; case EFormat::R8G8_Snorm: return "R8G8_Snorm"; case EFormat::R8G8_Sint: return "R8G8_Sint"; case EFormat::R16_Typeless: return "R16_Typeless"; case EFormat::R16_Float: return "R16_Float"; case EFormat::D16_Unorm: return "D16_Unorm"; case EFormat::R16_Unorm: return "R16_Unorm"; case EFormat::R16_Uint: return "R16_Uint"; case EFormat::R16_Snorm: return "R16_Snorm"; case EFormat::R16_Sint: return "R16_Sint"; case EFormat::R8_Typeless: return "R8_Typeless"; case EFormat::R8_Unorm: return "R8_Unorm"; case EFormat::R8_Uint: return "R8_Uint"; case EFormat::R8_Snorm: return "R8_Snorm"; case EFormat::R8_Sint: return "R8_Sint"; default: return "Unknown"; } } inline uint32 GetByteStrideFromFormat(EFormat Format) { switch (Format) { case EFormat::R32G32B32A32_Typeless: case EFormat::R32G32B32A32_Float: case EFormat::R32G32B32A32_Uint: case EFormat::R32G32B32A32_Sint: { return 16; } case EFormat::R32G32B32_Typeless: case EFormat::R32G32B32_Float: case EFormat::R32G32B32_Uint: case EFormat::R32G32B32_Sint: { return 12; } case EFormat::R16G16B16A16_Typeless: case EFormat::R16G16B16A16_Float: case EFormat::R16G16B16A16_Unorm: case EFormat::R16G16B16A16_Uint: case EFormat::R16G16B16A16_Snorm: case EFormat::R16G16B16A16_Sint: case EFormat::R32G32_Typeless: case EFormat::R32G32_Float: case EFormat::R32G32_Uint: case EFormat::R32G32_Sint: { return 8; } case EFormat::R10G10B10A2_Typeless: case EFormat::R10G10B10A2_Unorm: case EFormat::R10G10B10A2_Uint: case EFormat::R11G11B10_Float: case EFormat::R8G8B8A8_Typeless: case EFormat::R8G8B8A8_Unorm: case EFormat::R8G8B8A8_Unorm_SRGB: case EFormat::R8G8B8A8_Uint: case EFormat::R8G8B8A8_Snorm: case EFormat::R8G8B8A8_Sint: case EFormat::R16G16_Typeless: case EFormat::R16G16_Float: case EFormat::R16G16_Unorm: case EFormat::R16G16_Uint: case EFormat::R16G16_Snorm: case EFormat::R16G16_Sint: case EFormat::R32_Typeless: case EFormat::D32_Float: case EFormat::R32_Float: case EFormat::R32_Uint: case EFormat::R32_Sint: case EFormat::R24G8_Typeless: case EFormat::D24_Unorm_S8_Uint: case EFormat::R24_Unorm_X8_Typeless: case EFormat::X24_Typeless_G8_Uint: { return 4; } case EFormat::R8G8_Typeless: case EFormat::R8G8_Unorm: case EFormat::R8G8_Uint: case EFormat::R8G8_Snorm: case EFormat::R8G8_Sint: case EFormat::R16_Typeless: case EFormat::R16_Float: case EFormat::D16_Unorm: case EFormat::R16_Unorm: case EFormat::R16_Uint: case EFormat::R16_Snorm: case EFormat::R16_Sint: { return 2; } case EFormat::R8_Typeless: case EFormat::R8_Unorm: case EFormat::R8_Uint: case EFormat::R8_Snorm: case EFormat::R8_Sint: { return 1; } default: { return 0; } } } enum class EComparisonFunc { Never = 1, Less = 2, Equal = 3, LessEqual = 4, Greater = 5, NotEqual = 6, GreaterEqual = 7, Always = 8 }; inline const char* ToString(EComparisonFunc ComparisonFunc) { switch (ComparisonFunc) { case EComparisonFunc::Never: return "Never"; case EComparisonFunc::Less: return "Less"; case EComparisonFunc::Equal: return "Equal"; case EComparisonFunc::LessEqual: return "LessEqual"; case EComparisonFunc::Greater: return "Greater"; case EComparisonFunc::NotEqual: return "NotEqual"; case EComparisonFunc::GreaterEqual: return "GreaterEqual"; case EComparisonFunc::Always: return "Always"; default: return "Unknown"; } } enum class EPrimitiveTopologyType { Undefined = 0, Point = 1, Line = 2, Triangle = 3, Patch = 4 }; inline const char* ToString(EPrimitiveTopologyType PrimitveTopologyType) { switch (PrimitveTopologyType) { case EPrimitiveTopologyType::Undefined: return "Undefined"; case EPrimitiveTopologyType::Point: return "Point"; case EPrimitiveTopologyType::Line: return "Line"; case EPrimitiveTopologyType::Triangle: return "Triangle"; case EPrimitiveTopologyType::Patch: return "Patch"; default: return "Unknown"; } } enum class EResourceState { Common = 0, VertexAndConstantBuffer = 1, IndexBuffer = 2, RenderTarget = 3, UnorderedAccess = 4, DepthWrite = 5, DepthRead = 6, NonPixelShaderResource = 7, PixelShaderResource = 8, CopyDest = 9, CopySource = 10, ResolveDest = 11, ResolveSource = 12, RayTracingAccelerationStructure = 13, ShadingRateSource = 14, Present = 15, GenericRead = 16, }; inline const char* ToString(EResourceState ResourceState) { switch (ResourceState) { case EResourceState::Common: return "Common"; case EResourceState::VertexAndConstantBuffer: return "VertexAndConstantBuffer"; case EResourceState::IndexBuffer: return "IndexBuffer"; case EResourceState::RenderTarget: return "RenderTarget"; case EResourceState::UnorderedAccess: return "UnorderedAccess"; case EResourceState::DepthWrite: return "DepthWrite"; case EResourceState::DepthRead: return "DepthRead"; case EResourceState::NonPixelShaderResource: return "NonPixelShaderResource"; case EResourceState::PixelShaderResource: return "PixelShaderResource"; case EResourceState::CopyDest: return "CopyDest"; case EResourceState::CopySource: return "CopySource"; case EResourceState::ResolveDest: return "ResolveDest"; case EResourceState::ResolveSource: return "ResolveSource"; case EResourceState::RayTracingAccelerationStructure: return "RayTracingAccelerationStructure"; case EResourceState::ShadingRateSource: return "ShadingRateSource"; case EResourceState::Present: return "Present"; default: return "Unknown"; } } enum class EPrimitiveTopology { Undefined = 0, PointList = 1, LineList = 2, LineStrip = 3, TriangleList = 4, TriangleStrip = 5, }; inline const char* ToString(EPrimitiveTopology ResourceState) { switch (ResourceState) { case EPrimitiveTopology::Undefined: return "Undefined"; case EPrimitiveTopology::PointList: return "PointList"; case EPrimitiveTopology::LineList: return "LineList"; case EPrimitiveTopology::LineStrip: return "LineStrip"; case EPrimitiveTopology::TriangleList: return "TriangleList"; case EPrimitiveTopology::TriangleStrip: return "TriangleStrip"; default: return "Unknown"; } } enum class EShadingRate { VRS_1x1 = 0x0, VRS_1x2 = 0x1, VRS_2x1 = 0x4, VRS_2x2 = 0x5, VRS_2x4 = 0x6, VRS_4x2 = 0x9, VRS_4x4 = 0xa, }; inline const char* ToString(EShadingRate ShadingRate) { switch (ShadingRate) { case EShadingRate::VRS_1x1: return "VRS_1x1"; case EShadingRate::VRS_1x2: return "VRS_1x2"; case EShadingRate::VRS_2x1: return "VRS_2x1"; case EShadingRate::VRS_2x2: return "VRS_2x2"; case EShadingRate::VRS_2x4: return "VRS_2x4"; case EShadingRate::VRS_4x2: return "VRS_4x2"; case EShadingRate::VRS_4x4: return "VRS_4x4"; default: return "Unknown"; } } struct DepthStencilF { DepthStencilF() = default; DepthStencilF(float InDepth, uint8 InStencil) : Depth(InDepth) , Stencil(InStencil) { } float Depth = 1.0f; uint8 Stencil = 0; }; struct ClearValue { public: enum class EType { Color = 1, DepthStencil = 2 }; // NOTE: Default clear color is black ClearValue() : Type(EType::Color) , Format(EFormat::Unknown) , Color(0.0f, 0.0f, 0.0f, 1.0f) { } ClearValue(EFormat InFormat, float Depth, uint8 Stencil) : Type(EType::DepthStencil) , Format(InFormat) , DepthStencil(Depth, Stencil) { } ClearValue(EFormat InFormat, float r, float g, float b, float a) : Type(EType::Color) , Format(InFormat) , Color(r, g, b, a) { } ClearValue(const ClearValue& Other) : Type(Other.Type) , Format(Other.Format) , Color() { if (Other.Type == EType::Color) { Color = Other.Color; } else if (Other.Type == EType::DepthStencil) { DepthStencil = Other.DepthStencil; } } ClearValue& operator=(const ClearValue& Other) { Type = Other.Type; Format = Other.Format; if (Other.Type == EType::Color) { Color = Other.Color; } else if (Other.Type == EType::DepthStencil) { DepthStencil = Other.DepthStencil; } return *this; } EType GetType() const { return Type; } EFormat GetFormat() const { return Format; } ColorF& AsColor() { Assert(Type == EType::Color); return Color; } const ColorF& AsColor() const { Assert(Type == EType::Color); return Color; } DepthStencilF& AsDepthStencil() { Assert(Type == EType::DepthStencil); return DepthStencil; } const DepthStencilF& AsDepthStencil() const { Assert(Type == EType::DepthStencil); return DepthStencil; } private: EType Type; EFormat Format; union { ColorF Color; DepthStencilF DepthStencil; }; }; struct ResourceData { ResourceData() : Data(nullptr) { } ResourceData(const void* InData, uint32 InSizeInBytes) : Data(InData) , SizeInBytes(InSizeInBytes) { } ResourceData(const void* InData, EFormat InFormat, uint32 InWidth) : Data(InData) , Format(InFormat) , Width(InWidth) , Height(0) { } ResourceData(const void* InData, EFormat InFormat, uint32 InWidth, uint32 InHeight) : Data(InData) , Format(InFormat) , Width(InWidth) , Height(InHeight) { } void Set(const void* InData, uint32 InSizeInBytes) { Data = InData; SizeInBytes = InSizeInBytes; } void Set(const void* InData, EFormat InFormat, uint32 InWidth) { Data = InData; Format = InFormat; Width = InWidth; } void Set(const void* InData, EFormat InFormat, uint32 InWidth, uint32 InHeight) { Set(InData, InFormat, InWidth, InHeight); Height = InHeight; } const void* GetData() const { return Data; } uint32 GetSizeInBytes() const { return SizeInBytes; } uint32 GetPitch() const { return GetByteStrideFromFormat(Format) * Width; } uint32 GetSlicePitch() const { return GetByteStrideFromFormat(Format) * Width * Height; } private: const void* Data; union { struct { uint32 SizeInBytes; }; struct { EFormat Format; uint32 Width; uint32 Height; }; }; }; struct CopyBufferInfo { CopyBufferInfo() = default; CopyBufferInfo(uint64 InSourceOffset, uint32 InDestinationOffset, uint32 InSizeInBytes) : SourceOffset(InSourceOffset) , DestinationOffset(InDestinationOffset) , SizeInBytes(InSizeInBytes) { } uint64 SourceOffset = 0; uint32 DestinationOffset = 0; uint32 SizeInBytes = 0; }; struct CopyTextureSubresourceInfo { CopyTextureSubresourceInfo() = default; CopyTextureSubresourceInfo(uint32 InX, uint32 InY, uint32 InZ, uint32 InSubresourceIndex) : x(InX) , y(InY) , z(InZ) , SubresourceIndex(InSubresourceIndex) { } uint32 x = 0; uint32 y = 0; uint32 z = 0; uint32 SubresourceIndex = 0; }; struct CopyTextureInfo { CopyTextureSubresourceInfo Source; CopyTextureSubresourceInfo Destination; uint32 Width = 0; uint32 Height = 0; uint32 Depth = 0; };
[ "konrad.uciechowski@gmail.com" ]
konrad.uciechowski@gmail.com
acf59681347094cc45cf6aca72ab8a737d1abd87
38fa9993d11d4bf03495dd76da92c87dd517e4d1
/main.cpp
0d87e4e75f9a2041c88d8156f01ba45b14f34c69
[ "MIT" ]
permissive
wangmh2003/datamodule
99d5eaae8c9ecb6f29fcdc04432932b3e8de7954
dcd76398cbfa39bba0c743d2d58aeff3aeec77cf
refs/heads/main
2023-02-20T07:02:25.627073
2021-01-15T16:16:52
2021-01-15T16:16:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,693
cpp
#include "include/normal_typedef.h" #include "feature/easyloggingpp/src/easylogging++.h" #include "thirdparty/restclient/include/restclient-cpp/restclient.h" #include "common/typeany/inc/typeany.h" #include "product/inc/datacollecter.h" /// 西门子CNC test #include "protocol/SimensCnc/Simens/libsiemenscnc/inc/siemenscnc.h" #include "protocol/SimensCnc/Simens/libsiemenscnc/828d/siemens_828d_new.h" /// JSON #include "include/json.hpp" #include <fstream> using namespace std; using json = nlohmann::json; #ifdef ELPP_THREAD_SAFE INITIALIZE_EASYLOGGINGPP #endif #if ELPP_FEATURE_CRASH_LOG void myCrashHandler(int sig) { LOG(ERROR) << "Woops! Crashed!"; // FOLLOWING LINE IS ABSOLUTELY NEEDED AT THE END IN ORDER TO ABORT APPLICATION el::Helpers::crashAbort(sig); } #endif void easylogginginit() { // 加载配置文件,构造一个配置器对象 el::Configurations conf( "/home/fchuanlin/datamodule/doc/log.conf" ); // 重新配置一个单一日志记录器 el::Loggers::reconfigureLogger( "default", conf ); // 用配置文件配置所有的日志记录器 el::Loggers::reconfigureAllLoggers( conf ); #if ELPP_FEATURE_CRASH_LOG el:: Helpers::setCrashHandler(myCrashHandler); #endif } int main( int argc, char * argv[] ) { easylogginginit(); LOG( INFO ) << "Start DataModule! "; /// 开启采集线程 DataCollecter *pDC = new DataCollecter(); pDC->Init(); if( argc > 1 ) { /// 读取配置文件 pDC->InitIOListByJson( ( const CHAR * )argv[1] ); } else { pDC->InitIOListByJson( ( const CHAR * )"get_param.json" ); } pDC->Start(); return 0; }
[ "fchuanlin@localhost.localdomain" ]
fchuanlin@localhost.localdomain
f2648396e6ad7bc9e28686dcf19c5b72abcafbda
350b13fa239d83b98137dc0a3b2a67a0882e3d70
/shared/include/packet.h
d022391375c1bbe85e7dfd99e66b1cf0830b7dfc
[]
no_license
Dumtard/Dragon-Ponies
e4c7c4add9faddb308ca572672231881a785b9ca
01b2c22924363447f1b2d5e0c861804fc001909d
refs/heads/master
2021-03-30T17:28:26.205597
2017-09-07T19:09:07
2017-09-09T18:02:41
102,775,743
0
0
null
null
null
null
UTF-8
C++
false
false
1,163
h
#ifndef PACKET_H #define PACKET_H #include <iostream> #include <cstring> #include <SDL2/SDL_endian.h> SDL_FORCE_INLINE float swapFloat(float x) { if (SDL_BYTEORDER != SDL_BIG_ENDIAN) { std::cout << "HERE" << std::endl; return SDL_SwapFloat(x); } return x; } struct Packet { float x; float y; public: Packet() : x(0), y(0) {} Packet(float x, float y) { this->x = swapFloat(x); this->y = swapFloat(y); } Packet(char* buffer) { auto end = sizeof(Packet); std::copy(buffer, buffer+end, reinterpret_cast<char*>(this)); this->x = swapFloat(x); this->y = swapFloat(y); } void serialize(char*); friend std::ostream& operator<< (std::ostream& os, const Packet& p) { os << p.x << ", " << p.y; return os; } }; inline void Packet::serialize(char* msg) { Packet packet(this->x, this->y); std::memcpy(msg, &packet, sizeof(Packet)); } #endif //PACKET_H
[ "charles.black90@gmail.com" ]
charles.black90@gmail.com
989e9f1408203c1a92c418db9c55063cf14a72b6
ce254e72b4ec80c72a25264b4788bfe39968f6b7
/Source/iDoNew/Main.cpp
7686c20cb692c8bb448bb1bf3cf324ae534f2280
[]
no_license
supraja2610/iDo
2376b8ed7d30834028c4023f4b48e32f2589e3b3
c42a2dfa33a9cef980dc0d04bd74f4f329b0c7a0
refs/heads/master
2016-08-05T17:06:37.457968
2013-06-16T12:08:31
2013-06-16T12:08:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
194
cpp
#include "Logic.h" #include "Tester.h" int main(int argument_count, char** argument_vars) { //runTest(argument_count, argument_vars) ; Logic driver ; driver.logicMain() ; return 0 ; }
[ "suprajabhavanisekhar@gmail.com" ]
suprajabhavanisekhar@gmail.com
1be7b6cd7a92bf5134076eb70ccc3244531832fa
f65bf1756c49c16cf5a061b3e97c18824877eb6e
/U1661665/Engine/Engine/positionclass.cpp
c201e8eb45c277084b7a969c7404b5e6a06ef4fa
[]
no_license
Natalo77/Studio2
210510d0a9905d97cf09aed5126b95c406c9507a
8c8291dfeb97e7980585ce8f2d34210443818c6f
refs/heads/master
2020-04-19T17:32:24.722660
2019-03-12T14:26:59
2019-03-12T14:26:59
168,337,998
0
0
null
null
null
null
UTF-8
C++
false
false
7,682
cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: positionclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "positionclass.h" PositionClass::PositionClass() { m_positionX = 0.0f; m_positionY = 0.0f; m_positionZ = 0.0f; m_rotationX = 0.0f; m_rotationY = 0.0f; m_rotationZ = 0.0f; m_frameTime = 0.0f; m_forwardSpeed = 0.0f; m_backwardSpeed = 0.0f; m_upwardSpeed = 0.0f; m_downwardSpeed = 0.0f; m_leftTurnSpeed = 0.0f; m_rightTurnSpeed = 0.0f; m_lookDownSpeed = 0.0f; m_lookUpSpeed = 0.0f; } PositionClass::PositionClass(const PositionClass& other) { } PositionClass::~PositionClass() { } void PositionClass::SetPosition(float x, float y, float z) { m_positionX = x; m_positionY = y; m_positionZ = z; return; } void PositionClass::SetRotation(float x, float y, float z) { m_rotationX = x; m_rotationY = y; m_rotationZ = z; return; } void PositionClass::GetPosition(float& x, float& y, float& z) { x = m_positionX; y = m_positionY; z = m_positionZ; return; } void PositionClass::GetRotation(float& x, float& y, float& z) { x = m_rotationX; y = m_rotationY; z = m_rotationZ; return; } void PositionClass::setFrameTime(float time) { m_frameTime = time; return; } void PositionClass::MoveForward(bool keydown, bool sprintKeyDown) { float radians; int speedMod = 1 + sprintKeyDown; //Updates the forward speed movement based on the frame time //and whether the user is holding the key down or not. if (keydown) { m_forwardSpeed += m_frameTime * 0.001f * speedMod; if (m_forwardSpeed > (m_frameTime * 0.03f * speedMod)) { m_forwardSpeed = m_frameTime * 0.03f * speedMod; } } else { m_forwardSpeed -= m_frameTime * 0.0007f; if (m_forwardSpeed < 0.0f) { m_forwardSpeed = 0.0f; } } //Convert degrees to radians. radians = m_rotationY * 0.0174532925f; //Update the position. m_positionX += sinf(radians) * m_forwardSpeed; m_positionZ += cosf(radians) * m_forwardSpeed; return; } void PositionClass::MoveBackward(bool keydown, bool sprintKeyDown) { float radians; int speedMod = 1 + sprintKeyDown; // Update the backward speed movement based on the frame time and whether the user is holding the key down or not. if (keydown) { m_backwardSpeed += m_frameTime * 0.001f * speedMod; if (m_backwardSpeed > (m_frameTime * 0.03f * speedMod)) { m_backwardSpeed = m_frameTime * 0.03f * speedMod; } } else { m_backwardSpeed -= m_frameTime * 0.0007f; if (m_backwardSpeed < 0.0f) { m_backwardSpeed = 0.0f; } } // Convert degrees to radians. radians = m_rotationY * 0.0174532925f; // Update the position. m_positionX -= sinf(radians) * m_backwardSpeed; m_positionZ -= cosf(radians) * m_backwardSpeed; return; } void PositionClass::MoveLeft(bool keydown, bool sprintKeyDown) { float radians; int speedMod = 1 + sprintKeyDown; // Update the backward speed movement based on the frame time and whether the user is holding the key down or not. if (keydown) { m_leftSpeed += m_frameTime * 0.001f * speedMod; if (m_leftSpeed > (m_frameTime * 0.03f * speedMod)) { m_leftSpeed = m_frameTime * 0.03f * speedMod; } } else { m_leftSpeed -= m_frameTime * 0.0007f; if (m_leftSpeed < 0.0f) { m_leftSpeed = 0.0f; } } // Convert degrees to radians. radians = m_rotationY * 0.0174532925f; // Update the position. m_positionX -= cosf(radians) * m_leftSpeed; m_positionZ += sinf(radians) * m_leftSpeed; return; } void PositionClass::MoveRight(bool keydown, bool sprintKeyDown) { float radians; int speedMod = 1 + sprintKeyDown; // Update the backward speed movement based on the frame time and whether the user is holding the key down or not. if (keydown) { m_rightSpeed += m_frameTime * 0.001f * speedMod; if (m_rightSpeed > (m_frameTime * 0.03f * speedMod)) { m_rightSpeed = m_frameTime * 0.03f * speedMod; } } else { m_rightSpeed -= m_frameTime * 0.0007f; if (m_rightSpeed < 0.0f) { m_rightSpeed = 0.0f; } } // Convert degrees to radians. radians = m_rotationY * 0.0174532925f; // Update the position. m_positionX += cosf(radians) * m_rightSpeed; m_positionZ -= sinf(radians) * m_rightSpeed; return; } void PositionClass::MoveUpward(bool keydown) { if (keydown) { m_upwardSpeed += m_frameTime * 0.003f; if (m_upwardSpeed > (m_frameTime * 0.03f)) { m_upwardSpeed = m_frameTime * 0.03f; } } else { m_upwardSpeed -= m_frameTime * 0.002f; if (m_upwardSpeed < 0.0f) { m_upwardSpeed = 0.0f; } } //update the height position. m_positionY += m_upwardSpeed; return; } void PositionClass::MoveDownward(bool keydown) { // Update the downward speed movement based on the frame time and whether the user is holding the key down or not. if (keydown) { m_downwardSpeed += m_frameTime * 0.003f; if (m_downwardSpeed > (m_frameTime * 0.03f)) { m_downwardSpeed = m_frameTime * 0.03f; } } else { m_downwardSpeed -= m_frameTime * 0.002f; if (m_downwardSpeed < 0.0f) { m_downwardSpeed = 0.0f; } } // Update the height position. m_positionY -= m_downwardSpeed; return; } void PositionClass::TurnLeft(bool keydown) { // Update the left turn speed movement based on the frame time and whether the user is holding the key down or not. if (keydown) { m_leftTurnSpeed += m_frameTime * 0.01f; if (m_leftTurnSpeed > (m_frameTime * 0.15f)) { m_leftTurnSpeed = m_frameTime * 0.15f; } } else { m_leftTurnSpeed -= m_frameTime * 0.005f; if (m_leftTurnSpeed < 0.0f) { m_leftTurnSpeed = 0.0f; } } // Update the rotation. m_rotationY -= m_leftTurnSpeed; // Keep the rotation in the 0 to 360 range. if (m_rotationY < 0.0f) { m_rotationY += 360.0f; } return; } void PositionClass::TurnRight(bool keydown) { // Update the right turn speed movement based on the frame time and whether the user is holding the key down or not. if (keydown) { m_rightTurnSpeed += m_frameTime * 0.01f; if (m_rightTurnSpeed > (m_frameTime * 0.15f)) { m_rightTurnSpeed = m_frameTime * 0.15f; } } else { m_rightTurnSpeed -= m_frameTime * 0.005f; if (m_rightTurnSpeed < 0.0f) { m_rightTurnSpeed = 0.0f; } } // Update the rotation. m_rotationY += m_rightTurnSpeed; // Keep the rotation in the 0 to 360 range. if (m_rotationY > 360.0f) { m_rotationY -= 360.0f; } return; } void PositionClass::LookUpward(bool keydown) { // Update the upward rotation speed movement based on the frame time and whether the user is holding the key down or not. if (keydown) { m_lookUpSpeed += m_frameTime * 0.01f; if (m_lookUpSpeed > (m_frameTime * 0.15f)) { m_lookUpSpeed = m_frameTime * 0.15f; } } else { m_lookUpSpeed -= m_frameTime * 0.005f; if (m_lookUpSpeed < 0.0f) { m_lookUpSpeed = 0.0f; } } // Update the rotation. m_rotationX -= m_lookUpSpeed; // Keep the rotation maximum 90 degrees. if (m_rotationX > 90.0f) { m_rotationX = 90.0f; } return; } void PositionClass::LookDownward(bool keydown) { // Update the downward rotation speed movement based on the frame time and whether the user is holding the key down or not. if (keydown) { m_lookDownSpeed += m_frameTime * 0.01f; if (m_lookDownSpeed > (m_frameTime * 0.15f)) { m_lookDownSpeed = m_frameTime * 0.15f; } } else { m_lookDownSpeed -= m_frameTime * 0.005f; if (m_lookDownSpeed < 0.0f) { m_lookDownSpeed = 0.0f; } } // Update the rotation. m_rotationX += m_lookDownSpeed; // Keep the rotation maximum 90 degrees. if (m_rotationX < -90.0f) { m_rotationX = -90.0f; } return; }
[ "U1661665@unimail.hud.ac.uk" ]
U1661665@unimail.hud.ac.uk
490c5a643af09e9ce4f29fa306b133b32cf93bde
fabdbc3cba422b1dfb8724de24f5b9e829463ed2
/source_def/ViewTrack.cxx
af86595a751a4ff96935baeafb3c65a62e95890b
[]
no_license
shimada-takuya/garfieldpp
a43c45a3e06fd39e5791a995e962753c6819abec
c7f99eea51d8a14e6ecaae0cf501d27117a01923
refs/heads/master
2020-12-12T02:07:59.659717
2020-01-15T07:49:33
2020-01-15T07:49:33
234,016,972
0
0
null
null
null
null
UTF-8
C++
false
false
3,369
cxx
#include <cstdio> #include <cstdlib> #include <iostream> #include <iomanip> #include <fstream> #include <string> #include <cmath> // ROOT #include <TApplication.h> #include <TCanvas.h> #include <TMath.h> #include <TH1.h> #include <TH2.h> #include <TFile.h> // Garifeld++ #include <MediumMagboltz.hh> #include <ComponentElmer.hh> #include <GarfieldConstants.hh> #include <Random.hh> #include <Sensor.hh> #include <AvalancheMicroscopic.hh> #include <AvalancheMC.hh> #include <ViewField.hh> #include <ViewFEMesh.hh> #include <Plotting.hh> using namespace Garfield; int main(int argc, char *argv[]){ TApplication *app = new TApplication("app", &argc, argv); const double lem_th = 0.04; // LEM thickness in cm const double lem_cpth = 0.0035; // Copper thickness const double lem_pitch = 0.07; // LEM pitch in cm const double axis_x = 0.1; const double axis_y = 0.1; const double axis_z = 0.25 + lem_th/2 + lem_cpth; // Set the electron start parameters. const double zi = lem_th/2 + lem_cpth + 0.1; double ri = (lem_pitch/2)*RndmUniform(); double thetai = RndmUniform()*TwoPi; double xi = ri*cos(thetai); double yi = ri*sin(thetai); MediumMagboltz *gas = new MediumMagboltz(); gas->SetComposition("ar", 90., "c2h6", 10.); gas->SetTemperature(293.15); // [K] gas->SetPressure(760.); // [Torr] gas->EnablePenningTransfer(0.31, 0, "ar"); gas->SetMaxElectronEnergy(200.); // [eV] gas->EnableDrift(); gas->Initialise(true); gas->LoadIonMobility("/usr/local/Garfield/Data/IonMobility_Ar+_Ar.txt"); ComponentElmer *elm = new ComponentElmer("gemcell/mesh.header", "gemcell/mesh.elements", "gemcell/mesh.nodes", "gemcell/dielectrics.dat", "gemcell/gemcell.result", "cm"); elm->EnablePeriodicityX(); elm->EnableMirrorPeriodicityY(); elm->SetMedium(0, gas); Sensor *sensor = new Sensor(); sensor->AddComponent(elm); sensor->SetArea(-axis_x,-axis_y,-axis_z,axis_x,axis_y,axis_z); ViewDrift *viewDrift = new ViewDrift(); viewDrift->SetArea(-axis_x, -axis_y, -axis_z, axis_x, axis_y, axis_z); TCanvas *ViewWin = new TCanvas("ViewWin", "", 0, 0, 800, 800); ViewWin->SetFillColor(0); ViewWin->SetFrameFillColor(0); ViewFEMesh *vFE = new ViewFEMesh(); vFE->SetCanvas(ViewWin); vFE->SetComponent(elm); vFE->SetPlane(0, 1, 0, 0, 0, 0); vFE->SetFillMesh(true); vFE->SetColor(1, kOrange); vFE->SetColor(2, kGreen); vFE->SetColor(3, kGreen); AvalancheMicroscopic *aval = new AvalancheMicroscopic(); aval->SetSensor(sensor); aval->EnablePlotting(viewDrift); AvalancheMC *ion = new AvalancheMC(); ion->SetSensor(sensor); ion->SetDistanceSteps(2.e-4); ion->EnablePlotting(viewDrift); aval->AvalancheElectron(xi, yi, zi, 0, 0, 0); Int_t nd = aval->GetNumberOfElectronEndpoints(); for(int i=0; i<nd; i++){ Int_t Stat; double x0, y0, z0, t0, e0; double x1, y1, z1, t1, e1; aval->GetElectronEndpoint(i, x0, y0, z0, t0, e0, x1, y1, z1, t1, e1, Stat); ion->DriftIon(x0, y0, z0, t0); } ViewWin->cd(); vFE->SetArea(-axis_x,-axis_z,0.,axis_x,axis_z,0.); vFE->EnableAxes(); vFE->SetViewDrift(viewDrift); vFE->SetXaxisTitle("[cm]"); vFE->SetYaxisTitle("[cm]"); vFE->Plot(); ViewWin->Update(); ViewWin->Print("track.png"); app->Run(); }
[ "shimada@stu.kobe-u.ac.jp" ]
shimada@stu.kobe-u.ac.jp
181f4ea1c7737981147de8070300e3a78df24c7c
d92acaaabf07ca21f83bd136ed3bbd741aea9cfe
/LuckyLeprechauns/Game/TrapNetwork.h
0eccd13f4dded3f0a559bba8c33fae843ad0b3c2
[]
no_license
sp-alex-osou/LuckyLeprechauns
54b4c64718769ba2c93a723f331ef160c8def7c5
c7bce0f14be1cc1cfd7ca4571cbb11c3819fc1e8
refs/heads/master
2016-09-05T13:46:54.134574
2013-08-26T10:46:39
2013-08-26T10:46:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
324
h
#pragma once #include "DrawableNetwork.h" #include "TrapManager.h" class TrapNetwork : public DrawableNetwork<TrapManager> { public: TrapNetwork(LLNetworkManager* manager, TrapManager* trapManager); void receive(const NetworkPacketAddTrap& packet); void receive(const NetworkPacketRemoveTrap& packet); };
[ "aosou@Alex-MBP.local" ]
aosou@Alex-MBP.local
58454aa505744d0c85ef4b55629df0563ea613ea
1f40abf77c33ebb9f276f34421ad98e198427186
/tools/output/stubs/lib/streflop/libm/flt-32/e_lgammaf_r_stub.cpp
6bcb8b55c1b08a59240ec3567745e84183dcd0d8
[]
no_license
fzn7/rts
ff0f1f17bc01fe247ea9e6b761738f390ece112e
b63d3f8a72329ace0058fa821f8dd9a2ece1300d
refs/heads/master
2021-09-04T14:09:26.159157
2018-01-19T09:25:56
2018-01-19T09:25:56
103,816,815
0
2
null
2018-05-22T10:37:40
2017-09-17T09:17:14
C++
UTF-8
C++
false
false
4,325
cpp
#include <iostream> /* See the import.pl script for potential modifications */ /* e_lgammaf_r.c -- Simple version of e_lgamma_r.c. * Conversion to Simple by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #if defined(LIBM_SCCS) && !defined(lint) static char rcsid[] = "$NetBSD: e_lgammaf_r.c,v 1.3f 1995/05/10 20:45:47 jtc Exp $"; #endif #include "SMath.h" #include "math_private.h" namespace streflop_libm { #ifdef __STDC__ static const Simple #else static Simple #endif two23 = 8.3886080000e+06f, /* 0x4b000000 */ half = 5.0000000000e-01f, /* 0x3f000000 */ one = 1.0000000000e+00f, /* 0x3f800000 */ pi = 3.1415927410e+00f, /* 0x40490fdb */ a0 = 7.7215664089e-02f, /* 0x3d9e233f */ a1 = 3.2246702909e-01f, /* 0x3ea51a66 */ a2 = 6.7352302372e-02f, /* 0x3d89f001 */ a3 = 2.0580807701e-02f, /* 0x3ca89915 */ a4 = 7.3855509982e-03f, /* 0x3bf2027e */ a5 = 2.8905137442e-03f, /* 0x3b3d6ec6 */ a6 = 1.1927076848e-03f, /* 0x3a9c54a1 */ a7 = 5.1006977446e-04f, /* 0x3a05b634 */ a8 = 2.2086278477e-04f, /* 0x39679767 */ a9 = 1.0801156895e-04f, /* 0x38e28445 */ a10 = 2.5214456400e-05f, /* 0x37d383a2 */ a11 = 4.4864096708e-05f, /* 0x383c2c75 */ tc = 1.4616321325e+00f, /* 0x3fbb16c3 */ tf = -1.2148628384e-01f, /* 0xbdf8cdcd */ /* tt = -(tail of tf) */ tt = 6.6971006518e-09f, /* 0x31e61c52 */ t0 = 4.8383611441e-01f, /* 0x3ef7b95e */ t1 = -1.4758771658e-01f, /* 0xbe17213c */ t2 = 6.4624942839e-02f, /* 0x3d845a15 */ t3 = -3.2788541168e-02f, /* 0xbd064d47 */ t4 = 1.7970675603e-02f, /* 0x3c93373d */ t5 = -1.0314224288e-02f, /* 0xbc28fcfe */ t6 = 6.1005386524e-03f, /* 0x3bc7e707 */ t7 = -3.6845202558e-03f, /* 0xbb7177fe */ t8 = 2.2596477065e-03f, /* 0x3b141699 */ t9 = -1.4034647029e-03f, /* 0xbab7f476 */ t10 = 8.8108185446e-04f, /* 0x3a66f867 */ t11 = -5.3859531181e-04f, /* 0xba0d3085 */ t12 = 3.1563205994e-04f, /* 0x39a57b6b */ t13 = -3.1275415677e-04f, /* 0xb9a3f927 */ t14 = 3.3552918467e-04f, /* 0x39afe9f7 */ u0 = -7.7215664089e-02f, /* 0xbd9e233f */ u1 = 6.3282704353e-01f, /* 0x3f2200f4 */ u2 = 1.4549225569e+00f, /* 0x3fba3ae7 */ u3 = 9.7771751881e-01f, /* 0x3f7a4bb2 */ u4 = 2.2896373272e-01f, /* 0x3e6a7578 */ u5 = 1.3381091878e-02f, /* 0x3c5b3c5e */ v1 = 2.4559779167e+00f, /* 0x401d2ebe */ v2 = 2.1284897327e+00f, /* 0x4008392d */ v3 = 7.6928514242e-01f, /* 0x3f44efdf */ v4 = 1.0422264785e-01f, /* 0x3dd572af */ v5 = 3.2170924824e-03f, /* 0x3b52d5db */ s0 = -7.7215664089e-02f, /* 0xbd9e233f */ s1 = 2.1498242021e-01f, /* 0x3e5c245a */ s2 = 3.2577878237e-01f, /* 0x3ea6cc7a */ s3 = 1.4635047317e-01f, /* 0x3e15dce6 */ s4 = 2.6642270386e-02f, /* 0x3cda40e4 */ s5 = 1.8402845599e-03f, /* 0x3af135b4 */ s6 = 3.1947532989e-05f, /* 0x3805ff67 */ r1 = 1.3920053244e+00f, /* 0x3fb22d3b */ r2 = 7.2193557024e-01f, /* 0x3f38d0c5 */ r3 = 1.7193385959e-01f, /* 0x3e300f6e */ r4 = 1.8645919859e-02f, /* 0x3c98bf54 */ r5 = 7.7794247773e-04f, /* 0x3a4beed6 */ r6 = 7.3266842264e-06f, /* 0x36f5d7bd */ w0 = 4.1893854737e-01f, /* 0x3ed67f1d */ w1 = 8.3333335817e-02f, /* 0x3daaaaab */ w2 = -2.7777778450e-03f, /* 0xbb360b61 */ w3 = 7.9365057172e-04f, /* 0x3a500cfd */ w4 = -5.9518753551e-04f, /* 0xba1c065c */ w5 = 8.3633989561e-04f, /* 0x3a5b3dd2 */ w6 = -1.6309292987e-03f; /* 0xbad5c4e8 */ #ifdef __STDC__ static const Simple zero = 0.0000000000e+00f; #else static Simple zero = 0.0000000000e+00f; #endif #ifdef __STDC__ static Simple sin_pif(Simple x) #else static Simple sin_pif(x) Simple x; #endif { //stub method std::cout << _FUNCTION_ << std::endl; } #ifdef __STDC__ Simple __ieee754_lgammaf_r(Simple x, int* signgamp) #else Simple __ieee754_lgammaf_r(x, signgamp) Simple x; int* signgamp; #endif { //stub method std::cout << _FUNCTION_ << std::endl; } }
[ "plotnikov@teamidea.ru" ]
plotnikov@teamidea.ru
e541ba99d5b52f6e55950986ba8676dead386d2d
6970e4cc5e2cc11582ca09e85ec612766fc7c128
/src/builtins/builtins-definitions.h
f4af77fec9f0382d761ea143a2f1d18398270250
[ "BSD-3-Clause", "Apache-2.0", "bzip2-1.0.6", "SunPro" ]
permissive
rockjsq/v8
ee6e15e70dd8d351662fb2851965dec93d9ea47d
dd13d1668530c20a2354e8608704497340739256
refs/heads/master
2023-03-08T11:52:09.964847
2019-11-07T13:34:20
2020-02-08T06:48:08
220,241,346
0
0
NOASSERTION
2023-03-02T04:31:36
2019-11-07T13:17:53
C++
UTF-8
C++
false
false
99,609
h
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_BUILTINS_BUILTINS_DEFINITIONS_H_ #define V8_BUILTINS_BUILTINS_DEFINITIONS_H_ #include "builtins-generated/bytecodes-builtins-list.h" // include generated header #include "torque-generated/builtin-definitions-tq.h" namespace v8 { namespace internal { // CPP: Builtin in C++. Entered via BUILTIN_EXIT frame. // Args: name // TFJ: Builtin in Turbofan, with JS linkage (callable as Javascript function). // Args: name, arguments count, explicit argument names... // TFS: Builtin in Turbofan, with CodeStub linkage. // Args: name, explicit argument names... // TFC: Builtin in Turbofan, with CodeStub linkage and custom descriptor. // Args: name, interface descriptor // TFH: Handlers in Turbofan, with CodeStub linkage. // Args: name, interface descriptor // BCH: Bytecode Handlers, with bytecode dispatch linkage. // Args: name, OperandScale, Bytecode // ASM: Builtin in platform-dependent assembly. // Args: name, interface descriptor // TODO(jgruber): Remove DummyDescriptor once all ASM builtins have been // properly associated with their descriptor. #define BUILTIN_LIST_BASE(CPP, TFJ, TFC, TFS, TFH, ASM) \ /* GC write barrirer */ \ TFC(RecordWrite, RecordWrite) \ TFC(EphemeronKeyBarrier, EphemeronKeyBarrier) \ \ /* Adaptor for CPP builtin */ \ TFC(AdaptorWithBuiltinExitFrame, CppBuiltinAdaptor) \ \ /* Calls */ \ ASM(ArgumentsAdaptorTrampoline, ArgumentsAdaptor) \ /* ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList) */ \ ASM(CallFunction_ReceiverIsNullOrUndefined, CallTrampoline) \ ASM(CallFunction_ReceiverIsNotNullOrUndefined, CallTrampoline) \ ASM(CallFunction_ReceiverIsAny, CallTrampoline) \ /* ES6 section 9.4.1.1 [[Call]] ( thisArgument, argumentsList) */ \ ASM(CallBoundFunction, CallTrampoline) \ /* ES6 section 7.3.12 Call(F, V, [argumentsList]) */ \ ASM(Call_ReceiverIsNullOrUndefined, CallTrampoline) \ ASM(Call_ReceiverIsNotNullOrUndefined, CallTrampoline) \ ASM(Call_ReceiverIsAny, CallTrampoline) \ \ /* ES6 section 9.5.12[[Call]] ( thisArgument, argumentsList ) */ \ TFC(CallProxy, CallTrampoline) \ ASM(CallVarargs, CallVarargs) \ TFC(CallWithSpread, CallWithSpread) \ TFC(CallWithArrayLike, CallWithArrayLike) \ ASM(CallForwardVarargs, CallForwardVarargs) \ ASM(CallFunctionForwardVarargs, CallForwardVarargs) \ /* Call an API callback via a {FunctionTemplateInfo}, doing appropriate */ \ /* access and compatible receiver checks. */ \ TFC(CallFunctionTemplate_CheckAccess, CallFunctionTemplate) \ TFC(CallFunctionTemplate_CheckCompatibleReceiver, CallFunctionTemplate) \ TFC(CallFunctionTemplate_CheckAccessAndCompatibleReceiver, \ CallFunctionTemplate) \ \ /* Construct */ \ /* ES6 section 9.2.2 [[Construct]] ( argumentsList, newTarget) */ \ ASM(ConstructFunction, JSTrampoline) \ /* ES6 section 9.4.1.2 [[Construct]] (argumentsList, newTarget) */ \ ASM(ConstructBoundFunction, JSTrampoline) \ ASM(ConstructedNonConstructable, JSTrampoline) \ /* ES6 section 7.3.13 Construct (F, [argumentsList], [newTarget]) */ \ ASM(Construct, JSTrampoline) \ ASM(ConstructVarargs, ConstructVarargs) \ TFC(ConstructWithSpread, ConstructWithSpread) \ TFC(ConstructWithArrayLike, ConstructWithArrayLike) \ ASM(ConstructForwardVarargs, ConstructForwardVarargs) \ ASM(ConstructFunctionForwardVarargs, ConstructForwardVarargs) \ ASM(JSConstructStubGeneric, Dummy) \ ASM(JSBuiltinsConstructStub, Dummy) \ TFC(FastNewObject, FastNewObject) \ TFS(FastNewClosure, kSharedFunctionInfo, kFeedbackCell) \ TFC(FastNewFunctionContextEval, FastNewFunctionContext) \ TFC(FastNewFunctionContextFunction, FastNewFunctionContext) \ TFS(CreateRegExpLiteral, kFeedbackVector, kSlot, kPattern, kFlags) \ TFS(CreateEmptyArrayLiteral, kFeedbackVector, kSlot) \ TFS(CreateShallowArrayLiteral, kFeedbackVector, kSlot, kConstantElements) \ TFS(CreateShallowObjectLiteral, kFeedbackVector, kSlot, \ kObjectBoilerplateDescription, kFlags) \ /* ES6 section 9.5.14 [[Construct]] ( argumentsList, newTarget) */ \ TFC(ConstructProxy, JSTrampoline) \ \ /* Apply and entries */ \ ASM(JSEntry, Dummy) \ ASM(JSConstructEntry, Dummy) \ ASM(JSRunMicrotasksEntry, RunMicrotasksEntry) \ ASM(JSEntryTrampoline, JSTrampoline) \ ASM(JSConstructEntryTrampoline, JSTrampoline) \ ASM(ResumeGeneratorTrampoline, ResumeGenerator) \ \ /* String helpers */ \ TFC(StringCodePointAt, StringAt) \ TFC(StringFromCodePointAt, StringAtAsString) \ TFC(StringEqual, Compare) \ TFC(StringGreaterThan, Compare) \ TFC(StringGreaterThanOrEqual, Compare) \ TFS(StringIndexOf, kReceiver, kSearchString, kPosition) \ TFC(StringLessThan, Compare) \ TFC(StringLessThanOrEqual, Compare) \ TFC(StringSubstring, StringSubstring) \ \ /* OrderedHashTable helpers */ \ TFS(OrderedHashTableHealIndex, kTable, kIndex) \ \ /* Interpreter */ \ ASM(InterpreterEntryTrampoline, JSTrampoline) \ ASM(InterpreterPushArgsThenCall, InterpreterPushArgsThenCall) \ ASM(InterpreterPushUndefinedAndArgsThenCall, InterpreterPushArgsThenCall) \ ASM(InterpreterPushArgsThenCallWithFinalSpread, InterpreterPushArgsThenCall) \ ASM(InterpreterPushArgsThenConstruct, InterpreterPushArgsThenConstruct) \ ASM(InterpreterPushArgsThenConstructArrayFunction, \ InterpreterPushArgsThenConstruct) \ ASM(InterpreterPushArgsThenConstructWithFinalSpread, \ InterpreterPushArgsThenConstruct) \ ASM(InterpreterEnterBytecodeAdvance, Dummy) \ ASM(InterpreterEnterBytecodeDispatch, Dummy) \ ASM(InterpreterOnStackReplacement, ContextOnly) \ \ /* Code life-cycle */ \ TFC(CompileLazy, JSTrampoline) \ TFC(CompileLazyDeoptimizedCode, JSTrampoline) \ ASM(InstantiateAsmJs, Dummy) \ ASM(NotifyDeoptimized, Dummy) \ \ /* Trampolines called when returning from a deoptimization that expects */ \ /* to continue in a JavaScript builtin to finish the functionality of a */ \ /* an TF-inlined version of builtin that has side-effects. */ \ /* */ \ /* The trampolines work as follows: */ \ /* 1. Trampoline restores input register values that */ \ /* the builtin expects from a BuiltinContinuationFrame. */ \ /* 2. Trampoline tears down BuiltinContinuationFrame. */ \ /* 3. Trampoline jumps to the builtin's address. */ \ /* 4. Builtin executes as if invoked by the frame above it. */ \ /* 5. When the builtin returns, execution resumes normally in the */ \ /* calling frame, processing any return result from the JavaScript */ \ /* builtin as if it had called the builtin directly. */ \ /* */ \ /* There are two variants of the stub that differ in their handling of a */ \ /* value returned by the next frame deeper on the stack. For LAZY deopts, */ \ /* the return value (e.g. rax on x64) is explicitly passed as an extra */ \ /* stack parameter to the JavaScript builtin by the "WithResult" */ \ /* trampoline variant. The plain variant is used in EAGER deopt contexts */ \ /* and has no such special handling. */ \ ASM(ContinueToCodeStubBuiltin, Dummy) \ ASM(ContinueToCodeStubBuiltinWithResult, Dummy) \ ASM(ContinueToJavaScriptBuiltin, Dummy) \ ASM(ContinueToJavaScriptBuiltinWithResult, Dummy) \ \ /* API callback handling */ \ ASM(CallApiCallback, ApiCallback) \ ASM(CallApiGetter, ApiGetter) \ CPP(HandleApiCall) \ CPP(HandleApiCallAsFunction) \ CPP(HandleApiCallAsConstructor) \ \ /* Adapters for Turbofan into runtime */ \ TFC(AllocateInYoungGeneration, Allocate) \ TFC(AllocateRegularInYoungGeneration, Allocate) \ TFC(AllocateInOldGeneration, Allocate) \ TFC(AllocateRegularInOldGeneration, Allocate) \ \ /* TurboFan support builtins */ \ TFS(CopyFastSmiOrObjectElements, kObject) \ TFC(GrowFastDoubleElements, GrowArrayElements) \ TFC(GrowFastSmiOrObjectElements, GrowArrayElements) \ TFC(NewArgumentsElements, NewArgumentsElements) \ \ /* Debugger */ \ TFJ(DebugBreakTrampoline, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ ASM(FrameDropperTrampoline, FrameDropperTrampoline) \ ASM(HandleDebuggerStatement, ContextOnly) \ \ /* Type conversions */ \ TFC(ToObject, TypeConversion) \ TFC(ToBoolean, TypeConversion) \ TFC(OrdinaryToPrimitive_Number, TypeConversion) \ TFC(OrdinaryToPrimitive_String, TypeConversion) \ TFC(NonPrimitiveToPrimitive_Default, TypeConversion) \ TFC(NonPrimitiveToPrimitive_Number, TypeConversion) \ TFC(NonPrimitiveToPrimitive_String, TypeConversion) \ TFC(StringToNumber, TypeConversion) \ TFC(ToName, TypeConversion) \ TFC(NonNumberToNumber, TypeConversion) \ TFC(NonNumberToNumeric, TypeConversion) \ TFC(ToNumber, TypeConversion) \ TFC(ToNumberConvertBigInt, TypeConversion) \ TFC(ToNumeric, TypeConversion) \ TFC(NumberToString, TypeConversion) \ TFC(ToInteger, TypeConversion) \ TFC(ToInteger_TruncateMinusZero, TypeConversion) \ TFC(ToLength, TypeConversion) \ TFC(Typeof, Typeof) \ TFC(GetSuperConstructor, Typeof) \ TFC(BigIntToI64, BigIntToI64) \ TFC(BigIntToI32Pair, BigIntToI32Pair) \ TFC(I64ToBigInt, I64ToBigInt) \ TFC(I32PairToBigInt, I32PairToBigInt) \ \ /* Type conversions continuations */ \ TFC(ToBooleanLazyDeoptContinuation, TypeConversionStackParameter) \ \ /* Handlers */ \ TFH(KeyedLoadIC_PolymorphicName, LoadWithVector) \ TFH(KeyedLoadIC_Slow, LoadWithVector) \ TFH(KeyedStoreIC_Megamorphic, Store) \ TFH(KeyedStoreIC_Slow, StoreWithVector) \ TFH(LoadGlobalIC_NoFeedback, LoadGlobalNoFeedback) \ TFH(LoadIC_FunctionPrototype, LoadWithVector) \ TFH(LoadIC_StringLength, LoadWithVector) \ TFH(LoadIC_StringWrapperLength, LoadWithVector) \ TFH(LoadIC_NoFeedback, LoadNoFeedback) \ TFH(StoreGlobalIC_Slow, StoreWithVector) \ TFH(StoreIC_NoFeedback, Store) \ TFH(StoreInArrayLiteralIC_Slow, StoreWithVector) \ TFH(KeyedLoadIC_SloppyArguments, LoadWithVector) \ TFH(LoadIndexedInterceptorIC, LoadWithVector) \ TFH(KeyedStoreIC_SloppyArguments_Standard, StoreWithVector) \ TFH(KeyedStoreIC_SloppyArguments_GrowNoTransitionHandleCOW, StoreWithVector) \ TFH(KeyedStoreIC_SloppyArguments_NoTransitionIgnoreOOB, StoreWithVector) \ TFH(KeyedStoreIC_SloppyArguments_NoTransitionHandleCOW, StoreWithVector) \ TFH(StoreInArrayLiteralIC_Slow_Standard, StoreWithVector) \ TFH(StoreFastElementIC_Standard, StoreWithVector) \ TFH(StoreFastElementIC_GrowNoTransitionHandleCOW, StoreWithVector) \ TFH(StoreFastElementIC_NoTransitionIgnoreOOB, StoreWithVector) \ TFH(StoreFastElementIC_NoTransitionHandleCOW, StoreWithVector) \ TFH(StoreInArrayLiteralIC_Slow_GrowNoTransitionHandleCOW, StoreWithVector) \ TFH(StoreInArrayLiteralIC_Slow_NoTransitionIgnoreOOB, StoreWithVector) \ TFH(StoreInArrayLiteralIC_Slow_NoTransitionHandleCOW, StoreWithVector) \ TFH(KeyedStoreIC_Slow_Standard, StoreWithVector) \ TFH(KeyedStoreIC_Slow_GrowNoTransitionHandleCOW, StoreWithVector) \ TFH(KeyedStoreIC_Slow_NoTransitionIgnoreOOB, StoreWithVector) \ TFH(KeyedStoreIC_Slow_NoTransitionHandleCOW, StoreWithVector) \ TFH(ElementsTransitionAndStore_Standard, StoreTransition) \ TFH(ElementsTransitionAndStore_GrowNoTransitionHandleCOW, StoreTransition) \ TFH(ElementsTransitionAndStore_NoTransitionIgnoreOOB, StoreTransition) \ TFH(ElementsTransitionAndStore_NoTransitionHandleCOW, StoreTransition) \ TFH(KeyedHasIC_PolymorphicName, LoadWithVector) \ TFH(KeyedHasIC_SloppyArguments, LoadWithVector) \ TFH(HasIndexedInterceptorIC, LoadWithVector) \ TFH(HasIC_Slow, LoadWithVector) \ \ /* Microtask helpers */ \ TFS(EnqueueMicrotask, kMicrotask) \ ASM(RunMicrotasksTrampoline, RunMicrotasksEntry) \ TFC(RunMicrotasks, RunMicrotasks) \ \ /* Object property helpers */ \ TFS(HasProperty, kObject, kKey) \ TFS(DeleteProperty, kObject, kKey, kLanguageMode) \ /* ES #sec-copydataproperties */ \ TFS(CopyDataProperties, kTarget, kSource) \ TFS(SetDataProperties, kTarget, kSource) \ \ /* Abort */ \ TFC(Abort, Abort) \ TFC(AbortCSAAssert, Abort) \ \ /* Built-in functions for Javascript */ \ /* Special internal builtins */ \ CPP(EmptyFunction) \ CPP(Illegal) \ CPP(StrictPoisonPillThrower) \ CPP(UnsupportedThrower) \ TFJ(ReturnReceiver, 0, kReceiver) \ \ /* Array */ \ TFC(ArrayConstructor, JSTrampoline) \ TFC(ArrayConstructorImpl, ArrayConstructor) \ TFC(ArrayNoArgumentConstructor_PackedSmi_DontOverride, \ ArrayNoArgumentConstructor) \ TFC(ArrayNoArgumentConstructor_HoleySmi_DontOverride, \ ArrayNoArgumentConstructor) \ TFC(ArrayNoArgumentConstructor_PackedSmi_DisableAllocationSites, \ ArrayNoArgumentConstructor) \ TFC(ArrayNoArgumentConstructor_HoleySmi_DisableAllocationSites, \ ArrayNoArgumentConstructor) \ TFC(ArrayNoArgumentConstructor_Packed_DisableAllocationSites, \ ArrayNoArgumentConstructor) \ TFC(ArrayNoArgumentConstructor_Holey_DisableAllocationSites, \ ArrayNoArgumentConstructor) \ TFC(ArrayNoArgumentConstructor_PackedDouble_DisableAllocationSites, \ ArrayNoArgumentConstructor) \ TFC(ArrayNoArgumentConstructor_HoleyDouble_DisableAllocationSites, \ ArrayNoArgumentConstructor) \ TFC(ArraySingleArgumentConstructor_PackedSmi_DontOverride, \ ArraySingleArgumentConstructor) \ TFC(ArraySingleArgumentConstructor_HoleySmi_DontOverride, \ ArraySingleArgumentConstructor) \ TFC(ArraySingleArgumentConstructor_PackedSmi_DisableAllocationSites, \ ArraySingleArgumentConstructor) \ TFC(ArraySingleArgumentConstructor_HoleySmi_DisableAllocationSites, \ ArraySingleArgumentConstructor) \ TFC(ArraySingleArgumentConstructor_Packed_DisableAllocationSites, \ ArraySingleArgumentConstructor) \ TFC(ArraySingleArgumentConstructor_Holey_DisableAllocationSites, \ ArraySingleArgumentConstructor) \ TFC(ArraySingleArgumentConstructor_PackedDouble_DisableAllocationSites, \ ArraySingleArgumentConstructor) \ TFC(ArraySingleArgumentConstructor_HoleyDouble_DisableAllocationSites, \ ArraySingleArgumentConstructor) \ TFC(ArrayNArgumentsConstructor, ArrayNArgumentsConstructor) \ CPP(ArrayConcat) \ /* ES6 #sec-array.prototype.fill */ \ CPP(ArrayPrototypeFill) \ /* ES6 #sec-array.from */ \ TFJ(ArrayFrom, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES7 #sec-array.prototype.includes */ \ TFS(ArrayIncludesSmiOrObject, kElements, kSearchElement, kLength, \ kFromIndex) \ TFS(ArrayIncludesPackedDoubles, kElements, kSearchElement, kLength, \ kFromIndex) \ TFS(ArrayIncludesHoleyDoubles, kElements, kSearchElement, kLength, \ kFromIndex) \ TFJ(ArrayIncludes, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-array.prototype.indexof */ \ TFS(ArrayIndexOfSmiOrObject, kElements, kSearchElement, kLength, kFromIndex) \ TFS(ArrayIndexOfPackedDoubles, kElements, kSearchElement, kLength, \ kFromIndex) \ TFS(ArrayIndexOfHoleyDoubles, kElements, kSearchElement, kLength, \ kFromIndex) \ TFJ(ArrayIndexOf, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-array.prototype.pop */ \ CPP(ArrayPop) \ TFJ(ArrayPrototypePop, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-array.prototype.push */ \ CPP(ArrayPush) \ TFJ(ArrayPrototypePush, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-array.prototype.shift */ \ CPP(ArrayShift) \ /* ES6 #sec-array.prototype.unshift */ \ CPP(ArrayUnshift) \ /* Support for Array.from and other array-copying idioms */ \ TFS(CloneFastJSArray, kSource) \ TFS(CloneFastJSArrayFillingHoles, kSource) \ TFS(ExtractFastJSArray, kSource, kBegin, kCount) \ /* ES6 #sec-array.prototype.entries */ \ TFJ(ArrayPrototypeEntries, 0, kReceiver) \ /* ES6 #sec-array.prototype.keys */ \ TFJ(ArrayPrototypeKeys, 0, kReceiver) \ /* ES6 #sec-array.prototype.values */ \ TFJ(ArrayPrototypeValues, 0, kReceiver) \ /* ES6 #sec-%arrayiteratorprototype%.next */ \ TFJ(ArrayIteratorPrototypeNext, 0, kReceiver) \ /* https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray */ \ TFS(FlattenIntoArray, kTarget, kSource, kSourceLength, kStart, kDepth) \ TFS(FlatMapIntoArray, kTarget, kSource, kSourceLength, kStart, kDepth, \ kMapperFunction, kThisArg) \ /* https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flat */ \ TFJ(ArrayPrototypeFlat, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap */ \ TFJ(ArrayPrototypeFlatMap, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ \ /* ArrayBuffer */ \ /* ES #sec-arraybuffer-constructor */ \ CPP(ArrayBufferConstructor) \ CPP(ArrayBufferConstructor_DoNotInitialize) \ CPP(ArrayBufferPrototypeGetByteLength) \ CPP(ArrayBufferIsView) \ CPP(ArrayBufferPrototypeSlice) \ \ /* AsyncFunction */ \ TFS(AsyncFunctionEnter, kClosure, kReceiver) \ TFS(AsyncFunctionReject, kAsyncFunctionObject, kReason, kCanSuspend) \ TFS(AsyncFunctionResolve, kAsyncFunctionObject, kValue, kCanSuspend) \ TFC(AsyncFunctionLazyDeoptContinuation, AsyncFunctionStackParameter) \ TFS(AsyncFunctionAwaitCaught, kAsyncFunctionObject, kValue) \ TFS(AsyncFunctionAwaitUncaught, kAsyncFunctionObject, kValue) \ TFJ(AsyncFunctionAwaitRejectClosure, 1, kReceiver, kSentError) \ TFJ(AsyncFunctionAwaitResolveClosure, 1, kReceiver, kSentValue) \ \ /* BigInt */ \ CPP(BigIntConstructor) \ CPP(BigIntAsUintN) \ CPP(BigIntAsIntN) \ CPP(BigIntPrototypeToLocaleString) \ CPP(BigIntPrototypeToString) \ CPP(BigIntPrototypeValueOf) \ \ /* CallSite */ \ CPP(CallSitePrototypeGetColumnNumber) \ CPP(CallSitePrototypeGetEvalOrigin) \ CPP(CallSitePrototypeGetFileName) \ CPP(CallSitePrototypeGetFunction) \ CPP(CallSitePrototypeGetFunctionName) \ CPP(CallSitePrototypeGetLineNumber) \ CPP(CallSitePrototypeGetMethodName) \ CPP(CallSitePrototypeGetPosition) \ CPP(CallSitePrototypeGetPromiseIndex) \ CPP(CallSitePrototypeGetScriptNameOrSourceURL) \ CPP(CallSitePrototypeGetThis) \ CPP(CallSitePrototypeGetTypeName) \ CPP(CallSitePrototypeIsAsync) \ CPP(CallSitePrototypeIsConstructor) \ CPP(CallSitePrototypeIsEval) \ CPP(CallSitePrototypeIsNative) \ CPP(CallSitePrototypeIsPromiseAll) \ CPP(CallSitePrototypeIsToplevel) \ CPP(CallSitePrototypeToString) \ \ /* Console */ \ CPP(ConsoleDebug) \ CPP(ConsoleError) \ CPP(ConsoleInfo) \ CPP(ConsoleLog) \ CPP(ConsoleWarn) \ CPP(ConsoleDir) \ CPP(ConsoleDirXml) \ CPP(ConsoleTable) \ CPP(ConsoleTrace) \ CPP(ConsoleGroup) \ CPP(ConsoleGroupCollapsed) \ CPP(ConsoleGroupEnd) \ CPP(ConsoleClear) \ CPP(ConsoleCount) \ CPP(ConsoleCountReset) \ CPP(ConsoleAssert) \ CPP(ConsoleProfile) \ CPP(ConsoleProfileEnd) \ CPP(ConsoleTime) \ CPP(ConsoleTimeLog) \ CPP(ConsoleTimeEnd) \ CPP(ConsoleTimeStamp) \ CPP(ConsoleContext) \ \ /* DataView */ \ /* ES #sec-dataview-constructor */ \ CPP(DataViewConstructor) \ \ /* Date */ \ /* ES #sec-date-constructor */ \ CPP(DateConstructor) \ /* ES6 #sec-date.prototype.getdate */ \ TFJ(DatePrototypeGetDate, 0, kReceiver) \ /* ES6 #sec-date.prototype.getday */ \ TFJ(DatePrototypeGetDay, 0, kReceiver) \ /* ES6 #sec-date.prototype.getfullyear */ \ TFJ(DatePrototypeGetFullYear, 0, kReceiver) \ /* ES6 #sec-date.prototype.gethours */ \ TFJ(DatePrototypeGetHours, 0, kReceiver) \ /* ES6 #sec-date.prototype.getmilliseconds */ \ TFJ(DatePrototypeGetMilliseconds, 0, kReceiver) \ /* ES6 #sec-date.prototype.getminutes */ \ TFJ(DatePrototypeGetMinutes, 0, kReceiver) \ /* ES6 #sec-date.prototype.getmonth */ \ TFJ(DatePrototypeGetMonth, 0, kReceiver) \ /* ES6 #sec-date.prototype.getseconds */ \ TFJ(DatePrototypeGetSeconds, 0, kReceiver) \ /* ES6 #sec-date.prototype.gettime */ \ TFJ(DatePrototypeGetTime, 0, kReceiver) \ /* ES6 #sec-date.prototype.gettimezoneoffset */ \ TFJ(DatePrototypeGetTimezoneOffset, 0, kReceiver) \ /* ES6 #sec-date.prototype.getutcdate */ \ TFJ(DatePrototypeGetUTCDate, 0, kReceiver) \ /* ES6 #sec-date.prototype.getutcday */ \ TFJ(DatePrototypeGetUTCDay, 0, kReceiver) \ /* ES6 #sec-date.prototype.getutcfullyear */ \ TFJ(DatePrototypeGetUTCFullYear, 0, kReceiver) \ /* ES6 #sec-date.prototype.getutchours */ \ TFJ(DatePrototypeGetUTCHours, 0, kReceiver) \ /* ES6 #sec-date.prototype.getutcmilliseconds */ \ TFJ(DatePrototypeGetUTCMilliseconds, 0, kReceiver) \ /* ES6 #sec-date.prototype.getutcminutes */ \ TFJ(DatePrototypeGetUTCMinutes, 0, kReceiver) \ /* ES6 #sec-date.prototype.getutcmonth */ \ TFJ(DatePrototypeGetUTCMonth, 0, kReceiver) \ /* ES6 #sec-date.prototype.getutcseconds */ \ TFJ(DatePrototypeGetUTCSeconds, 0, kReceiver) \ /* ES6 #sec-date.prototype.valueof */ \ TFJ(DatePrototypeValueOf, 0, kReceiver) \ /* ES6 #sec-date.prototype-@@toprimitive */ \ TFJ(DatePrototypeToPrimitive, 1, kReceiver, kHint) \ CPP(DatePrototypeGetYear) \ CPP(DatePrototypeSetYear) \ CPP(DateNow) \ CPP(DateParse) \ CPP(DatePrototypeSetDate) \ CPP(DatePrototypeSetFullYear) \ CPP(DatePrototypeSetHours) \ CPP(DatePrototypeSetMilliseconds) \ CPP(DatePrototypeSetMinutes) \ CPP(DatePrototypeSetMonth) \ CPP(DatePrototypeSetSeconds) \ CPP(DatePrototypeSetTime) \ CPP(DatePrototypeSetUTCDate) \ CPP(DatePrototypeSetUTCFullYear) \ CPP(DatePrototypeSetUTCHours) \ CPP(DatePrototypeSetUTCMilliseconds) \ CPP(DatePrototypeSetUTCMinutes) \ CPP(DatePrototypeSetUTCMonth) \ CPP(DatePrototypeSetUTCSeconds) \ CPP(DatePrototypeToDateString) \ CPP(DatePrototypeToISOString) \ CPP(DatePrototypeToUTCString) \ CPP(DatePrototypeToString) \ CPP(DatePrototypeToTimeString) \ CPP(DatePrototypeToJson) \ CPP(DateUTC) \ \ /* Error */ \ CPP(ErrorConstructor) \ CPP(ErrorCaptureStackTrace) \ CPP(ErrorPrototypeToString) \ CPP(MakeError) \ CPP(MakeRangeError) \ CPP(MakeSyntaxError) \ CPP(MakeTypeError) \ CPP(MakeURIError) \ \ /* Function */ \ CPP(FunctionConstructor) \ ASM(FunctionPrototypeApply, JSTrampoline) \ CPP(FunctionPrototypeBind) \ /* ES6 #sec-function.prototype.bind */ \ TFJ(FastFunctionPrototypeBind, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ ASM(FunctionPrototypeCall, JSTrampoline) \ /* ES6 #sec-function.prototype-@@hasinstance */ \ TFJ(FunctionPrototypeHasInstance, 1, kReceiver, kV) \ /* ES6 #sec-function.prototype.tostring */ \ CPP(FunctionPrototypeToString) \ \ /* Belongs to Objects but is a dependency of GeneratorPrototypeResume */ \ TFS(CreateIterResultObject, kValue, kDone) \ \ /* Generator and Async */ \ TFS(CreateGeneratorObject, kClosure, kReceiver) \ CPP(GeneratorFunctionConstructor) \ /* ES6 #sec-generator.prototype.next */ \ TFJ(GeneratorPrototypeNext, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-generator.prototype.return */ \ TFJ(GeneratorPrototypeReturn, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-generator.prototype.throw */ \ TFJ(GeneratorPrototypeThrow, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ CPP(AsyncFunctionConstructor) \ \ /* Iterator Protocol */ \ TFC(GetIteratorWithFeedbackLazyDeoptContinuation, GetIteratorStackParameter) \ \ /* Global object */ \ CPP(GlobalDecodeURI) \ CPP(GlobalDecodeURIComponent) \ CPP(GlobalEncodeURI) \ CPP(GlobalEncodeURIComponent) \ CPP(GlobalEscape) \ CPP(GlobalUnescape) \ CPP(GlobalEval) \ /* ES6 #sec-isfinite-number */ \ TFJ(GlobalIsFinite, 1, kReceiver, kNumber) \ /* ES6 #sec-isnan-number */ \ TFJ(GlobalIsNaN, 1, kReceiver, kNumber) \ \ /* JSON */ \ CPP(JsonParse) \ CPP(JsonStringify) \ \ /* ICs */ \ TFH(LoadIC, LoadWithVector) \ TFH(LoadIC_Megamorphic, LoadWithVector) \ TFH(LoadIC_Noninlined, LoadWithVector) \ TFH(LoadICTrampoline, Load) \ TFH(LoadICTrampoline_Megamorphic, Load) \ TFH(KeyedLoadIC, LoadWithVector) \ TFH(KeyedLoadIC_Megamorphic, LoadWithVector) \ TFH(KeyedLoadICTrampoline, Load) \ TFH(KeyedLoadICTrampoline_Megamorphic, Load) \ TFH(StoreGlobalIC, StoreGlobalWithVector) \ TFH(StoreGlobalICTrampoline, StoreGlobal) \ TFH(StoreIC, StoreWithVector) \ TFH(StoreICTrampoline, Store) \ TFH(KeyedStoreIC, StoreWithVector) \ TFH(KeyedStoreICTrampoline, Store) \ TFH(StoreInArrayLiteralIC, StoreWithVector) \ TFH(LoadGlobalIC, LoadGlobalWithVector) \ TFH(LoadGlobalICInsideTypeof, LoadGlobalWithVector) \ TFH(LoadGlobalICTrampoline, LoadGlobal) \ TFH(LoadGlobalICInsideTypeofTrampoline, LoadGlobal) \ TFH(CloneObjectIC, CloneObjectWithVector) \ TFH(CloneObjectIC_Slow, CloneObjectWithVector) \ TFH(KeyedHasIC, LoadWithVector) \ TFH(KeyedHasIC_Megamorphic, LoadWithVector) \ \ /* IterableToList */ \ /* ES #sec-iterabletolist */ \ TFS(IterableToList, kIterable, kIteratorFn) \ TFS(IterableToListWithSymbolLookup, kIterable) \ TFS(IterableToListMayPreserveHoles, kIterable, kIteratorFn) \ TFS(IterableToFixedArrayForWasm, kIterable, kExpectedLength) \ \ /* #sec-createstringlistfromiterable */ \ TFS(StringListFromIterable, kIterable) \ \ /* Map */ \ TFS(FindOrderedHashMapEntry, kTable, kKey) \ TFJ(MapConstructor, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFJ(MapPrototypeSet, 2, kReceiver, kKey, kValue) \ TFJ(MapPrototypeDelete, 1, kReceiver, kKey) \ TFJ(MapPrototypeGet, 1, kReceiver, kKey) \ TFJ(MapPrototypeHas, 1, kReceiver, kKey) \ CPP(MapPrototypeClear) \ /* ES #sec-map.prototype.entries */ \ TFJ(MapPrototypeEntries, 0, kReceiver) \ /* ES #sec-get-map.prototype.size */ \ TFJ(MapPrototypeGetSize, 0, kReceiver) \ /* ES #sec-map.prototype.forEach */ \ TFJ(MapPrototypeForEach, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES #sec-map.prototype.keys */ \ TFJ(MapPrototypeKeys, 0, kReceiver) \ /* ES #sec-map.prototype.values */ \ TFJ(MapPrototypeValues, 0, kReceiver) \ /* ES #sec-%mapiteratorprototype%.next */ \ TFJ(MapIteratorPrototypeNext, 0, kReceiver) \ TFS(MapIteratorToList, kSource) \ \ /* Math */ \ /* ES6 #sec-math.abs */ \ TFJ(MathAbs, 1, kReceiver, kX) \ /* ES6 #sec-math.ceil */ \ TFJ(MathCeil, 1, kReceiver, kX) \ /* ES6 #sec-math.floor */ \ TFJ(MathFloor, 1, kReceiver, kX) \ /* ES6 #sec-math.imul */ \ TFJ(MathImul, 2, kReceiver, kX, kY) \ /* ES6 #sec-math.max */ \ TFJ(MathMax, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-math.min */ \ TFJ(MathMin, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-math.pow */ \ TFJ(MathPow, 2, kReceiver, kBase, kExponent) \ /* ES6 #sec-math.random */ \ TFJ(MathRandom, 0, kReceiver) \ /* ES6 #sec-math.round */ \ TFJ(MathRound, 1, kReceiver, kX) \ /* ES6 #sec-math.trunc */ \ TFJ(MathTrunc, 1, kReceiver, kX) \ \ /* Number */ \ TFC(AllocateHeapNumber, AllocateHeapNumber) \ /* ES #sec-number-constructor */ \ TFJ(NumberConstructor, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-number.isfinite */ \ TFJ(NumberIsFinite, 1, kReceiver, kNumber) \ /* ES6 #sec-number.isinteger */ \ TFJ(NumberIsInteger, 1, kReceiver, kNumber) \ /* ES6 #sec-number.isnan */ \ TFJ(NumberIsNaN, 1, kReceiver, kNumber) \ /* ES6 #sec-number.issafeinteger */ \ TFJ(NumberIsSafeInteger, 1, kReceiver, kNumber) \ /* ES6 #sec-number.parsefloat */ \ TFJ(NumberParseFloat, 1, kReceiver, kString) \ /* ES6 #sec-number.parseint */ \ TFJ(NumberParseInt, 2, kReceiver, kString, kRadix) \ TFS(ParseInt, kString, kRadix) \ CPP(NumberPrototypeToExponential) \ CPP(NumberPrototypeToFixed) \ CPP(NumberPrototypeToLocaleString) \ CPP(NumberPrototypeToPrecision) \ /* ES6 #sec-number.prototype.valueof */ \ TFJ(NumberPrototypeValueOf, 0, kReceiver) \ TFC(Add, BinaryOp) \ TFC(Subtract, BinaryOp) \ TFC(Multiply, BinaryOp) \ TFC(Divide, BinaryOp) \ TFC(Modulus, BinaryOp) \ TFC(Exponentiate, BinaryOp) \ TFC(BitwiseAnd, BinaryOp) \ TFC(BitwiseOr, BinaryOp) \ TFC(BitwiseXor, BinaryOp) \ TFC(ShiftLeft, BinaryOp) \ TFC(ShiftRight, BinaryOp) \ TFC(ShiftRightLogical, BinaryOp) \ TFC(LessThan, Compare) \ TFC(LessThanOrEqual, Compare) \ TFC(GreaterThan, Compare) \ TFC(GreaterThanOrEqual, Compare) \ TFC(Equal, Compare) \ TFC(SameValue, Compare) \ TFC(SameValueNumbersOnly, Compare) \ TFC(StrictEqual, Compare) \ TFS(BitwiseNot, kValue) \ TFS(Decrement, kValue) \ TFS(Increment, kValue) \ TFS(Negate, kValue) \ \ /* Object */ \ /* ES #sec-object-constructor */ \ TFJ(ObjectConstructor, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFJ(ObjectAssign, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES #sec-object.create */ \ TFJ(ObjectCreate, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFS(CreateObjectWithoutProperties, kPrototypeArg) \ CPP(ObjectDefineGetter) \ CPP(ObjectDefineProperties) \ CPP(ObjectDefineProperty) \ CPP(ObjectDefineSetter) \ TFJ(ObjectEntries, 1, kReceiver, kObject) \ CPP(ObjectFreeze) \ TFJ(ObjectGetOwnPropertyDescriptor, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ CPP(ObjectGetOwnPropertyDescriptors) \ TFJ(ObjectGetOwnPropertyNames, 1, kReceiver, kObject) \ CPP(ObjectGetOwnPropertySymbols) \ TFJ(ObjectIs, 2, kReceiver, kLeft, kRight) \ CPP(ObjectIsFrozen) \ CPP(ObjectIsSealed) \ TFJ(ObjectKeys, 1, kReceiver, kObject) \ CPP(ObjectLookupGetter) \ CPP(ObjectLookupSetter) \ /* ES6 #sec-object.prototype.tostring */ \ TFJ(ObjectPrototypeToString, 0, kReceiver) \ /* ES6 #sec-object.prototype.valueof */ \ TFJ(ObjectPrototypeValueOf, 0, kReceiver) \ /* ES6 #sec-object.prototype.hasownproperty */ \ TFJ(ObjectPrototypeHasOwnProperty, 1, kReceiver, kKey) \ TFJ(ObjectPrototypeIsPrototypeOf, 1, kReceiver, kValue) \ CPP(ObjectPrototypePropertyIsEnumerable) \ CPP(ObjectPrototypeGetProto) \ CPP(ObjectPrototypeSetProto) \ /* ES #sec-object.prototype.tolocalestring */ \ TFJ(ObjectPrototypeToLocaleString, 0, kReceiver) \ CPP(ObjectSeal) \ TFS(ObjectToString, kReceiver) \ TFJ(ObjectValues, 1, kReceiver, kObject) \ \ /* instanceof */ \ TFC(OrdinaryHasInstance, Compare) \ TFC(InstanceOf, Compare) \ \ /* for-in */ \ TFS(ForInEnumerate, kReceiver) \ TFS(ForInFilter, kKey, kObject) \ \ /* Promise */ \ /* ES #sec-promise-resolve-functions */ \ /* Starting at step 6 of "Promise Resolve Functions" */ \ TFS(ResolvePromise, kPromise, kResolution) \ /* ES #sec-promise-reject-functions */ \ TFJ(PromiseCapabilityDefaultReject, 1, kReceiver, kReason) \ /* ES #sec-promise-resolve-functions */ \ TFJ(PromiseCapabilityDefaultResolve, 1, kReceiver, kResolution) \ /* ES6 #sec-getcapabilitiesexecutor-functions */ \ TFJ(PromiseGetCapabilitiesExecutor, 2, kReceiver, kResolve, kReject) \ TFJ(PromiseConstructorLazyDeoptContinuation, 4, kReceiver, kPromise, \ kReject, kException, kResult) \ /* ES6 #sec-promise-executor */ \ TFJ(PromiseConstructor, 1, kReceiver, kExecutor) \ CPP(IsPromise) \ /* ES #sec-promise.prototype.then */ \ TFJ(PromisePrototypeThen, 2, kReceiver, kOnFulfilled, kOnRejected) \ /* ES #sec-performpromisethen */ \ TFS(PerformPromiseThen, kPromise, kOnFulfilled, kOnRejected, kResultPromise) \ /* ES #sec-promise.prototype.catch */ \ TFJ(PromisePrototypeCatch, 1, kReceiver, kOnRejected) \ /* ES #sec-promisereactionjob */ \ TFS(PromiseRejectReactionJob, kReason, kHandler, kPromiseOrCapability) \ TFS(PromiseFulfillReactionJob, kValue, kHandler, kPromiseOrCapability) \ /* ES #sec-promiseresolvethenablejob */ \ TFS(PromiseResolveThenableJob, kPromiseToResolve, kThenable, kThen) \ /* ES #sec-promise.resolve */ \ TFJ(PromiseResolveTrampoline, 1, kReceiver, kValue) \ /* ES #sec-promise-resolve */ \ TFS(PromiseResolve, kConstructor, kValue) \ /* ES #sec-promise.reject */ \ TFJ(PromiseReject, 1, kReceiver, kReason) \ TFJ(PromisePrototypeFinally, 1, kReceiver, kOnFinally) \ TFJ(PromiseThenFinally, 1, kReceiver, kValue) \ TFJ(PromiseCatchFinally, 1, kReceiver, kReason) \ TFJ(PromiseValueThunkFinally, 0, kReceiver) \ TFJ(PromiseThrowerFinally, 0, kReceiver) \ /* ES #sec-promise.all */ \ TFJ(PromiseAll, 1, kReceiver, kIterable) \ TFJ(PromiseAllResolveElementClosure, 1, kReceiver, kValue) \ /* ES #sec-promise.race */ \ TFJ(PromiseRace, 1, kReceiver, kIterable) \ /* ES #sec-promise.allsettled */ \ TFJ(PromiseAllSettled, 1, kReceiver, kIterable) \ TFJ(PromiseAllSettledResolveElementClosure, 1, kReceiver, kValue) \ TFJ(PromiseAllSettledRejectElementClosure, 1, kReceiver, kValue) \ \ /* Reflect */ \ ASM(ReflectApply, JSTrampoline) \ ASM(ReflectConstruct, JSTrampoline) \ CPP(ReflectDefineProperty) \ CPP(ReflectGetOwnPropertyDescriptor) \ CPP(ReflectOwnKeys) \ CPP(ReflectSet) \ \ /* RegExp */ \ CPP(RegExpCapture1Getter) \ CPP(RegExpCapture2Getter) \ CPP(RegExpCapture3Getter) \ CPP(RegExpCapture4Getter) \ CPP(RegExpCapture5Getter) \ CPP(RegExpCapture6Getter) \ CPP(RegExpCapture7Getter) \ CPP(RegExpCapture8Getter) \ CPP(RegExpCapture9Getter) \ /* ES #sec-regexp-pattern-flags */ \ TFJ(RegExpConstructor, 2, kReceiver, kPattern, kFlags) \ CPP(RegExpInputGetter) \ CPP(RegExpInputSetter) \ CPP(RegExpLastMatchGetter) \ CPP(RegExpLastParenGetter) \ CPP(RegExpLeftContextGetter) \ /* ES #sec-regexp.prototype.compile */ \ TFJ(RegExpPrototypeCompile, 2, kReceiver, kPattern, kFlags) \ CPP(RegExpPrototypeToString) \ CPP(RegExpRightContextGetter) \ \ /* RegExp helpers */ \ TFS(RegExpExecAtom, kRegExp, kString, kLastIndex, kMatchInfo) \ TFS(RegExpExecInternal, kRegExp, kString, kLastIndex, kMatchInfo) \ ASM(RegExpInterpreterTrampoline, CCall) \ \ /* Set */ \ TFJ(SetConstructor, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFJ(SetPrototypeHas, 1, kReceiver, kKey) \ TFJ(SetPrototypeAdd, 1, kReceiver, kKey) \ TFJ(SetPrototypeDelete, 1, kReceiver, kKey) \ CPP(SetPrototypeClear) \ /* ES #sec-set.prototype.entries */ \ TFJ(SetPrototypeEntries, 0, kReceiver) \ /* ES #sec-get-set.prototype.size */ \ TFJ(SetPrototypeGetSize, 0, kReceiver) \ /* ES #sec-set.prototype.foreach */ \ TFJ(SetPrototypeForEach, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES #sec-set.prototype.values */ \ TFJ(SetPrototypeValues, 0, kReceiver) \ /* ES #sec-%setiteratorprototype%.next */ \ TFJ(SetIteratorPrototypeNext, 0, kReceiver) \ TFS(SetOrSetIteratorToList, kSource) \ \ /* SharedArrayBuffer */ \ CPP(SharedArrayBufferPrototypeGetByteLength) \ CPP(SharedArrayBufferPrototypeSlice) \ TFJ(AtomicsLoad, 2, kReceiver, kArray, kIndex) \ TFJ(AtomicsStore, 3, kReceiver, kArray, kIndex, kValue) \ TFJ(AtomicsExchange, 3, kReceiver, kArray, kIndex, kValue) \ TFJ(AtomicsCompareExchange, 4, kReceiver, kArray, kIndex, kOldValue, \ kNewValue) \ TFJ(AtomicsAdd, 3, kReceiver, kArray, kIndex, kValue) \ TFJ(AtomicsSub, 3, kReceiver, kArray, kIndex, kValue) \ TFJ(AtomicsAnd, 3, kReceiver, kArray, kIndex, kValue) \ TFJ(AtomicsOr, 3, kReceiver, kArray, kIndex, kValue) \ TFJ(AtomicsXor, 3, kReceiver, kArray, kIndex, kValue) \ CPP(AtomicsNotify) \ CPP(AtomicsIsLockFree) \ CPP(AtomicsWait) \ CPP(AtomicsWake) \ \ /* String */ \ /* ES #sec-string.fromcodepoint */ \ CPP(StringFromCodePoint) \ /* ES6 #sec-string.fromcharcode */ \ TFJ(StringFromCharCode, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-string.prototype.includes */ \ TFJ(StringPrototypeIncludes, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-string.prototype.indexof */ \ TFJ(StringPrototypeIndexOf, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-string.prototype.lastindexof */ \ CPP(StringPrototypeLastIndexOf) \ /* ES6 #sec-string.prototype.match */ \ TFJ(StringPrototypeMatch, 1, kReceiver, kRegexp) \ /* ES #sec-string.prototype.matchAll */ \ TFJ(StringPrototypeMatchAll, 1, kReceiver, kRegexp) \ /* ES6 #sec-string.prototype.localecompare */ \ CPP(StringPrototypeLocaleCompare) \ /* ES6 #sec-string.prototype.replace */ \ TFJ(StringPrototypeReplace, 2, kReceiver, kSearch, kReplace) \ /* ES6 #sec-string.prototype.search */ \ TFJ(StringPrototypeSearch, 1, kReceiver, kRegexp) \ /* ES6 #sec-string.prototype.split */ \ TFJ(StringPrototypeSplit, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFJ(StringPrototypeTrim, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFJ(StringPrototypeTrimEnd, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFJ(StringPrototypeTrimStart, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ES6 #sec-string.raw */ \ CPP(StringRaw) \ \ /* Symbol */ \ /* ES #sec-symbol-constructor */ \ CPP(SymbolConstructor) \ /* ES6 #sec-symbol.for */ \ CPP(SymbolFor) \ /* ES6 #sec-symbol.keyfor */ \ CPP(SymbolKeyFor) \ \ /* TypedArray */ \ /* ES #sec-typedarray-constructors */ \ TFJ(TypedArrayBaseConstructor, 0, kReceiver) \ TFJ(GenericLazyDeoptContinuation, 1, kReceiver, kResult) \ TFJ(TypedArrayConstructor, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ CPP(TypedArrayPrototypeBuffer) \ /* ES6 #sec-get-%typedarray%.prototype.bytelength */ \ TFJ(TypedArrayPrototypeByteLength, 0, kReceiver) \ /* ES6 #sec-get-%typedarray%.prototype.byteoffset */ \ TFJ(TypedArrayPrototypeByteOffset, 0, kReceiver) \ /* ES6 #sec-get-%typedarray%.prototype.length */ \ TFJ(TypedArrayPrototypeLength, 0, kReceiver) \ /* ES6 #sec-%typedarray%.prototype.entries */ \ TFJ(TypedArrayPrototypeEntries, 0, kReceiver) \ /* ES6 #sec-%typedarray%.prototype.keys */ \ TFJ(TypedArrayPrototypeKeys, 0, kReceiver) \ /* ES6 #sec-%typedarray%.prototype.values */ \ TFJ(TypedArrayPrototypeValues, 0, kReceiver) \ /* ES6 #sec-%typedarray%.prototype.copywithin */ \ CPP(TypedArrayPrototypeCopyWithin) \ /* ES6 #sec-%typedarray%.prototype.fill */ \ CPP(TypedArrayPrototypeFill) \ /* ES7 #sec-%typedarray%.prototype.includes */ \ CPP(TypedArrayPrototypeIncludes) \ /* ES6 #sec-%typedarray%.prototype.indexof */ \ CPP(TypedArrayPrototypeIndexOf) \ /* ES6 #sec-%typedarray%.prototype.lastindexof */ \ CPP(TypedArrayPrototypeLastIndexOf) \ /* ES6 #sec-%typedarray%.prototype.reverse */ \ CPP(TypedArrayPrototypeReverse) \ /* ES6 #sec-get-%typedarray%.prototype-@@tostringtag */ \ TFJ(TypedArrayPrototypeToStringTag, 0, kReceiver) \ /* ES6 %TypedArray%.prototype.map */ \ TFJ(TypedArrayPrototypeMap, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ \ /* Wasm */ \ ASM(WasmCompileLazy, Dummy) \ TFC(WasmAtomicNotify, WasmAtomicNotify) \ TFC(WasmI32AtomicWait, WasmI32AtomicWait) \ TFC(WasmI64AtomicWait, WasmI64AtomicWait) \ TFC(WasmMemoryGrow, WasmMemoryGrow) \ TFC(WasmTableGet, WasmTableGet) \ TFC(WasmTableSet, WasmTableSet) \ TFC(WasmStackGuard, NoContext) \ TFC(WasmStackOverflow, NoContext) \ TFC(WasmThrow, WasmThrow) \ TFC(WasmRethrow, WasmThrow) \ TFS(ThrowWasmTrapUnreachable) \ TFS(ThrowWasmTrapMemOutOfBounds) \ TFS(ThrowWasmTrapUnalignedAccess) \ TFS(ThrowWasmTrapDivByZero) \ TFS(ThrowWasmTrapDivUnrepresentable) \ TFS(ThrowWasmTrapRemByZero) \ TFS(ThrowWasmTrapFloatUnrepresentable) \ TFS(ThrowWasmTrapFuncInvalid) \ TFS(ThrowWasmTrapFuncSigMismatch) \ TFS(ThrowWasmTrapDataSegmentDropped) \ TFS(ThrowWasmTrapElemSegmentDropped) \ TFS(ThrowWasmTrapTableOutOfBounds) \ \ /* WeakMap */ \ TFJ(WeakMapConstructor, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFS(WeakMapLookupHashIndex, kTable, kKey) \ TFJ(WeakMapGet, 1, kReceiver, kKey) \ TFJ(WeakMapPrototypeHas, 1, kReceiver, kKey) \ TFJ(WeakMapPrototypeSet, 2, kReceiver, kKey, kValue) \ TFJ(WeakMapPrototypeDelete, 1, kReceiver, kKey) \ \ /* WeakSet */ \ TFJ(WeakSetConstructor, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ TFJ(WeakSetPrototypeHas, 1, kReceiver, kKey) \ TFJ(WeakSetPrototypeAdd, 1, kReceiver, kValue) \ TFJ(WeakSetPrototypeDelete, 1, kReceiver, kValue) \ \ /* WeakSet / WeakMap Helpers */ \ TFS(WeakCollectionDelete, kCollection, kKey) \ TFS(WeakCollectionSet, kCollection, kKey, kValue) \ \ /* AsyncGenerator */ \ \ TFS(AsyncGeneratorResolve, kGenerator, kValue, kDone) \ TFS(AsyncGeneratorReject, kGenerator, kValue) \ TFS(AsyncGeneratorYield, kGenerator, kValue, kIsCaught) \ TFS(AsyncGeneratorReturn, kGenerator, kValue, kIsCaught) \ TFS(AsyncGeneratorResumeNext, kGenerator) \ \ /* AsyncGeneratorFunction( p1, p2, ... pn, body ) */ \ /* proposal-async-iteration/#sec-asyncgeneratorfunction-constructor */ \ CPP(AsyncGeneratorFunctionConstructor) \ /* AsyncGenerator.prototype.next ( value ) */ \ /* proposal-async-iteration/#sec-asyncgenerator-prototype-next */ \ TFJ(AsyncGeneratorPrototypeNext, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* AsyncGenerator.prototype.return ( value ) */ \ /* proposal-async-iteration/#sec-asyncgenerator-prototype-return */ \ TFJ(AsyncGeneratorPrototypeReturn, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* AsyncGenerator.prototype.throw ( exception ) */ \ /* proposal-async-iteration/#sec-asyncgenerator-prototype-throw */ \ TFJ(AsyncGeneratorPrototypeThrow, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ \ /* Await (proposal-async-iteration/#await), with resume behaviour */ \ /* specific to Async Generators. Internal / Not exposed to JS code. */ \ TFS(AsyncGeneratorAwaitCaught, kAsyncGeneratorObject, kValue) \ TFS(AsyncGeneratorAwaitUncaught, kAsyncGeneratorObject, kValue) \ TFJ(AsyncGeneratorAwaitResolveClosure, 1, kReceiver, kValue) \ TFJ(AsyncGeneratorAwaitRejectClosure, 1, kReceiver, kValue) \ TFJ(AsyncGeneratorYieldResolveClosure, 1, kReceiver, kValue) \ TFJ(AsyncGeneratorReturnClosedResolveClosure, 1, kReceiver, kValue) \ TFJ(AsyncGeneratorReturnClosedRejectClosure, 1, kReceiver, kValue) \ TFJ(AsyncGeneratorReturnResolveClosure, 1, kReceiver, kValue) \ \ /* Async-from-Sync Iterator */ \ \ /* %AsyncFromSyncIteratorPrototype% */ \ /* See tc39.github.io/proposal-async-iteration/ */ \ /* #sec-%asyncfromsynciteratorprototype%-object) */ \ TFJ(AsyncFromSyncIteratorPrototypeNext, 1, kReceiver, kValue) \ /* #sec-%asyncfromsynciteratorprototype%.throw */ \ TFJ(AsyncFromSyncIteratorPrototypeThrow, 1, kReceiver, kReason) \ /* #sec-%asyncfromsynciteratorprototype%.return */ \ TFJ(AsyncFromSyncIteratorPrototypeReturn, 1, kReceiver, kValue) \ /* #sec-async-iterator-value-unwrap-functions */ \ TFJ(AsyncIteratorValueUnwrap, 1, kReceiver, kValue) \ \ /* CEntry */ \ ASM(CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit, Dummy) \ ASM(CEntry_Return1_DontSaveFPRegs_ArgvOnStack_BuiltinExit, Dummy) \ ASM(CEntry_Return1_DontSaveFPRegs_ArgvInRegister_NoBuiltinExit, Dummy) \ ASM(CEntry_Return1_SaveFPRegs_ArgvOnStack_NoBuiltinExit, Dummy) \ ASM(CEntry_Return1_SaveFPRegs_ArgvOnStack_BuiltinExit, Dummy) \ ASM(CEntry_Return2_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit, Dummy) \ ASM(CEntry_Return2_DontSaveFPRegs_ArgvOnStack_BuiltinExit, Dummy) \ ASM(CEntry_Return2_DontSaveFPRegs_ArgvInRegister_NoBuiltinExit, Dummy) \ ASM(CEntry_Return2_SaveFPRegs_ArgvOnStack_NoBuiltinExit, Dummy) \ ASM(CEntry_Return2_SaveFPRegs_ArgvOnStack_BuiltinExit, Dummy) \ ASM(DirectCEntry, Dummy) \ \ /* String helpers */ \ TFS(StringAdd_CheckNone, kLeft, kRight) \ TFS(SubString, kString, kFrom, kTo) \ \ /* Miscellaneous */ \ ASM(StackCheck, Dummy) \ ASM(DoubleToI, Dummy) \ TFC(GetProperty, GetProperty) \ TFS(GetPropertyWithReceiver, kObject, kKey, kReceiver, kOnNonExistent) \ TFS(SetProperty, kReceiver, kKey, kValue) \ TFS(SetPropertyInLiteral, kReceiver, kKey, kValue) \ ASM(MemCopyUint8Uint8, CCall) \ ASM(MemMove, CCall) \ \ /* Trace */ \ CPP(IsTraceCategoryEnabled) \ CPP(Trace) \ \ /* Weak refs */ \ CPP(FinalizationGroupCleanupIteratorNext) \ CPP(FinalizationGroupCleanupSome) \ CPP(FinalizationGroupConstructor) \ CPP(FinalizationGroupRegister) \ CPP(FinalizationGroupUnregister) \ CPP(WeakRefConstructor) \ CPP(WeakRefDeref) \ \ /* Async modules */ \ TFJ(AsyncModuleEvaluate, SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ \ /* CallAsyncModule* are spec anonymyous functions */ \ CPP(CallAsyncModuleFulfilled) \ CPP(CallAsyncModuleRejected) #ifdef V8_INTL_SUPPORT #define BUILTIN_LIST_INTL(CPP, TFJ, TFS) \ /* ecma402 #sec-intl.collator */ \ CPP(CollatorConstructor) \ /* ecma 402 #sec-collator-compare-functions*/ \ CPP(CollatorInternalCompare) \ /* ecma402 #sec-intl.collator.prototype.compare */ \ CPP(CollatorPrototypeCompare) \ /* ecma402 #sec-intl.collator.supportedlocalesof */ \ CPP(CollatorSupportedLocalesOf) \ CPP(CollatorPrototypeResolvedOptions) \ /* ecma402 #sup-date.prototype.tolocaledatestring */ \ CPP(DatePrototypeToLocaleDateString) \ /* ecma402 #sup-date.prototype.tolocalestring */ \ CPP(DatePrototypeToLocaleString) \ /* ecma402 #sup-date.prototype.tolocaletimestring */ \ CPP(DatePrototypeToLocaleTimeString) \ /* ecma402 #sec-intl.datetimeformat */ \ CPP(DateTimeFormatConstructor) \ /* ecma402 #sec-datetime-format-functions */ \ CPP(DateTimeFormatInternalFormat) \ /* ecma402 #sec-intl.datetimeformat.prototype.format */ \ CPP(DateTimeFormatPrototypeFormat) \ /* ecma402 #sec-intl.datetimeformat.prototype.formatrange */ \ CPP(DateTimeFormatPrototypeFormatRange) \ /* ecma402 #sec-intl.datetimeformat.prototype.formatrangetoparts */ \ CPP(DateTimeFormatPrototypeFormatRangeToParts) \ /* ecma402 #sec-intl.datetimeformat.prototype.formattoparts */ \ CPP(DateTimeFormatPrototypeFormatToParts) \ /* ecma402 #sec-intl.datetimeformat.prototype.resolvedoptions */ \ CPP(DateTimeFormatPrototypeResolvedOptions) \ /* ecma402 #sec-intl.datetimeformat.supportedlocalesof */ \ CPP(DateTimeFormatSupportedLocalesOf) \ /* ecma402 #sec-intl.getcanonicallocales */ \ CPP(IntlGetCanonicalLocales) \ /* ecma402 #sec-intl-listformat-constructor */ \ CPP(ListFormatConstructor) \ /* ecma402 #sec-intl-list-format.prototype.format */ \ TFJ(ListFormatPrototypeFormat, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ecma402 #sec-intl-list-format.prototype.formattoparts */ \ TFJ(ListFormatPrototypeFormatToParts, \ SharedFunctionInfo::kDontAdaptArgumentsSentinel) \ /* ecma402 #sec-intl.listformat.prototype.resolvedoptions */ \ CPP(ListFormatPrototypeResolvedOptions) \ /* ecma402 #sec-intl.ListFormat.supportedlocalesof */ \ CPP(ListFormatSupportedLocalesOf) \ /* ecma402 #sec-intl-locale-constructor */ \ CPP(LocaleConstructor) \ CPP(LocalePrototypeBaseName) \ CPP(LocalePrototypeCalendar) \ CPP(LocalePrototypeCaseFirst) \ CPP(LocalePrototypeCollation) \ CPP(LocalePrototypeHourCycle) \ CPP(LocalePrototypeLanguage) \ /* ecma402 #sec-Intl.Locale.prototype.maximize */ \ CPP(LocalePrototypeMaximize) \ /* ecma402 #sec-Intl.Locale.prototype.minimize */ \ CPP(LocalePrototypeMinimize) \ CPP(LocalePrototypeNumeric) \ CPP(LocalePrototypeNumberingSystem) \ CPP(LocalePrototypeRegion) \ CPP(LocalePrototypeScript) \ CPP(LocalePrototypeToString) \ /* ecma402 #sec-intl.numberformat */ \ CPP(NumberFormatConstructor) \ /* ecma402 #sec-number-format-functions */ \ CPP(NumberFormatInternalFormatNumber) \ /* ecma402 #sec-intl.numberformat.prototype.format */ \ CPP(NumberFormatPrototypeFormatNumber) \ /* ecma402 #sec-intl.numberformat.prototype.formattoparts */ \ CPP(NumberFormatPrototypeFormatToParts) \ /* ecma402 #sec-intl.numberformat.prototype.resolvedoptions */ \ CPP(NumberFormatPrototypeResolvedOptions) \ /* ecma402 #sec-intl.numberformat.supportedlocalesof */ \ CPP(NumberFormatSupportedLocalesOf) \ /* ecma402 #sec-intl.pluralrules */ \ CPP(PluralRulesConstructor) \ CPP(PluralRulesPrototypeResolvedOptions) \ /* ecma402 #sec-intl.pluralrules.prototype.select */ \ CPP(PluralRulesPrototypeSelect) \ /* ecma402 #sec-intl.pluralrules.supportedlocalesof */ \ CPP(PluralRulesSupportedLocalesOf) \ /* ecma402 #sec-intl.RelativeTimeFormat.constructor */ \ CPP(RelativeTimeFormatConstructor) \ /* ecma402 #sec-intl.RelativeTimeFormat.prototype.format */ \ CPP(RelativeTimeFormatPrototypeFormat) \ /* ecma402 #sec-intl.RelativeTimeFormat.prototype.formatToParts */ \ CPP(RelativeTimeFormatPrototypeFormatToParts) \ /* ecma402 #sec-intl.RelativeTimeFormat.prototype.resolvedOptions */ \ CPP(RelativeTimeFormatPrototypeResolvedOptions) \ /* ecma402 #sec-intl.RelativeTimeFormat.supportedlocalesof */ \ CPP(RelativeTimeFormatSupportedLocalesOf) \ /* ecma402 #sec-Intl.Segmenter */ \ CPP(SegmenterConstructor) \ /* ecma402 #sec-Intl.Segmenter.prototype.resolvedOptions */ \ CPP(SegmenterPrototypeResolvedOptions) \ /* ecma402 #sec-Intl.Segmenter.prototype.segment */ \ CPP(SegmenterPrototypeSegment) \ /* ecma402 #sec-Intl.Segmenter.supportedLocalesOf */ \ CPP(SegmenterSupportedLocalesOf) \ /* ecma402 #sec-segment-iterator-prototype-breakType */ \ CPP(SegmentIteratorPrototypeBreakType) \ /* ecma402 #sec-segment-iterator-prototype-following */ \ CPP(SegmentIteratorPrototypeFollowing) \ /* ecma402 #sec-segment-iterator-prototype-preceding */ \ CPP(SegmentIteratorPrototypePreceding) \ /* ecma402 #sec-segment-iterator-prototype-index */ \ CPP(SegmentIteratorPrototypeIndex) \ /* ecma402 #sec-segment-iterator-prototype-next */ \ CPP(SegmentIteratorPrototypeNext) \ /* ES #sec-string.prototype.normalize */ \ CPP(StringPrototypeNormalizeIntl) \ /* ecma402 #sup-string.prototype.tolocalelowercase */ \ CPP(StringPrototypeToLocaleLowerCase) \ /* ecma402 #sup-string.prototype.tolocaleuppercase */ \ CPP(StringPrototypeToLocaleUpperCase) \ /* ES #sec-string.prototype.tolowercase */ \ TFJ(StringPrototypeToLowerCaseIntl, 0, kReceiver) \ /* ES #sec-string.prototype.touppercase */ \ CPP(StringPrototypeToUpperCaseIntl) \ TFS(StringToLowerCaseIntl, kString) \ CPP(V8BreakIteratorConstructor) \ CPP(V8BreakIteratorInternalAdoptText) \ CPP(V8BreakIteratorInternalBreakType) \ CPP(V8BreakIteratorInternalCurrent) \ CPP(V8BreakIteratorInternalFirst) \ CPP(V8BreakIteratorInternalNext) \ CPP(V8BreakIteratorPrototypeAdoptText) \ CPP(V8BreakIteratorPrototypeBreakType) \ CPP(V8BreakIteratorPrototypeCurrent) \ CPP(V8BreakIteratorPrototypeFirst) \ CPP(V8BreakIteratorPrototypeNext) \ CPP(V8BreakIteratorPrototypeResolvedOptions) \ CPP(V8BreakIteratorSupportedLocalesOf) #else #define BUILTIN_LIST_INTL(CPP, TFJ, TFS) \ /* no-op fallback version */ \ CPP(StringPrototypeNormalize) \ /* same as toLowercase; fallback version */ \ CPP(StringPrototypeToLocaleLowerCase) \ /* same as toUppercase; fallback version */ \ CPP(StringPrototypeToLocaleUpperCase) \ /* (obsolete) Unibrow version */ \ CPP(StringPrototypeToLowerCase) \ /* (obsolete) Unibrow version */ \ CPP(StringPrototypeToUpperCase) #endif // V8_INTL_SUPPORT #define BUILTIN_LIST(CPP, TFJ, TFC, TFS, TFH, BCH, ASM) \ BUILTIN_LIST_BASE(CPP, TFJ, TFC, TFS, TFH, ASM) \ BUILTIN_LIST_FROM_TORQUE(CPP, TFJ, TFC, TFS, TFH, ASM) \ BUILTIN_LIST_INTL(CPP, TFJ, TFS) \ BUILTIN_LIST_BYTECODE_HANDLERS(BCH) // The exception thrown in the following builtins are caught // internally and result in a promise rejection. #define BUILTIN_PROMISE_REJECTION_PREDICTION_LIST(V) \ V(AsyncFromSyncIteratorPrototypeNext) \ V(AsyncFromSyncIteratorPrototypeReturn) \ V(AsyncFromSyncIteratorPrototypeThrow) \ V(AsyncFunctionAwaitCaught) \ V(AsyncFunctionAwaitUncaught) \ V(AsyncGeneratorResolve) \ V(AsyncGeneratorAwaitCaught) \ V(AsyncGeneratorAwaitUncaught) \ V(PromiseAll) \ V(PromiseConstructor) \ V(PromiseConstructorLazyDeoptContinuation) \ V(PromiseFulfillReactionJob) \ V(PromiseRace) \ V(ResolvePromise) // Convenience macro listing all wasm runtime stubs. Note that the first few // elements of the list coincide with {compiler::TrapId}, order matters. #define WASM_RUNTIME_STUB_LIST(V, VTRAP) \ FOREACH_WASM_TRAPREASON(VTRAP) \ V(WasmCompileLazy) \ V(WasmAtomicNotify) \ V(WasmI32AtomicWait) \ V(WasmI64AtomicWait) \ V(WasmMemoryGrow) \ V(WasmTableGet) \ V(WasmTableSet) \ V(WasmStackGuard) \ V(WasmStackOverflow) \ V(WasmThrow) \ V(WasmRethrow) \ V(AllocateHeapNumber) \ V(ArgumentsAdaptorTrampoline) \ V(BigIntToI32Pair) \ V(BigIntToI64) \ V(DoubleToI) \ V(I32PairToBigInt) \ V(I64ToBigInt) \ V(RecordWrite) \ V(ToNumber) // The exception thrown in the following builtins are caught internally and will // not be propagated further or re-thrown #define BUILTIN_EXCEPTION_CAUGHT_PREDICTION_LIST(V) V(PromiseRejectReactionJob) #define IGNORE_BUILTIN(...) #define BUILTIN_LIST_C(V) \ BUILTIN_LIST(V, IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN, \ IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN) #define BUILTIN_LIST_A(V) \ BUILTIN_LIST(IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN, \ IGNORE_BUILTIN, IGNORE_BUILTIN, V) #define BUILTIN_LIST_TFS(V) \ BUILTIN_LIST(IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN, V, \ IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN) #define BUILTIN_LIST_TFJ(V) \ BUILTIN_LIST(IGNORE_BUILTIN, V, IGNORE_BUILTIN, IGNORE_BUILTIN, \ IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN) #define BUILTIN_LIST_TFC(V) \ BUILTIN_LIST(IGNORE_BUILTIN, IGNORE_BUILTIN, V, IGNORE_BUILTIN, \ IGNORE_BUILTIN, IGNORE_BUILTIN, IGNORE_BUILTIN) } // namespace internal } // namespace v8 #endif // V8_BUILTINS_BUILTINS_DEFINITIONS_H_
[ "rockjsq@rockjsq.com" ]
rockjsq@rockjsq.com
4d67566abc9dee348cce45bb1a316e9af80907da
7835af31defec67bdbbdadba100476481424e197
/Section 5 - Performance Programming in C++/Lesson 2 - C++ Optimization Practice/code/DeadCode/matrix_addition_improved.cpp
8cf0f96c2b5ded6b0d6a48fe228bb9f537f9eb1f
[]
no_license
Fahadjudoon/Intro-self-driving-cars-udacity
71e907a856e734d2d46f07f2e8338408f6681530
f41c49c6a24468689e3d5900abc727cf932cc096
refs/heads/master
2023-03-17T01:04:25.782326
2020-08-30T12:05:03
2020-08-30T12:05:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,034
cpp
#include "matrix_addition_improved.h" using namespace std; vector < vector <int> > matrix_addition_improved (vector < vector <int> > matrixa, vector < vector <int> > matrixb) { // store the number of rows and columns in the matrices vector<int>::size_type rows_a = matrixa.size(); vector<int>::size_type rows_b = matrixb.size(); vector<int>::size_type cols_a = matrixa[0].size(); vector<int>::size_type cols_b = matrixb[0].size(); // default zero vector vector < vector <int> > matrix_sum(rows_a, vector<int>(cols_a)); // if both matrices have the same size, calculate and return the sum // otherwise check if the number of rows and columns are not equal and return a matrix of zero if (rows_a == rows_b && cols_a == cols_b) { for (unsigned int i = 0; i < rows_a; i++) { for (unsigned int j = 0; j < cols_b; j++) { matrix_sum[i][j] = matrixa[i][j] + matrixb[i][j]; } } return matrix_sum; } return matrix_sum; }
[ "ahmadchaiban@gmail.com" ]
ahmadchaiban@gmail.com
8a328cb8bdb112afc7ed8b6a8af5d0bed5f2cf65
5f63ca6a159239704001e9d53816c6f4139af8a9
/C++/uocsonguyentonhonhat.cpp
77ba5c9f8ccce8229c893965ec2881dc463c2ece
[]
no_license
buihuy17/Test
d9125a589941a39a830283c1dd0b6cb57f002a25
d9f8969a7855e5024d3a7e67a778e75bb697b5b4
refs/heads/main
2023-08-24T03:40:55.004530
2021-09-23T08:07:14
2021-09-23T08:07:14
409,489,273
0
0
null
null
null
null
UTF-8
C++
false
false
654
cpp
#define ll long long #include <bits/stdc++.h> using namespace std; int Nto(int x) { for (int i = 2; i <= sqrt(x); i++) { if (x % i == 0) return 0; } return 1; } void uoc(int a) { for (int b = 2; b <= a; b++) { if (a % b == 0) { if (Nto(b) == 1) { cout << b<<" "; break; } } } } main() { int t; cin >> t; while (t--) { int x; cin >> x; cout << 1 << " "; for (int i = 1; i <= x; i++) { uoc(i); } cout << endl; } return 0; }
[ "buivanhuy0971188942@gmail.com" ]
buivanhuy0971188942@gmail.com
ed66e1087573dc55407586b76825b7d10442a0d4
52b90cb799037a09e7e6f45f395f061b3084e495
/uniform_order/Main.cpp
fe380e60975fdd7a013dfb2dbabbd3ded1752f57
[ "MIT" ]
permissive
Kangz/GLDriverBugs
00d23ae9f6732d1975eccd1eca429e7a255a8a33
61f2e9c54a61d274817047301eb1a57b9934258b
refs/heads/master
2021-01-09T20:36:19.780987
2019-03-14T07:08:32
2019-03-14T13:21:46
61,653,662
0
1
MIT
2019-03-14T13:21:47
2016-06-21T17:32:10
C++
UTF-8
C++
false
false
2,024
cpp
#include "utils/GLFWApp.h" #include <string> #include "utils/Shader.h" class UniformOrder: public GLFWApp { public: void Init(GLFWwindow*) override { const std::string vs = R"(#version 450 in vec4 a_position; out vec4 vtxOut; struct structType{ uint n; uvec4 m; }; uniform structType u_var; void main(){ gl_Position = a_position; vtxOut = vec4(0.0, 0.0, 0.0, 1.0); vtxOut.r = u_var.n == 2u ? 1.0 : 0.0; vtxOut.g = u_var.m == uvec4(3u, 10u, 3u, 10u) ? 1.0 : 0.0; })"; const std::string fs = R"(#version 450 precision highp float; in vec4 vtxOut; layout(location = 0) out vec4 fragColor; void main(){ fragColor = vtxOut; })"; mProgram = CompileProgram(vs, fs); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); } void Frame() override { GLfloat vertices[] = { 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, }; glViewport(0, 0, 640, 480); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(mProgram); GLint location = glGetUniformLocation(mProgram, "u_var.n"); glUniform1ui(location, 2); GLint location2 = glGetUniformLocation(mProgram, "u_var.m"); glUniform4ui(location2, 3, 10, 3, 10); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vertices); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 3); } void Destroy() override { } GLuint mProgram; }; int main(int argc, const char** argv) { return GLFWApp::Run(new UniformOrder); }
[ "cwallez@google.com" ]
cwallez@google.com
65cda28972e2942fda64b1624702da715a04244a
e7fadeaa0be7f681722dccde42f92f1c6ee16a9b
/drds/src/model/DescribeDrdsInstanceResult.cc
1db0672469b94807879c11a69d41bd8cdb41f7a1
[ "Apache-2.0" ]
permissive
ELLIEbleu/aliyun-openapi-cpp-sdk
5a360447016d7fc32420907d0152e5aab43eeb9b
9b7dbef9c81c814a5fd519250b621d44339d3497
refs/heads/master
2020-04-10T21:08:54.368882
2018-12-06T02:28:48
2018-12-06T02:28:48
161,288,710
2
0
null
2018-12-11T06:38:23
2018-12-11T06:38:23
null
UTF-8
C++
false
false
3,113
cc
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/drds/model/DescribeDrdsInstanceResult.h> #include <json/json.h> using namespace AlibabaCloud::Drds; using namespace AlibabaCloud::Drds::Model; DescribeDrdsInstanceResult::DescribeDrdsInstanceResult() : ServiceResult() {} DescribeDrdsInstanceResult::DescribeDrdsInstanceResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDrdsInstanceResult::~DescribeDrdsInstanceResult() {} void DescribeDrdsInstanceResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; if(!dataNode["DrdsInstanceId"].isNull()) data_.drdsInstanceId = dataNode["DrdsInstanceId"].asString(); if(!dataNode["Type"].isNull()) data_.type = dataNode["Type"].asString(); if(!dataNode["RegionId"].isNull()) data_.regionId = dataNode["RegionId"].asString(); if(!dataNode["ZoneId"].isNull()) data_.zoneId = dataNode["ZoneId"].asString(); if(!dataNode["Description"].isNull()) data_.description = dataNode["Description"].asString(); if(!dataNode["NetworkType"].isNull()) data_.networkType = dataNode["NetworkType"].asString(); if(!dataNode["Status"].isNull()) data_.status = dataNode["Status"].asString(); if(!dataNode["CreateTime"].isNull()) data_.createTime = std::stol(dataNode["CreateTime"].asString()); if(!dataNode["Version"].isNull()) data_.version = std::stol(dataNode["Version"].asString()); if(!dataNode["Specification"].isNull()) data_.specification = dataNode["Specification"].asString(); if(!dataNode["VpcCloudInstanceId"].isNull()) data_.vpcCloudInstanceId = dataNode["VpcCloudInstanceId"].asString(); auto allVips = value["Vips"]["Vip"]; for (auto value : allVips) { Data::Vip vipObject; if(!value["IP"].isNull()) vipObject.iP = value["IP"].asString(); if(!value["Port"].isNull()) vipObject.port = value["Port"].asString(); if(!value["Type"].isNull()) vipObject.type = value["Type"].asString(); if(!value["VpcId"].isNull()) vipObject.vpcId = value["VpcId"].asString(); if(!value["VswitchId"].isNull()) vipObject.vswitchId = value["VswitchId"].asString(); data_.vips.push_back(vipObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } DescribeDrdsInstanceResult::Data DescribeDrdsInstanceResult::getData()const { return data_; } bool DescribeDrdsInstanceResult::getSuccess()const { return success_; }
[ "haowei.yao@alibaba-inc.com" ]
haowei.yao@alibaba-inc.com
da2f0806737422543a5a08374262e0d4cee48256
e0654961ba79338e82a0ba03360e97ead4465285
/include/argot/concepts/nothrow_assignable_when_contained.hpp
740511b90c2dd46b267ffa5283a9078dad2344f3
[ "BSL-1.0" ]
permissive
blockspacer/argot
68f0e2a56fb4686989b47d0ad0f6127167ea0a9a
97349baaf27659c9dc4d67cf8963b2e871eaedae
refs/heads/master
2022-11-25T02:57:08.808025
2020-08-04T21:15:00
2020-08-04T21:15:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,882
hpp
/*============================================================================== Copyright (c) 2018, 2019 Matt Calabrese Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef ARGOT_CONCEPTS_NOTHROW_ASSIGNABLE_WHEN_CONTAINED_HPP_ #define ARGOT_CONCEPTS_NOTHROW_ASSIGNABLE_WHEN_CONTAINED_HPP_ #include <argot/concepts/assignable_when_contained.hpp> #include <argot/concepts/detail/concepts_preprocessing_helpers.hpp> #include <argot/gen/explicit_concept.hpp> #ifndef ARGOT_GENERATE_PREPROCESSED_CONCEPTS #include <argot/contained.hpp> #include <argot/detail/declval.hpp> #include <argot/detail/detection.hpp> #include <type_traits> #endif // ARGOT_GENERATE_PREPROCESSED_CONCEPTS namespace argot { #define ARGOT_DETAIL_PREPROCESSED_CONCEPT_HEADER_NAME() \ s/nothrow_assignable_when_contained.h #ifdef ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER #include ARGOT_CONCEPTS_DETAIL_PREPROCESSED_HEADER #else #include <argot/concepts/detail/preprocess_header_begin.hpp> ARGOT_CONCEPTS_DETAIL_CREATE_LINE_DIRECTIVE( __LINE__ ) template< class T, class P > ARGOT_EXPLICIT_CONCEPT( NothrowAssignableWhenContained ) ( AssignableWhenContained< T, P > ); #include <argot/concepts/detail/preprocess_header_end.hpp> #endif // ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER template< class T, class P > struct make_concept_map < NothrowAssignableWhenContained< T, P > , call_detail::fast_enable_if_t < noexcept( ARGOT_DECLVAL( assign_contained_fn< T > const& ) ( ARGOT_DECLVAL( contained< T >& ), ARGOT_DECLVAL( P ) ) ) > > {}; } // namespace argot #endif // ARGOT_CONCEPTS_NOTHROW_ASSIGNABLE_WHEN_CONTAINED_HPP_
[ "matt@boost.org" ]
matt@boost.org
04ec1293c82c2f018b76d00feee54d68217f206c
c0488c02f0bd25f42050573ab886703dcf4205ec
/1145.cpp
cea712a23e0bb628260c508334f94294855a5b60
[]
no_license
RoeeXu/leetcode-cn
efb99f2b323fa32453ecdd0afb973df0392b9602
4c8d1a3692d25ffecc7dcf666c34e183210e245d
refs/heads/master
2021-08-02T22:30:29.004679
2021-07-27T18:17:39
2021-07-27T18:17:39
221,400,818
0
0
null
null
null
null
UTF-8
C++
false
false
1,039
cpp
/*************************************************** * Copyright (c) 2019 Roee Xu. All Rights Reserved **************************************************** * File: 1145.cpp * Author: roeexu * Date: 2019-12-20 11:07:26 * Brief: ****************************************************/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int N; bool over; bool btreeGameWinningMove(TreeNode* root, int n, int x) { if(!root) return false; over = false; N = n; dfs(root, x); return over; } int dfs(TreeNode* root, int x) { if(!root) return 0; if(over) return 0; int l = dfs(root->left, x), r = dfs(root->right, x); if(root->val == x && max(max(l, r), N - l - r - 1) > N / 2) over = true; return l + r + 1; } }; /* vim: set expandtab ts=4 sw=4 sts=4 tw=100 */
[ "roeexu@gmail.com" ]
roeexu@gmail.com
449f7277593d88a2ee461059eac5f1d26357771e
db5ee18e9e4da030ac45acd228443c07968ce1e3
/Classes/Mover.h
054b71d6b413341b1e4f8994f9c99f1a94fa35d5
[ "MIT" ]
permissive
ljwlaji/cocos2d-x_Fate-Alpha
6ae2120209c50aeee65b86937f0ddcb4c8340e2f
271691b383322e7479a3fc284fd6c923141e5822
refs/heads/master
2021-01-21T16:05:43.919646
2017-05-27T14:32:58
2017-05-27T14:32:58
91,875,817
18
0
null
null
null
null
GB18030
C++
false
false
196
h
#ifndef __MOVER_H__ #define __MOVER_H__ //全局单例对象 用来检测碰撞 #include "Types.h" class Mover { public: Mover(); ~Mover(); static Mover* GetInstance(); private: }; #endif
[ "602809934@qq.com" ]
602809934@qq.com
9b11a09a8c4560ed47030787a7428d1bec45d60b
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5751500831719424_1/C++/igerasim/a.cpp
c97007a6cf49961ee84f9d34883c7bc5cade90a6
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,839
cpp
#include <iostream> #include <iomanip> #include <vector> #include <array> #include <algorithm> #include <hash_map> #include <string> #include <map> #include <set> #include <queue> #if 0 #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; typedef int256_t lll; typedef uint256_t ulll; #endif using namespace std; using namespace std::tr1; using namespace stdext; typedef __int64 ll; typedef unsigned __int64 ull; int T, N; string str[128]; int solve() { if (str[0].empty()) return 0; char ch = str[0][0]; vector<int> cnts(N, 0); for (int n = 0; n != N; ++n) { for (int i = 0; i != str[n].size(); ++i) { if (str[n][i] != ch) break; cnts[n]++; } } int opt_dlt = 10000000; for (int c = 1; c != 128; ++c) { int dlt = 0; for (int n = 0; n != N; ++n) { dlt += abs(c - cnts[n]); } if (dlt < opt_dlt) { opt_dlt = dlt; } } for (int n = 0; n != N; ++n) { str[n] = str[n].substr(cnts[n]); } return opt_dlt + solve(); } int main(int argc, char* argv[]) { cin >> dec >> T; for (int t = 0; t != T; ++t) { cout << "Case #" << (t + 1) << ": "; cin >> N; for (int n = 0; n != N; ++n) { cin >> str[n]; } bool ok = true; string s = str[0]; s.erase(unique(s.begin(), s.end()), s.end()); for (int n = 0; ok && n != N; ++n) { string s1 = str[n]; s1.erase(unique(s1.begin(), s1.end()), s1.end()); ok = (s1 == s); } if (!ok) { cout << "Fegla Won" << "\n"; } else { cout << solve() << "\n"; } } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
bc5eb7693c8b89af1ef2ec4c70be51240a67fcd3
d435749c4904b127ea52ca39508c39c94ef8735b
/techer4_2_2/Revarray.h
75804bdb748cceae8acf52422f70ccf7df04ee34
[]
no_license
Tesla-1i/CPP
1fefcea726c29bb6dc7c1f18f580640252f70b2b
9e37a9e1b3cd0426710a86f582be97ad5fda61d8
refs/heads/master
2021-10-13T09:19:06.559404
2017-04-19T01:01:46
2017-04-19T01:01:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
170
h
#include "Myarray.h" #ifndef REVARRAY #define REVARRAY class Revarray :virtual public Myarray { public: Revarray(int leng); ~Revarray(); void revArray(); }; #endif
[ "sdmengxiangyu@gmail.com" ]
sdmengxiangyu@gmail.com
3c48a2ca1b9e1b5b74f09a36f976c2dd16bc44ed
675fade53b5dc60dac5d9cf08150b15d11e6dca3
/Temp/StagingArea/Data/il2cppOutput/System_System_ComponentModel_Int32Converter1078787070.h
2897f7572d51e4dce50f823853d1ca68a2975333
[]
no_license
tejaskhorana/SandboxFPS
be90670c29dbe20b20295e36c85e8e73b948f08f
6c795634703e31e4ab6d416663fbf6c89b179c59
refs/heads/master
2020-02-26T15:05:01.879563
2017-05-24T05:52:04
2017-05-24T05:52:04
83,266,163
2
1
null
null
null
null
UTF-8
C++
false
false
568
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "System_System_ComponentModel_BaseNumberConverter3737780012.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ComponentModel.Int32Converter struct Int32Converter_t1078787070 : public BaseNumberConverter_t3737780012 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "tejaskhorana@gatech.edu" ]
tejaskhorana@gatech.edu
252bd428b8ad47f5814bf4696ff6c379673d43fb
7f7f472167623e31277b950690ee088981450901
/DigitalFactory/mainwindow_about/mainwindow.h
0abf2c317bcf97342170b632e02fcb8ad4d384e5
[]
no_license
infcnwangjie/cpp_isbest
056d2a8fa1742303254af9ed43fa2652da577a1b
2777deba5955f62b2ad81e34e493e9cf3c7cbb4b
refs/heads/master
2023-04-13T14:44:54.617178
2021-04-30T22:07:26
2021-04-30T22:07:26
261,371,230
0
0
null
null
null
null
UTF-8
C++
false
false
777
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include<QMdiArea> #include <QMdiSubWindow> #include <QVBoxLayout> //#include "loginform.h" #include "tinyjson.hpp" #include <cassert> QT_BEGIN_NAMESPACE namespace Ui { class MainWindowUi; class MainWindowNewUi;} QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); //private: // LoginForm * loginDialog; public: void paintEvent(QPaintEvent *event); void currentuserinfo();//当前用户信息 private: Ui::MainWindowUi *ui; // QVBoxLayout *loginLayout; // QMdiArea * mdiArea; // QMdiSubWindow *loginFormMdiSubWindow; // Ui::LoginDialog * loginUi; }; #endif // MAINWINDOW_H
[ "wangjie@shengyidi.com" ]
wangjie@shengyidi.com
4ae55f8a5cb563a46c202afd57331e6724f3af56
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5695413893988352_0/C++/chigichan24/b.cpp
9da97d779f9148a57b8dfdc91c6060dc50d597dd
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,647
cpp
#include <bits/stdc++.h> using namespace std; const int dx[]={1,0,-1,0,1,-1,-1,1}; const int dy[]={0,1,0,-1,1,1,-1,-1}; const int INF = 1e9; const long long LINF = 1e18; const double EPS = 1e-8; #define pb push_back #define mk make_pair #define fr first #define sc second #define ll long long #define reps(i,j,k) for(int i = (j); i < (k); i++) #define rep(i,j) reps(i,0,j) #define MOD 1000000007 typedef pair<int,int> Pii; typedef pair<int, ll> Pil; typedef pair<string,string> Pss; typedef vector<int> vi; typedef vector<vi> vvi; string C,J; int mx; void dfs(string a,string b,int depth){ if(depth == a.size()){ int ret = abs(atoi(a.c_str())-atoi(b.c_str())); if(ret < mx){ C = a; J = b; mx = ret; } return ; } if(a[depth] == '?' && b[depth] != '?'){ rep(i,10){ a[depth] = i+'0'; dfs(a,b,depth+1); a[depth] = '?'; } } if(a[depth] != '?' && b[depth] == '?'){ rep(i,10){ b[depth] = i+'0'; dfs(a,b,depth+1); b[depth] = '?'; } } if(a[depth] == '?' && b[depth] == '?'){ rep(i,10){ rep(j,10){ a[depth] = i+'0'; b[depth] = j+'0'; dfs(a,b,depth+1); a[depth] = b[depth] = '?'; } } } if(a[depth] != '?' && b[depth] != '?'){ dfs(a,b,depth+1); } return ; } Pss solve(string str1,string str2){ mx = INF; C = ""; J = ""; dfs(str1,str2,0); Pss ans; ans.fr = C; ans.sc = J; return ans; } int main(){ int Q; scanf("%d",&Q); rep(q,Q){ string str1,str2; cin >> str1 >> str2; Pss ans = solve(str1,str2); printf("Case #%d: %s %s\n",q+1,ans.fr.c_str(),ans.sc.c_str()); } return 0; }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
afc5c21da6644597f1f6b017e184547aa022065a
cf2bb021e8a3fd7b9323ab785b3b050044b4270e
/src/mapelemview.cpp
30a15cf134a257c476617e028702cc25eab181d9
[]
no_license
bulat-f/SeaBattle
bd0e0a0be90e76bbac4608a5ace634b24affa6e4
0a3b048110978b36b90e6b4340d8f8b9d51257b3
refs/heads/master
2021-05-27T23:48:59.244104
2013-12-19T06:39:29
2013-12-19T06:39:29
15,053,476
0
1
null
null
null
null
UTF-8
C++
false
false
500
cpp
#include "mapelemview.h" #include <iostream> using namespace std; MapElemView::MapElemView() { //ctor } MapElemView::~MapElemView() { //dtor } void MapElemView::show(const MapElement &elem) { switch (elem.state) { case MapElement::MISS: cout << "' | "; return; case MapElement::DEAD: cout << "X | "; return; case MapElement::type::BORDER: cout << "b | "; return; default: cout << " | "; } }
[ "fatbulat5@gmail.com" ]
fatbulat5@gmail.com
50f0761e9dbf199dc42a698720c7c0739f084cd4
4fffd88df0391db8cb0274733c160595c3ca7fa6
/Practice/Plagiarism.cpp
eb82e952c343a916879967cdbd36110235bef7f1
[]
no_license
YatharthNigam/Codechef
b00bffa7c9d3b51e76fce9d96599161909da21c0
67b6977cf2a6e6764ec924ccfcded2323e894a29
refs/heads/main
2023-08-01T20:50:06.653197
2021-09-15T17:50:52
2021-09-15T17:50:52
390,731,038
0
0
null
null
null
null
UTF-8
C++
false
false
687
cpp
#include <bits/stdc++.h> using namespace std; void solve() { int n, m, k; cin >> n >> m >> k; int arr[k]; for (int i = 0; i < k; i++) { cin >> arr[i]; } map<int, int> map; for (int i = 0; i < k; i++) { if (arr[i] <= n) map[arr[i]]++; } int flag = 0; for (auto i : map) { if (i.second >= 2) { flag++; } } cout << flag << " "; for (auto i : map) { if (i.second >= 2) { cout << i.first << " "; } } cout << endl; } int main() { int t; cin >> t; while (t--) { solve(); } return 0; }
[ "yatharthnigam@gmail.com" ]
yatharthnigam@gmail.com
14281b1ed954325cb15730453b4b4f9c63a49ddd
d6b4bdf418ae6ab89b721a79f198de812311c783
/faceid/include/tencentcloud/faceid/v20180301/model/DetectReflectLivenessAndCompareRequest.h
0969870ab4dd40097b93342c10c9d41192788cd6
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
6,683
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_FACEID_V20180301_MODEL_DETECTREFLECTLIVENESSANDCOMPAREREQUEST_H_ #define TENCENTCLOUD_FACEID_V20180301_MODEL_DETECTREFLECTLIVENESSANDCOMPAREREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Faceid { namespace V20180301 { namespace Model { /** * DetectReflectLivenessAndCompare request structure. */ class DetectReflectLivenessAndCompareRequest : public AbstractModel { public: DetectReflectLivenessAndCompareRequest(); ~DetectReflectLivenessAndCompareRequest() = default; std::string ToJsonString() const; /** * 获取URL of the liveness detection data package generated by the SDK * @return LiveDataUrl URL of the liveness detection data package generated by the SDK * */ std::string GetLiveDataUrl() const; /** * 设置URL of the liveness detection data package generated by the SDK * @param _liveDataUrl URL of the liveness detection data package generated by the SDK * */ void SetLiveDataUrl(const std::string& _liveDataUrl); /** * 判断参数 LiveDataUrl 是否已赋值 * @return LiveDataUrl 是否已赋值 * */ bool LiveDataUrlHasBeenSet() const; /** * 获取MD5 hash value (32-bit) of the liveness detection data package generated by the SDK, which is used to verify the LiveData consistency. * @return LiveDataMd5 MD5 hash value (32-bit) of the liveness detection data package generated by the SDK, which is used to verify the LiveData consistency. * */ std::string GetLiveDataMd5() const; /** * 设置MD5 hash value (32-bit) of the liveness detection data package generated by the SDK, which is used to verify the LiveData consistency. * @param _liveDataMd5 MD5 hash value (32-bit) of the liveness detection data package generated by the SDK, which is used to verify the LiveData consistency. * */ void SetLiveDataMd5(const std::string& _liveDataMd5); /** * 判断参数 LiveDataMd5 是否已赋值 * @return LiveDataMd5 是否已赋值 * */ bool LiveDataMd5HasBeenSet() const; /** * 获取URL of the target image for comparison * @return ImageUrl URL of the target image for comparison * */ std::string GetImageUrl() const; /** * 设置URL of the target image for comparison * @param _imageUrl URL of the target image for comparison * */ void SetImageUrl(const std::string& _imageUrl); /** * 判断参数 ImageUrl 是否已赋值 * @return ImageUrl 是否已赋值 * */ bool ImageUrlHasBeenSet() const; /** * 获取MD5 hash value (32-bit) of the target image for comparison, which is used to verify the `Image` consistency. * @return ImageMd5 MD5 hash value (32-bit) of the target image for comparison, which is used to verify the `Image` consistency. * */ std::string GetImageMd5() const; /** * 设置MD5 hash value (32-bit) of the target image for comparison, which is used to verify the `Image` consistency. * @param _imageMd5 MD5 hash value (32-bit) of the target image for comparison, which is used to verify the `Image` consistency. * */ void SetImageMd5(const std::string& _imageMd5); /** * 判断参数 ImageMd5 是否已赋值 * @return ImageMd5 是否已赋值 * */ bool ImageMd5HasBeenSet() const; private: /** * URL of the liveness detection data package generated by the SDK */ std::string m_liveDataUrl; bool m_liveDataUrlHasBeenSet; /** * MD5 hash value (32-bit) of the liveness detection data package generated by the SDK, which is used to verify the LiveData consistency. */ std::string m_liveDataMd5; bool m_liveDataMd5HasBeenSet; /** * URL of the target image for comparison */ std::string m_imageUrl; bool m_imageUrlHasBeenSet; /** * MD5 hash value (32-bit) of the target image for comparison, which is used to verify the `Image` consistency. */ std::string m_imageMd5; bool m_imageMd5HasBeenSet; }; } } } } #endif // !TENCENTCLOUD_FACEID_V20180301_MODEL_DETECTREFLECTLIVENESSANDCOMPAREREQUEST_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
5d3e9acee966dfa28cbc0be042d26d92107f8adc
1a20961af3b03b46c109b09812143a7ef95c6caa
/ZGame/DX11/hieroglyph3/trunk/Hieroglyph3/Source/Frustum3f.cpp
c194fba84f751d17418801454aa75b767afa8d60
[ "MIT" ]
permissive
JetAr/ZNginx
eff4ae2457b7b28115787d6af7a3098c121e8368
698b40085585d4190cf983f61b803ad23468cdef
refs/heads/master
2021-07-16T13:29:57.438175
2017-10-23T02:05:43
2017-10-23T02:05:43
26,522,265
3
1
null
null
null
null
UTF-8
C++
false
false
5,187
cpp
//-------------------------------------------------------------------------------- // This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed // under the MIT License, available in the root of this distribution and // at the following URL: // // http://www.opensource.org/licenses/mit-license.php // // Copyright (c) Jason Zink //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- #include "PCH.h" #include "Frustum3f.h" //-------------------------------------------------------------------------------- using namespace Glyph3; //-------------------------------------------------------------------------------- Frustum3f::Frustum3f() { for (int i = 0; i < 6; i++) { planes[i].a = 0.0f; planes[i].b = 0.0f; planes[i].c = 0.0f; planes[i].d = 0.0f; } } //-------------------------------------------------------------------------------- Frustum3f::Frustum3f( const Matrix4f& ViewProjection ) { Update( ViewProjection, true ); } //-------------------------------------------------------------------------------- Frustum3f::~Frustum3f() { } //-------------------------------------------------------------------------------- void Frustum3f::Update( const Matrix4f& ViewProj, bool bNormalize ) { // Left Plane planes[0].a = ViewProj(0,3) + ViewProj(0,0); planes[0].b = ViewProj(1,3) + ViewProj(1,0); planes[0].c = ViewProj(2,3) + ViewProj(2,0); planes[0].d = ViewProj(3,3) + ViewProj(3,0); // Right Plane planes[1].a = ViewProj(0,3) - ViewProj(0,0); planes[1].b = ViewProj(1,3) - ViewProj(1,0); planes[1].c = ViewProj(2,3) - ViewProj(2,0); planes[1].d = ViewProj(3,3) - ViewProj(3,0); // Top Plane planes[2].a = ViewProj(0,3) - ViewProj(0,1); planes[2].b = ViewProj(1,3) - ViewProj(1,1); planes[2].c = ViewProj(2,3) - ViewProj(2,1); planes[2].d = ViewProj(3,3) - ViewProj(3,1); // Bottom Plane planes[3].a = ViewProj(0,3) + ViewProj(0,1); planes[3].b = ViewProj(1,3) + ViewProj(1,1); planes[3].c = ViewProj(2,3) + ViewProj(2,1); planes[3].d = ViewProj(3,3) + ViewProj(3,1); // Near Plane planes[4].a = ViewProj(0,2); planes[4].b = ViewProj(1,2); planes[4].c = ViewProj(2,2); planes[4].d = ViewProj(3,2); // Far Plane planes[5].a = ViewProj(0,3) - ViewProj(0,2); planes[5].b = ViewProj(1,3) - ViewProj(1,2); planes[5].c = ViewProj(2,3) - ViewProj(2,2); planes[5].d = ViewProj(3,3) - ViewProj(3,2); // Normalize all planes if ( bNormalize ) { for (int i = 0; i < 6; i++) { planes[i].Normalize(); } } } //-------------------------------------------------------------------------------- bool Frustum3f::Test( const Vector3f& TestPoint ) const { // Test the point against each plane if ( planes[0].DistanceToPoint( TestPoint ) < 0 ) return(false); if ( planes[1].DistanceToPoint( TestPoint ) < 0 ) return(false); if ( planes[2].DistanceToPoint( TestPoint ) < 0 ) return(false); if ( planes[3].DistanceToPoint( TestPoint ) < 0 ) return(false); if ( planes[4].DistanceToPoint( TestPoint ) < 0 ) return(false); if ( planes[5].DistanceToPoint( TestPoint ) < 0 ) return(false); // If all tests passed, point is within the frustum return( true ); } //-------------------------------------------------------------------------------- bool Frustum3f::Test( const Sphere3f& TestSphere ) const { // Test the center against each plane and compare the radius float fTemp = 0.0f; for (int i = 0; i < 6; i++) { fTemp = planes[i].DistanceToPoint( TestSphere.center ); if ( fTemp < -TestSphere.radius ) return( false ); if ( float(fabs(fTemp)) < TestSphere.radius ) return( true ); } // If all tests passed, sphere is at least intersecting the frustum return( true ); } //-------------------------------------------------------------------------------- bool Frustum3f::Intersects( const Sphere3f& bounds ) const { // distance to point plus the radius must be greater than zero to be intersecting!!! for ( int i = 0; i < 6; i++ ) { if ( planes[i].DistanceToPoint( bounds.center ) + bounds.radius < 0 ) return( false ); } // must not be enveloped if it is intersecting //if ( Envelops( bounds ) ) // return( false ); // if all tests passed, then sphere is enveloped return( true ); } //-------------------------------------------------------------------------------- bool Frustum3f::Envelops( const Sphere3f& bounds ) const { // distance to point minus the radius must be greater than zero to be enveloped!!! for ( int i = 0; i < 6; i++ ) { if (planes[i].DistanceToPoint( bounds.center ) - bounds.radius < 0) return( false ); } // If all tests passed, sphere is enveloped return( true ); } //--------------------------------------------------------------------------------
[ "126.org@gmail.com" ]
126.org@gmail.com
fe01b558fbc656b8abfa6fad39bd438702724c2b
97edd04548079640c7d8f37293adcd2e94ca82d6
/source files/EnemyPattern.h
da64ca3f45220d3bd6ff87ef03f54484037f6076
[]
no_license
eunho5751/BarrageShooting
5d2ef19d14a15f429a85ce571f77d5f7865a196e
0c7e0d5ab4a2076c2e7294c3e6efd45e45e24817
refs/heads/master
2022-06-04T04:55:07.808228
2022-03-30T14:27:25
2022-03-30T14:27:25
159,177,025
0
0
null
null
null
null
UTF-8
C++
false
false
1,883
h
#pragma once #include "Enemy.h" #include "EntityMgr.h" #include "DataMgr.h" class CSpiralShooter : public CEnemy { private: float m_fShotAngle; float m_fShotAngleRate; float m_fShotSpeed; public: CSpiralShooter(ImageData* _image, float _scale, float _speed, float _x, float _y, float _shotAngle, float _shotAngleRate, float _shotSpeed) : CEnemy(_image, _scale, _speed, _x, _y), m_fShotAngle(_shotAngle), m_fShotAngleRate(_shotAngleRate), m_fShotSpeed(_shotSpeed) { } virtual void Update(float _time) { ENTITY_MGR().CreateBullet(this, DATA_MGR().GetImageData("bullet1.bmp"), 1.f, 1.0f, m_fX, m_fY, m_fShotSpeed, m_fShotAngle, 0.0f, 0.0f); m_fShotAngle += m_fShotAngleRate; } }; class CSpiralShooter2 : public CEnemy { private: float m_fShotAngle; float m_fShotAngleRate; float m_fShotSpeed; public: CSpiralShooter2(ImageData* _image, float _scale, float _speed, float _x, float _y, float _shotAngle, float _shotAngleRate, float _shotSpeed) : CEnemy(_image, _scale, _speed, _x, _y), m_fShotAngle(_shotAngle), m_fShotAngleRate(_shotAngleRate), m_fShotSpeed(_shotSpeed) { } virtual void Update(float _time) { ENTITY_MGR().CreateBullet(this, DATA_MGR().GetImageData("bullet2.bmp"), 1.f, 1.0f, m_fX, m_fY, m_fShotSpeed, m_fShotAngle, 1.0f, 0.0f); m_fShotAngle += m_fShotAngleRate; } }; class CRandomShooter : public CEnemy { private: float m_fShotAngle; float m_fShotSpeed; public: CRandomShooter(ImageData* _image, float _scale, float _speed, float _x, float _y, float _shotSpeed) : CEnemy(_image, _scale, _speed, _x, _y), m_fShotAngle(0.0f), m_fShotSpeed(_shotSpeed) { } virtual void Update(float _time) { ENTITY_MGR().CreateBullet(this, DATA_MGR().GetImageData("bullet3.bmp"), 1.f, 1.0f, m_fX, m_fY, m_fShotSpeed, m_fShotAngle, 0.0f, 0.0f); m_fShotAngle += rand() % 100; } };
[ "noreply@github.com" ]
noreply@github.com
e071d5ad6a77748dcdb83ec886012cddd408d3d9
ec8118f8bc19611e205c57dce39c6c9102c5a00f
/baekjoon/1120_문자열.cpp
f47e71663b7f75e1e9acf8b1df3be38c11312299
[]
no_license
sjsjsj1246/Algorithm_study
a5433223741ffda89b2b63c22e876920c46882ea
5a45b1f64991138fdb0fdb02b0f345e07d2f6a74
refs/heads/master
2021-06-06T08:40:47.275376
2019-12-09T14:31:22
2019-12-09T14:31:22
143,863,615
1
0
null
null
null
null
UTF-8
C++
false
false
517
cpp
#include <iostream> #include <vector> #include <string> #include <cstring> #include <functional> #include <queue> #include <algorithm> #define MOD 1000000 #define fast ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); using namespace std; int main() { string a, b; cin >> a >> b; int Min = 51; int len = b.length() - a.length() + 1; for (int i = 0; i < len; i++) { int sum = 0; for (int j = 0; j < a.length(); j++) { if (a[j] != b[j + i]) sum++; } if (Min > sum) Min = sum; } cout << Min; }
[ "sjsjsj1246@gmail.com" ]
sjsjsj1246@gmail.com
cc31efaeb212904e58f48ff090b80fd996567d03
21b7d8820a0fbf8350d2d195f711c35ce9865a21
/Required Remainder.cpp
6108f18c76c778554d0ee387d2df238b9d72fc1d
[]
no_license
HarshitCd/Codeforces-Solutions
16e20619971c08e036bb19186473e3c77b9c4634
d8966129b391875ecf93bc3c03fc7b0832a2a542
refs/heads/master
2022-12-25T22:00:17.077890
2020-10-12T16:18:20
2020-10-12T16:18:20
286,409,002
0
0
null
null
null
null
UTF-8
C++
false
false
217
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int t, x, y, n; cin>>t; while(t--){ cin>>x>>y>>n; n = (n>=n-n%x+y)?n-n%x+y:n-n%x+y-x; cout<<n<<endl; } return 0; }
[ "harshitcd@gmail.com" ]
harshitcd@gmail.com
391fd6f3777cba3e7177e45d6ed99cef72dbc8a1
6fed8181b8680a160c15efa9df76543785549693
/include/Util/TypeDefs.h
0e3838aa6e659d08b714371e9b2d589812ea6165
[ "Apache-2.0" ]
permissive
marchartung/Actul
dcc774bdd3ae7c445336c88ac062f4f669e66099
eb5b1f278a6d128377afba631d62e07e7e909eef
refs/heads/master
2020-03-16T02:11:56.039211
2018-05-07T12:46:20
2018-05-07T12:46:20
132,459,196
1
0
null
null
null
null
UTF-8
C++
false
false
1,192
h
//////////////////////////////////////////////////////////////////////////////// // Copyright 2017-2018 Zuse Institute Berlin // // 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. // // Contributors: // Marc Hartung //////////////////////////////////////////////////////////////////////////////// #ifndef INCLUDE_TYPEDEFS_HPP_ #define INCLUDE_TYPEDEFS_HPP_ #include <cstdint> #include <sys/types.h> namespace Actul { typedef uint16_t tid_type; typedef int16_t sid_type; typedef uint32_t size_type; typedef uint32_t event_id; typedef int64_t sync_status_type; typedef const void * AddressType; typedef void*(*ExecuteFunction)(void*); } #endif /* INCLUDE_TYPEDEFS_HPP_ */
[ "hartung@zib.de" ]
hartung@zib.de
1c31256a1fa0d40f2291bf1a5cc2d29536357ca3
2bce17904e161a4bdaa2d65cefd25802bf81c85b
/codeforces/121/A/bf.cc
36c36c24dc21bc1cdd3c44527ddb676608c3abc0
[]
no_license
lichenk/AlgorithmContest
9c3e26ccbe66d56f27e574f5469e9cfa4c6a74a9
74f64554cb05dc173b5d44b8b67394a0b6bb3163
refs/heads/master
2020-03-24T12:52:13.437733
2018-08-26T01:41:13
2018-08-26T01:41:13
142,727,319
0
0
null
null
null
null
UTF-8
C++
false
false
1,601
cc
#pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,sse4.1,sse4.2,popcnt,abm,mmx,avx,tune=native") #include "bits/stdc++.h" #include <assert.h> using namespace std; typedef long long ll; typedef long double ld; #define PB push_back #define MP make_pair const int MOD=1000000007; #define endl "\n" #define fst first #define snd second const int UNDEF = -1; const int INF=1<<30; template<typename T> inline bool chkmax(T &aa, T bb) { return aa < bb ? aa = bb, true : false; } template<typename T> inline bool chkmin(T &aa, T bb) { return aa > bb ? aa = bb, true : false; } typedef pair<ll,ll> pll;typedef vector<ll> vll;typedef pair<int,int> pii;typedef vector<int> vi;typedef vector<vi> vvi; #ifdef ONLINE_JUDGE #define assert(...) /* nothing */ #endif #define DEBUG_CAT #ifdef DEBUG_CAT #define dbg(...) printf( __VA_ARGS__ ) #else #define dbg(...) /****nothing****/ #endif int rint();char rch();long long rlong(); int main() { ios_base::sync_with_stdio(false); cin.tie(0); vector<ll> v; for (int l=1;l<=11;l++) { for (int z=0;z<(1<<l);z++) { ll x=0; for (int i=0;i<l;i++) { x*=10; if (z&(1<<i)) x+=7; else x+=4; } v.PB(x); } } sort(v.begin(),v.end()); ll l=rint(),r=rint(); ll ans=0; for (ll x=l;x<=r;x++) { ll got=0; for (auto &w:v) { if (w>=x) {got=w; break;} } assert(got!=0); ans+=got; } printf("%lld\n",ans); } int rint() { int x; scanf("%d",&x); return x; } char rch() { char x; scanf("%c",&x); return x; } long long rlong() { long long x; scanf("%lld",&x); return x; }
[ "Li Chen Koh" ]
Li Chen Koh
d721c010674d6407ba223b37880d65d090474aaf
dfb931f848291d10bf6c23d35532a511feb14829
/laba1.cpp
f951d8e5390ca5813a458d8b166e0e863aff3b06
[]
no_license
SergeiPetrin/DA
465ca8bcb8699f49ebe894ea6310e0688183e3f0
6f71de5ebe50a115febb7db60b1c5ad5b9c658ce
refs/heads/master
2020-09-27T15:39:52.243459
2019-12-12T01:06:29
2019-12-12T01:06:29
226,548,066
0
0
null
null
null
null
UTF-8
C++
false
false
4,058
cpp
#include <iostream> #include <cstdlib> struct KValue { char keys[9]; unsigned long long value; }; class TVector { int size; int capacity; KValue* vectorData; public: TVector() { size = 0; capacity = 0; vectorData = new KValue[2]; } TVector(int var) { size = var; capacity = var; vectorData = new KValue[var]; } TVector(int k, KValue* m) { size = k; capacity = k; vectorData = new KValue[k]; if (k != 0) { for (size_t j = 0; j < k; j++) { vectorData[j] = m[j]; } } } KValue& operator[] (int k) { return vectorData[k]; } int VectorSize() { return size; } void NewSize() { if (capacity == 0) { capacity = 1; } capacity *= 2; KValue* temporary = new KValue[capacity]; for (int j = 0; j < size; j++) { temporary[j] = vectorData[j]; } delete [] vectorData; vectorData = temporary; } void PushBack(KValue element) { if (size == capacity) { NewSize(); } vectorData[size++] = element; } ~TVector() { delete [] vectorData; } }; void RadixSorting(TVector &vector) { int digitsC[10] = {}; int charsC[26] = {}; TVector temp(vector.VectorSize()); for (int i = 8; i != 0; i--) { if (vector[0].keys[i - 1] == ' ') { continue; } if (vector[0].keys[i - 1] >= '0' && vector[0].keys[i - 1] <= '9') { int j = 0; int n = 0; for (j = 0; j < vector.VectorSize(); j++) { digitsC[vector[j].keys[i - 1] - '0'] += 1; } for (n = 1; n < 10; n++) { digitsC[n] += digitsC[n - 1]; } for (j = vector.VectorSize(); j != 0; j--) { --digitsC[vector[j - 1].keys[i - 1] - '0']; temp[digitsC[vector[j - 1].keys[i - 1] - '0']] = vector[j - 1]; } } else { int j = 0; int n = 0; for (j = 0; j < vector.VectorSize(); j++) { charsC[vector[j].keys[i - 1] - 'A'] += 1; } for (n = 1; n < 26; n++) { charsC[n] += charsC[n - 1]; } for (j = vector.VectorSize(); j != 0; j--) { --charsC[vector[j - 1].keys[i - 1] - 'A']; temp[charsC[vector[j - 1].keys[i - 1] - 'A']] = vector[j - 1]; } } for (int k = 0; k < 10; k++) { digitsC[k] = 0; } for (int k = 0; k < 26; k++) { charsC[k] = 0; } for (int m = 0; m < vector.VectorSize(); m++) { vector[m] = temp[m]; } } } int main() { std::ios::sync_with_stdio(false); TVector dataVector; KValue element; char string[64] = {}; char number[32] = {}; while (true) { string[0] = '\0'; std::cin.getline(string, 64); if (std::cin.eof()) { break; } if (std::cin.fail() || (string[0] < 'A')) { continue; } int k = 0; int j = 0; for (k = 0; k < 8; k++) { element.keys[k] = string[k]; } element.keys[8] = '\0'; while (!(string[k] >= '0' && string[k] <= '9')) { k++; } while (string[k] >= '0' && string[k] <= '9') { number[j++] = string[k++]; } element.value = std::strtoull(number, NULL, 10); dataVector.PushBack(element); for (j = 0; j < 32; j++) { number[j] = 0; } for (k = 0; k < 64; k++) { string[k] = 0; } } if (dataVector.VectorSize() != 0) { RadixSorting(dataVector); } for (int j = 0; j < dataVector.VectorSize(); j++) { std::cout << dataVector[j].keys << " " << dataVector[j].value << std::endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
feb6a128a07809db79ff9a8de90a5b329a6fcfca
41194968e73ba2874847828bc7f31a41259e29b5
/xulrunner-sdk-26/xulrunner-sdk/include/nsIComponentRegistrar.h
7446c9f8bbf5fcdf93c85e576ef1ce011c1f58e0
[]
no_license
snowmantw/gaia-essential
81d544d579ff4c502a75480f1fcf3a19a6e783b7
2751716dc87dea320c9c9fd2a3f82deed337ad70
refs/heads/master
2020-04-05T17:03:12.939201
2013-12-08T10:55:46
2013-12-08T10:55:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,200
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/m-cen-osx64-xr-ntly-0000000000/build/xpcom/components/nsIComponentRegistrar.idl */ #ifndef __gen_nsIComponentRegistrar_h__ #define __gen_nsIComponentRegistrar_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIFile; /* forward declaration */ class nsIFactory; /* forward declaration */ class nsISimpleEnumerator; /* forward declaration */ /* starting interface: nsIComponentRegistrar */ #define NS_ICOMPONENTREGISTRAR_IID_STR "2417cbfe-65ad-48a6-b4b6-eb84db174392" #define NS_ICOMPONENTREGISTRAR_IID \ {0x2417cbfe, 0x65ad, 0x48a6, \ { 0xb4, 0xb6, 0xeb, 0x84, 0xdb, 0x17, 0x43, 0x92 }} class NS_NO_VTABLE nsIComponentRegistrar : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICOMPONENTREGISTRAR_IID) /* void autoRegister (in nsIFile aSpec); */ NS_IMETHOD AutoRegister(nsIFile *aSpec) = 0; /* void autoUnregister (in nsIFile aSpec); */ NS_IMETHOD AutoUnregister(nsIFile *aSpec) = 0; /* void registerFactory (in nsCIDRef aClass, in string aClassName, in string aContractID, in nsIFactory aFactory); */ NS_IMETHOD RegisterFactory(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFactory *aFactory) = 0; /* void unregisterFactory (in nsCIDRef aClass, in nsIFactory aFactory); */ NS_IMETHOD UnregisterFactory(const nsCID & aClass, nsIFactory *aFactory) = 0; /* void registerFactoryLocation (in nsCIDRef aClass, in string aClassName, in string aContractID, in nsIFile aFile, in string aLoaderStr, in string aType); */ NS_IMETHOD RegisterFactoryLocation(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFile *aFile, const char * aLoaderStr, const char * aType) = 0; /* void unregisterFactoryLocation (in nsCIDRef aClass, in nsIFile aFile); */ NS_IMETHOD UnregisterFactoryLocation(const nsCID & aClass, nsIFile *aFile) = 0; /* boolean isCIDRegistered (in nsCIDRef aClass); */ NS_IMETHOD IsCIDRegistered(const nsCID & aClass, bool *_retval) = 0; /* boolean isContractIDRegistered (in string aContractID); */ NS_IMETHOD IsContractIDRegistered(const char * aContractID, bool *_retval) = 0; /* nsISimpleEnumerator enumerateCIDs (); */ NS_IMETHOD EnumerateCIDs(nsISimpleEnumerator * *_retval) = 0; /* nsISimpleEnumerator enumerateContractIDs (); */ NS_IMETHOD EnumerateContractIDs(nsISimpleEnumerator * *_retval) = 0; /* string CIDToContractID (in nsCIDRef aClass); */ NS_IMETHOD CIDToContractID(const nsCID & aClass, char * *_retval) = 0; /* nsCIDPtr contractIDToCID (in string aContractID); */ NS_IMETHOD ContractIDToCID(const char * aContractID, nsCID **_retval) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIComponentRegistrar, NS_ICOMPONENTREGISTRAR_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSICOMPONENTREGISTRAR \ NS_IMETHOD AutoRegister(nsIFile *aSpec); \ NS_IMETHOD AutoUnregister(nsIFile *aSpec); \ NS_IMETHOD RegisterFactory(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFactory *aFactory); \ NS_IMETHOD UnregisterFactory(const nsCID & aClass, nsIFactory *aFactory); \ NS_IMETHOD RegisterFactoryLocation(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFile *aFile, const char * aLoaderStr, const char * aType); \ NS_IMETHOD UnregisterFactoryLocation(const nsCID & aClass, nsIFile *aFile); \ NS_IMETHOD IsCIDRegistered(const nsCID & aClass, bool *_retval); \ NS_IMETHOD IsContractIDRegistered(const char * aContractID, bool *_retval); \ NS_IMETHOD EnumerateCIDs(nsISimpleEnumerator * *_retval); \ NS_IMETHOD EnumerateContractIDs(nsISimpleEnumerator * *_retval); \ NS_IMETHOD CIDToContractID(const nsCID & aClass, char * *_retval); \ NS_IMETHOD ContractIDToCID(const char * aContractID, nsCID **_retval); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSICOMPONENTREGISTRAR(_to) \ NS_IMETHOD AutoRegister(nsIFile *aSpec) { return _to AutoRegister(aSpec); } \ NS_IMETHOD AutoUnregister(nsIFile *aSpec) { return _to AutoUnregister(aSpec); } \ NS_IMETHOD RegisterFactory(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFactory *aFactory) { return _to RegisterFactory(aClass, aClassName, aContractID, aFactory); } \ NS_IMETHOD UnregisterFactory(const nsCID & aClass, nsIFactory *aFactory) { return _to UnregisterFactory(aClass, aFactory); } \ NS_IMETHOD RegisterFactoryLocation(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFile *aFile, const char * aLoaderStr, const char * aType) { return _to RegisterFactoryLocation(aClass, aClassName, aContractID, aFile, aLoaderStr, aType); } \ NS_IMETHOD UnregisterFactoryLocation(const nsCID & aClass, nsIFile *aFile) { return _to UnregisterFactoryLocation(aClass, aFile); } \ NS_IMETHOD IsCIDRegistered(const nsCID & aClass, bool *_retval) { return _to IsCIDRegistered(aClass, _retval); } \ NS_IMETHOD IsContractIDRegistered(const char * aContractID, bool *_retval) { return _to IsContractIDRegistered(aContractID, _retval); } \ NS_IMETHOD EnumerateCIDs(nsISimpleEnumerator * *_retval) { return _to EnumerateCIDs(_retval); } \ NS_IMETHOD EnumerateContractIDs(nsISimpleEnumerator * *_retval) { return _to EnumerateContractIDs(_retval); } \ NS_IMETHOD CIDToContractID(const nsCID & aClass, char * *_retval) { return _to CIDToContractID(aClass, _retval); } \ NS_IMETHOD ContractIDToCID(const char * aContractID, nsCID **_retval) { return _to ContractIDToCID(aContractID, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSICOMPONENTREGISTRAR(_to) \ NS_IMETHOD AutoRegister(nsIFile *aSpec) { return !_to ? NS_ERROR_NULL_POINTER : _to->AutoRegister(aSpec); } \ NS_IMETHOD AutoUnregister(nsIFile *aSpec) { return !_to ? NS_ERROR_NULL_POINTER : _to->AutoUnregister(aSpec); } \ NS_IMETHOD RegisterFactory(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFactory *aFactory) { return !_to ? NS_ERROR_NULL_POINTER : _to->RegisterFactory(aClass, aClassName, aContractID, aFactory); } \ NS_IMETHOD UnregisterFactory(const nsCID & aClass, nsIFactory *aFactory) { return !_to ? NS_ERROR_NULL_POINTER : _to->UnregisterFactory(aClass, aFactory); } \ NS_IMETHOD RegisterFactoryLocation(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFile *aFile, const char * aLoaderStr, const char * aType) { return !_to ? NS_ERROR_NULL_POINTER : _to->RegisterFactoryLocation(aClass, aClassName, aContractID, aFile, aLoaderStr, aType); } \ NS_IMETHOD UnregisterFactoryLocation(const nsCID & aClass, nsIFile *aFile) { return !_to ? NS_ERROR_NULL_POINTER : _to->UnregisterFactoryLocation(aClass, aFile); } \ NS_IMETHOD IsCIDRegistered(const nsCID & aClass, bool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsCIDRegistered(aClass, _retval); } \ NS_IMETHOD IsContractIDRegistered(const char * aContractID, bool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsContractIDRegistered(aContractID, _retval); } \ NS_IMETHOD EnumerateCIDs(nsISimpleEnumerator * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->EnumerateCIDs(_retval); } \ NS_IMETHOD EnumerateContractIDs(nsISimpleEnumerator * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->EnumerateContractIDs(_retval); } \ NS_IMETHOD CIDToContractID(const nsCID & aClass, char * *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->CIDToContractID(aClass, _retval); } \ NS_IMETHOD ContractIDToCID(const char * aContractID, nsCID **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->ContractIDToCID(aContractID, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsComponentRegistrar : public nsIComponentRegistrar { public: NS_DECL_ISUPPORTS NS_DECL_NSICOMPONENTREGISTRAR nsComponentRegistrar(); private: ~nsComponentRegistrar(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsComponentRegistrar, nsIComponentRegistrar) nsComponentRegistrar::nsComponentRegistrar() { /* member initializers and constructor code */ } nsComponentRegistrar::~nsComponentRegistrar() { /* destructor code */ } /* void autoRegister (in nsIFile aSpec); */ NS_IMETHODIMP nsComponentRegistrar::AutoRegister(nsIFile *aSpec) { return NS_ERROR_NOT_IMPLEMENTED; } /* void autoUnregister (in nsIFile aSpec); */ NS_IMETHODIMP nsComponentRegistrar::AutoUnregister(nsIFile *aSpec) { return NS_ERROR_NOT_IMPLEMENTED; } /* void registerFactory (in nsCIDRef aClass, in string aClassName, in string aContractID, in nsIFactory aFactory); */ NS_IMETHODIMP nsComponentRegistrar::RegisterFactory(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFactory *aFactory) { return NS_ERROR_NOT_IMPLEMENTED; } /* void unregisterFactory (in nsCIDRef aClass, in nsIFactory aFactory); */ NS_IMETHODIMP nsComponentRegistrar::UnregisterFactory(const nsCID & aClass, nsIFactory *aFactory) { return NS_ERROR_NOT_IMPLEMENTED; } /* void registerFactoryLocation (in nsCIDRef aClass, in string aClassName, in string aContractID, in nsIFile aFile, in string aLoaderStr, in string aType); */ NS_IMETHODIMP nsComponentRegistrar::RegisterFactoryLocation(const nsCID & aClass, const char * aClassName, const char * aContractID, nsIFile *aFile, const char * aLoaderStr, const char * aType) { return NS_ERROR_NOT_IMPLEMENTED; } /* void unregisterFactoryLocation (in nsCIDRef aClass, in nsIFile aFile); */ NS_IMETHODIMP nsComponentRegistrar::UnregisterFactoryLocation(const nsCID & aClass, nsIFile *aFile) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean isCIDRegistered (in nsCIDRef aClass); */ NS_IMETHODIMP nsComponentRegistrar::IsCIDRegistered(const nsCID & aClass, bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean isContractIDRegistered (in string aContractID); */ NS_IMETHODIMP nsComponentRegistrar::IsContractIDRegistered(const char * aContractID, bool *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsISimpleEnumerator enumerateCIDs (); */ NS_IMETHODIMP nsComponentRegistrar::EnumerateCIDs(nsISimpleEnumerator * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsISimpleEnumerator enumerateContractIDs (); */ NS_IMETHODIMP nsComponentRegistrar::EnumerateContractIDs(nsISimpleEnumerator * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* string CIDToContractID (in nsCIDRef aClass); */ NS_IMETHODIMP nsComponentRegistrar::CIDToContractID(const nsCID & aClass, char * *_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* nsCIDPtr contractIDToCID (in string aContractID); */ NS_IMETHODIMP nsComponentRegistrar::ContractIDToCID(const char * aContractID, nsCID **_retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIComponentRegistrar_h__ */
[ "snowmantw@gmail.com" ]
snowmantw@gmail.com
de36972f9d3df074b9bf2ed42c2be0070abfe445
a56c9cfcb60287941344f3ce7b7233fb3bdbbea1
/spreadsheet/finddialog.cpp
9a06b975b8bed5ecb5969ddd19c7ff40b1062f71
[]
no_license
AbdulmueezEmiola/Qt-Spreadsheet
b6c4b9f76d379b7900b4fcdfc0fe17fe9ab930df
f94c7475a435b37f9f3f506809207dbfde9ba670
refs/heads/master
2021-01-01T15:00:06.122577
2020-02-09T15:43:03
2020-02-09T15:43:03
239,328,528
0
0
null
null
null
null
UTF-8
C++
false
false
1,969
cpp
#include <QtWidgets> #include "finddialog.h" FindDialog::FindDialog(QWidget *parent) : QDialog(parent) { label = new QLabel(tr("Find &what:")); lineEdit = new QLineEdit; label->setBuddy(lineEdit); caseCheckBox = new QCheckBox(tr("Match &case")); backwardCheckBox = new QCheckBox(tr("Search &backward")); findButton = new QPushButton(tr("&Find")); findButton->setDefault(true); findButton->setEnabled(false); closeButton = new QPushButton(tr("Close")); connect(lineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(enableFindButton(const QString &))); connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked())); connect(closeButton, SIGNAL(clicked()), this, SLOT(close())); QHBoxLayout *topLeftLayout = new QHBoxLayout; topLeftLayout->addWidget(label); topLeftLayout->addWidget(lineEdit); QVBoxLayout *leftLayout = new QVBoxLayout; leftLayout->addLayout(topLeftLayout); leftLayout->addWidget(caseCheckBox); leftLayout->addWidget(backwardCheckBox); QVBoxLayout *rightLayout = new QVBoxLayout; rightLayout->addWidget(findButton); rightLayout->addWidget(closeButton); rightLayout->addStretch(); QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addLayout(leftLayout); mainLayout->addLayout(rightLayout); setLayout(mainLayout); setWindowTitle(tr("Find")); setFixedHeight(sizeHint().height()); } void FindDialog::findClicked(){ QString text = lineEdit->text(); Qt::CaseSensitivity cs = caseCheckBox->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive; if (backwardCheckBox->isChecked()) { emit findPrevious(text, cs); } else { emit findNext(text, cs); } } void FindDialog::enableFindButton(const QString &text) { findButton->setEnabled(!text.isEmpty()); }
[ "noreply@github.com" ]
noreply@github.com
bf51cb681d6caedbb2d3c5699b2e691e84fea68e
c270fe23c8e4aeca0d5ac4c64b84b32eb2c1d752
/copper/hpp/cast.hpp
b53e209ef2ca8e8bdeac7ce439eb4193cc734021
[ "MIT" ]
permissive
CobaltXII/sterling
25b326033ae33fc6390423d29fb428adc260f982
abef14ec8019aca55e359f78da5711c70be77d35
refs/heads/master
2020-04-30T12:23:27.285931
2019-03-24T19:22:36
2019-03-24T19:22:36
176,825,389
0
0
null
null
null
null
UTF-8
C++
false
false
1,346
hpp
float cast ( float ray_ox, float ray_oy, float ray_oz, float ray_dx, float ray_dy, float ray_dz, shape** hit_shape = NULL, float* hit_shape_r = NULL, float* hit_shape_g = NULL, float* hit_shape_b = NULL, float* norm_x = NULL, float* norm_y = NULL, float* norm_z = NULL, float* texture_u = NULL, float* texture_v = NULL, material_type* hit_shape_material = NULL ) { float temporary_norm_x; float temporary_norm_y; float temporary_norm_z; float temporary_texture_u; float temporary_texture_v; float min_dist = std::numeric_limits<float>::max(); for (int i = 0; i < shapes.size(); i++) { shape* shape1 = shapes[i]; float t = do_intersect ( ray_ox, ray_oy, ray_oz, ray_dx, ray_dy, ray_dz, &temporary_norm_x, &temporary_norm_y, &temporary_norm_z, &temporary_texture_u, &temporary_texture_v, &shape1 ); if (t > 0.0f && t < min_dist) { min_dist = t; set_ptr(hit_shape_material, shape1->material); set_ptr(hit_shape_r, shape1->r); set_ptr(hit_shape_g, shape1->g); set_ptr(hit_shape_b, shape1->b); set_ptr(hit_shape, shape1); set_ptr(norm_x, temporary_norm_x); set_ptr(norm_y, temporary_norm_y); set_ptr(norm_z, temporary_norm_z); set_ptr(texture_u, temporary_texture_u); set_ptr(texture_v, temporary_texture_v); } } return min_dist; }
[ "sidatt64@gmail.com" ]
sidatt64@gmail.com
0418bde4662b63daaa05572b219b06a66a6dd0b9
f5685a8bcc402e46e081f92137e6f26bd7d0ba3e
/docs/source/_src_snippets/simulation/environment_setup/environment_models/tabulated_ephemeris.cpp
e925382f860896370d11673b1074b8cb35d88b63
[]
no_license
MaartenvNistelrooij/tudat-space
d28d745e8b2cdd70b5e7df60c990459a23a0cc91
aa7cafff6bf0bcd4f1bda55cd1633c61719db749
refs/heads/master
2023-08-27T21:15:44.474114
2021-11-05T18:15:35
2021-11-05T18:15:35
421,984,329
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
std::map< double, Eigen::Vector6d > bodyStateHistory ... std::string frameOrigin = "SSB" std::string frameOrientation = "J2000" bodySettings[ "Jupiter" ]->ephemerisSettings = std::make_shared< TabulatedEphemerisSettings >( bodyStateHistory, frameOrigin, frameOrientation );
[ "aaron@Aarons-MBP.fritz.box" ]
aaron@Aarons-MBP.fritz.box
ca4c060d6238331034cbac144ed165b3ac9c8aef
9d03de321fe91c04147789a192f8354c57bcc6a4
/Objeto.cpp
d6a57ad00cd734880dda3090b18616564fb49760
[]
no_license
pequenyaheavy/Malvadisco
bbd69f2142798cfaa8f11659e805de796fab0590
6f14b81bfcad04d8229e0b20adf8c8ea713591f1
refs/heads/master
2023-02-15T00:51:16.600441
2015-04-22T19:11:11
2015-04-22T19:11:11
33,929,324
0
1
null
null
null
null
UTF-8
C++
false
false
198
cpp
/* * File: Objeto.cpp * Author: Juan * * Created on 14 de abril de 2015, 20:13 */ #include "Objeto.h" Objeto::Objeto() { } Objeto::Objeto(const Objeto& orig) { } Objeto::~Objeto() { }
[ "jcbarberadiaz@gmail.com" ]
jcbarberadiaz@gmail.com
6fa5d6fd47f704270b6ffaa0140fc004cad037c1
b9cea176542da3edf4f4da7594266a1f65b665c7
/src/W2/code/FPGA_EdgeBoard/sample_image_catdog/include/paddle-mobile/fpga/KD/llapi/zynqmp_api.h
4099bb23a301e21830d62d36d7c8da6829a9c542
[]
no_license
Heffie199/EdgeBoard_Experience
5ca89adbde338ed3540d12733c81f0490d1e1a33
4a8baa237b7f7b46b448bb9484e418763d757f17
refs/heads/master
2020-08-21T14:48:37.291540
2019-06-16T11:41:17
2019-06-16T11:41:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,805
h
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #ifndef PADDLE_MOBILE_SRC_FPGA_KD_ZYNQMP_API_H #define PADDLE_MOBILE_SRC_FPGA_KD_ZYNQMP_API_H #include <stdint.h> #include <cstddef> #include <iostream> #include <limits> namespace paddle_mobile { namespace zynqmp { typedef int16_t half; #define IMAGE_ALIGNMENT 16 // Aligned to 16 #define FILTER_NUM_ALIGNMENT 32 // Filter number aligned to 32 #define FILTER_ELEMENT_ALIGNMENT 16 // Filter element number aligned to 16 #define BS_NUM_ALIGNMENT 8 #define BIAS_NUM_ALIGNMENT 16 enum DDataType { DATA_TYPE_FP32 = 1, DATA_TYPE_FP16 = 0, }; enum DLayoutType { LAYOUT_CHW = 1, LAYOUT_HWC = 0, }; struct VersionArgs { void* buffer; }; struct MemoryCopyArgs { void* src; void* dest; size_t size; }; struct MemoryCacheArgs { void* address; size_t size; }; struct MemoryBarrierArgs {}; struct BNArgs { bool enabled; void* bias_address; void* scale_address; }; /** Conv and Pooling kernel */ struct KernelArgs { uint32_t width; uint32_t height; uint32_t stride_w; uint32_t stride_h; }; struct ImageInputArgs { void* address; // input featuremap virtual address void* scale_address; // input scale address; uint32_t channels; uint32_t width; // featuremap width uint32_t height; uint32_t pad_width; // padding width; uint32_t pad_height; }; struct ImageOutputArgs { void* address; // output result address; float* scale_address; // output scale address; }; struct ConvArgs { bool relu_enabled; void* sb_address; // scale and bias are interlaced; void* filter_address; void* filter_scale_address; uint32_t filter_num; uint32_t group_num; struct KernelArgs kernel; struct ImageInputArgs image; // input image; struct ImageOutputArgs output; }; struct DWconvArgs { bool relu_enabled; void* bias_address; void* filter_address; struct KernelArgs kernel; struct ImageInputArgs image; struct ImageOutputArgs output; uint16_t out_width; uint16_t out_height; uint16_t sub_conv_num; }; struct PoolingArgs { uint16_t mode; uint16_t kernel_reciprocal; struct KernelArgs kernel; struct ImageInputArgs image; // input image; struct ImageOutputArgs output; uint16_t out_width; uint16_t out_height; }; // elementwise add arguments struct EWAddArgs { bool relu_enabled; uint32_t const0; // output0 = const0 x input0 + const1 x input1; uint32_t const1; struct ImageInputArgs image0; struct ImageInputArgs image1; struct ImageOutputArgs output; }; struct BypassArgs { enum DDataType input_data_type; enum DDataType output_data_type; enum DLayoutType input_layout_type; enum DLayoutType output_layout_type; struct ImageInputArgs image; struct ImageOutputArgs output; }; struct ScaleArgs { void* scale_address; void* bias_address; uint32_t wc_alignment; uint32_t channel_alignment; struct ImageInputArgs image; struct ImageOutputArgs output; }; struct NormalizeArgs { void* input_image_address; void* output_image_address; uint32_t image_width; uint32_t image_height; uint32_t image_channel; uint32_t* output_scale_address; }; struct PowerParameterArgs { uint16_t shift; uint16_t scale; uint16_t power; }; struct NormalizeParameterArgs { uint32_t channel; uint32_t hight_width; }; struct ResizeArgs { void* input_image_address; void* output_image_address; uint32_t input_width; uint32_t input_height; uint32_t image_channel; uint32_t output_width; uint32_t output_height; uint32_t height_ratio; uint32_t width_ratio; uint32_t* output_scale_address; }; struct InplaceArgs { bool relu_enable; bool power_enable; bool normalize_enable; }; struct FpgaRegWriteArgs { uint64_t address; // uint64_t value; }; struct FpgaRegReadArgs { uint64_t address; uint64_t value; }; struct FpgaResetArgs {}; #define IOCTL_FPGA_MAGIC (('F' + 'P' + 'G' + 'A') / 4) #define IOCTL_VERSION _IOW(IOCTL_FPGA_MAGIC, 01, struct VersionArgs) #define IOCTL_SEPARATOR_0 10 #define IOCTL_MEM_COPY _IOW(IOCTL_FPGA_MAGIC, 11, struct MemoryCopyArgs) #define IOCTL_MEMCACHE_INVAL _IOW(IOCTL_FPGA_MAGIC, 12, struct MemoryCacheArgs) #define IOCTL_MEMCACHE_FLUSH _IOW(IOCTL_FPGA_MAGIC, 13, struct MemoryCacheArgs) #define IOCTL_MEMORY_BARRIER \ _IOW(IOCTL_FPGA_MAGIC, 14, struct MemoryBarrierArgs) #define IOCTL_SEPARATOR_1 20 #define IOCTL_CONFIG_CONV _IOW(IOCTL_FPGA_MAGIC, 21, struct ConvArgs) #define IOCTL_CONFIG_POOLING _IOW(IOCTL_FPGA_MAGIC, 22, struct PoolingArgs) #define IOCTL_CONFIG_EW _IOW(IOCTL_FPGA_MAGIC, 23, struct EWAddArgs) #define IOCTL_CONFIG_BYPASS _IOW(IOCTL_FPGA_MAGIC, 24, struct BypassArgs) #define IOCTL_CONFIG_SCALE _IOW(IOCTL_FPGA_MAGIC, 25, struct ScaleArgs) #define IOCTL_CONFIG_NORMALIZE _IOW(IOCTL_FPGA_MAGIC, 26, struct NormalizeArgs) #define IOCTL_CONFIG_RESIZE _IOW(IOCTL_FPGA_MAGIC, 30, struct ResizeArgs) #define IOCTL_CONFIG_DWCONV _IOW(IOCTL_FPGA_MAGIC, 31, struct DWconvArgs) #define IOCTL_CONFIG_INPLACE _IOW(IOCTL_FPGA_MAGIC, 40, struct InplaceArgs) #define IOCTL_CONFIG_POWER_PARAMETER \ _IOW(IOCTL_FPGA_MAGIC, 41, struct PowerParameterArgs) #define IOCTL_CONFIG_NORMALIZE_PARAMETER \ _IOW(IOCTL_FPGA_MAGIC, 42, struct NormalizeParameterArgs) #define IOCTL_FPGA_REG_READ _IOW(IOCTL_FPGA_MAGIC, 50, struct FpgaRegReadArgs) #define IOCTL_FPGA_REG_WRITE _IOW(IOCTL_FPGA_MAGIC, 51, struct FpgaRegWriteArgs) #define IOCTL_FPGA_RESET _IOW(IOCTL_FPGA_MAGIC, 52, struct FpgaResetArgs) //============================== API ============================= // struct DWconvArgs { // bool relu_enabled; // void* bias_address; // void* filter_address; // struct KernelArgs kernel; // struct ImageInputArgs image; // struct ImageOutputArgs output; // }; struct DeconvArgs { uint32_t sub_conv_num; uint32_t group_num; uint32_t filter_num; uint32_t omit_size; uint32_t sub_output_width; uint32_t sub_output_height; struct ImageOutputArgs output; struct SplitConvArgs* split_conv_args; }; struct SplitArgs { uint32_t image_num; int16_t* image_in; float* scale_in; void** images_out; float** scales_out; uint32_t* out_channel_nums; uint32_t height; uint32_t width; }; struct ConcatArgs { uint32_t image_num; half** images_in; float** scales_in; void* image_out; float* scale_out; uint32_t* channel_num; uint32_t height; uint32_t width; }; struct SplitConvArgs { uint32_t split_num; uint32_t group_num; uint32_t filter_num; struct ImageOutputArgs output; struct ConvArgs* conv_arg; struct ConcatArgs concat_arg; }; struct GroupConvArgs { uint32_t group_num; uint32_t filter_num; struct ImageOutputArgs output; struct SplitConvArgs* conv_args; struct ConcatArgs concat_arg; }; inline int align_to_x(int num, int x) { return (num + x - 1) / x * x; } int open_device(); void close_device(); void reset_device(); void* fpga_malloc(size_t size); void fpga_free(void* ptr); size_t fpga_get_memory_size(void* ptr); size_t fpga_get_memory_size_max(); size_t fpga_diagnose_memory(int detailed); void fpga_copy(void* dst, const void* src, int size); int fpga_flush(void* address, size_t size); int fpga_invalidate(void* address, size_t size); int perform_bypass(const struct BypassArgs& args); int compute_fpga_conv_basic(const struct ConvArgs& args); int compute_fpga_conv(const struct SplitConvArgs& args); int compute_fpga_pool(const struct PoolingArgs& args); int compute_fpga_ewadd(const struct EWAddArgs& args); int compute_fpga_scale(const struct ScaleArgs& args); int compute_fpga_concat(const struct ConcatArgs& args); int config_power(const struct PowerArgs& args); int compute_fpga_dwconv(const struct DWconvArgs& args); int config_norm_param(const struct NormalizeParameterArgs& args); int compute_norm(const struct NormalizeArgs& args); int compute_fpga_resize(const struct ResizeArgs& args); // int config_relu(const struct ReluArgs& args); int config_inplace(const struct InplaceArgs& args); int flush_cache(void* addr, int size); int invalidate_cache(void* addr, int size); int16_t fp32_2_fp16(float fp32_num); float fp16_2_fp32(int16_t fp16_num); } // namespace zynqmp } // namespace paddle_mobile #endif // PADDLE_MOBILE_SRC_FPGA_KD_ZYNQMP_API_H
[ "287827688@qq.com" ]
287827688@qq.com
148f045418ef1172d7b517361a132ce050a65800
6bc73bec189500f564332b0c4212cc057093fc43
/tests/no_repeated_types_in_component3_with_annotation.cpp
1d50397c89423128a8444f2cb6aeebd671df467d
[ "Apache-2.0" ]
permissive
preempt/fruit
0b0870fa465b27e4b082045ef1d2b373557dac3f
9ea3e31b63836797ec7ba1dd759ead8c00d0d227
refs/heads/master
2023-07-14T02:42:21.498680
2016-04-24T09:44:53
2016-04-24T09:44:53
72,961,655
0
0
Apache-2.0
2023-06-28T22:55:22
2016-11-06T00:35:43
C++
UTF-8
C++
false
false
1,084
cpp
// expect-compile-error RepeatedTypesError<fruit::Annotated<Annotation,X>,fruit::Annotated<Annotation,X>>|A type was specified more than once. /* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fruit/fruit.h> #include "test_macros.h" using fruit::Injector; using fruit::Component; using fruit::Required; using fruit::createComponent; struct Annotation {}; struct X { }; using XAnnot = fruit::Annotated<Annotation, X>; Component<Required<XAnnot>, XAnnot> getComponent() { return createComponent(); }
[ "poletti.marco@gmail.com" ]
poletti.marco@gmail.com
7e41182dcaacb5477215c55f11f017b72ea56726
6fc57553a02b485ad20c6e9a65679cd71fa0a35d
/src/cobalt/bin/system-metrics/memory_stats_fetcher.h
3db45611cab76b3f6e774059969c8baae7cebdb6
[ "BSD-3-Clause" ]
permissive
OpenTrustGroup/fuchsia
2c782ac264054de1a121005b4417d782591fb4d8
647e593ea661b8bf98dcad2096e20e8950b24a97
refs/heads/master
2023-01-23T08:12:32.214842
2019-08-03T20:27:06
2019-08-03T20:27:06
178,452,475
1
1
BSD-3-Clause
2023-01-05T00:43:10
2019-03-29T17:53:42
C++
UTF-8
C++
false
false
660
h
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_COBALT_BIN_SYSTEM_METRICS_MEMORY_STATS_FETCHER_H_ #define SRC_COBALT_BIN_SYSTEM_METRICS_MEMORY_STATS_FETCHER_H_ #include <lib/zx/resource.h> namespace cobalt { // An abstrace interface for memory stats fetching from various // resources class MemoryStatsFetcher { public: virtual ~MemoryStatsFetcher() = default; virtual bool FetchMemoryStats(zx_info_kmem_stats_t* mem_stats) = 0; }; } // namespace cobalt #endif // SRC_COBALT_BIN_SYSTEM_METRICS_MEMORY_STATS_FETCHER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
cd71a09dff7f748be469361c4651c3fd57404c46
c06574d4ddf1e2cab62737e8b74accea3c34007a
/Codeforces/Round 588/A.cpp
2a8a7f6d7fef959a1cafaedb4d2b813a24fbc97d
[]
no_license
t1war1/CP
5ec8210c37c54262cb8758647fe52c0fec402f35
237c8e32e351511142c4fd79bb965a4e8efa37b6
refs/heads/master
2022-12-21T11:03:14.300293
2020-04-10T11:06:24
2020-04-10T11:06:24
116,372,420
0
1
null
2020-10-01T20:37:31
2018-01-05T10:19:59
C++
UTF-8
C++
false
false
1,835
cpp
#include <bits/stdc++.h> #define pb push_back #define fastIO ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); #define PI 3.141592653589793238462643383 #define mp make_pair #define ff first #define ss second #define endl "\n" #define all(v) v.begin(),v.end() #define int long long using namespace std; typedef pair<int,int> pii; typedef pair<long double,long double>pdd; template<class T> using max_pq = priority_queue<T>; template<class T> using min_pq = priority_queue<T,vector<T>,greater<T> >; vector<string> split(const string& s, char c) { vector<string> v; stringstream ss(s); string x; while (getline(ss, x, c)) v.emplace_back(x); return move(v); } template<typename T, typename... Args> inline string arrStr(T arr, int n) { stringstream s; s << "["; for(int i = 0; i < n - 1; i++) s << arr[i] << ","; s << arr[n - 1] << "]"; return s.str(); } #define TRACE #ifdef TRACE #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define trace(...) #endif // const int N=; int32_t main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); freopen("debug.txt", "w", stderr); #endif fastIO; int a,b,c,d; cin>>a>>b>>c>>d; if((a+b==c+d)||(a+c==b+d)||(a+d==b+c)||(a==b+c+d)||(b==a+c+d)||(c==a+b+d)||(d==a+c+b)) { cout<<"YES"; } else { cout<<"NO"; } return 0; }
[ "tiwarigaurav1998@gmail.com" ]
tiwarigaurav1998@gmail.com
d5a9a40fbff858a033bb71d635b1298f325b0288
d2d4028ee83066400c53b7144ec416bff1fedc83
/ACM-UVA/694/694.cpp
8087c61b37e5217af7c00699ffd49e40aa030cc0
[]
no_license
sergarb1/Competitive-Programming-Solved-Problems
f822e3a11d8977e3bdacbe5e478055af792bdd0e
b33af9d6168a4acaf7f398d5e0598df99686e51a
refs/heads/master
2023-01-11T15:38:05.933581
2022-12-27T12:29:45
2022-12-27T12:29:45
137,689,428
5
12
null
null
null
null
UTF-8
C++
false
false
1,043
cpp
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <iostream> using namespace std; int main() { long long int i,j,k; #ifndef ONLINE_JUDGE close (0); open ("694.in", O_RDONLY); close (1); open ("694.out", O_WRONLY | O_CREAT, 0600); #endif long long int a,limit; long long int ntest=1; while(1) { long long int aor; cin >> a; cin >> limit; aor=a; long long int npasos=0; if(a==-1 && limit==-1) return 0; while(a!=1 && a<=limit) { npasos++; if(a%2==0) a/=2; else a=(3*a)+1; } if(a==1) npasos++; cout << "Case "<<ntest<<": A = "<<aor<<", limit = "<<limit<<", number of terms = "<<npasos<<endl; ntest++; } return 0; }
[ "sergi.profesor@gmail.com" ]
sergi.profesor@gmail.com
7fdb557617761771cb2d6e2358bfe9bc35efc871
11016ada61550f7d0316fd2bfabf05d8f103f10c
/dksorts/bubble_sort/bubble_sort_main.cc
2d153e6b0389b4c079828cd7ee6c1aadc3bcbc84
[]
no_license
DhruvKrish/CPP_DSA
530c37ff92ad4b7786405e52589eac1783bf5dec
11494f10e4f9db46b27c5d6a52177794bfaa93ac
refs/heads/master
2020-06-12T07:17:40.357386
2019-09-19T22:52:36
2019-09-19T22:52:36
194,229,775
0
0
null
null
null
null
UTF-8
C++
false
false
806
cc
#include <assert.h> #include "bubble_sort.h" int main(){ int to_sort[10] = {613, 55, 8721, 472, 94, 72, 74, 8, 61, 356}; int to_sort_recursive[10] = {613, 55, 8721, 472, 94, 72, 74, 8, 61, 356}; int sorted[10] = {8, 55, 61, 72, 74, 94, 356, 472, 613, 8721}; std::cout<<"To Sort: "; for(int i=0;i<10;i++){ std::cout<<to_sort[i]<<" "; } std::cout<<std::endl; dk::BubbleSort(to_sort, 10); dk::BubbleSortRecursive(to_sort_recursive,10); std::cout<<"Sorted: "; for(int i=0;i<10;i++){ std::cout<<to_sort[i]<<" "; } std::cout<<std::endl; std::cout<<"Recursive Sorted: "; for(int i=0;i<10;i++){ std::cout<<to_sort_recursive[i]<<" "; } std::cout<<std::endl; assert( std::equal(std::begin(to_sort), std::end(to_sort), std::begin(sorted))); return 0; }
[ "dhruvkrishnan@gmail.com" ]
dhruvkrishnan@gmail.com
4fd0a95b34ab387e25716450b8d05e810ab83c77
04afc8dc4ae6a0982e1e1725fe9413b14fc08200
/src/qt/eMarkgui.h
9f906650e41c04d6d845cb1bd86bbf9532f12574
[ "MIT" ]
permissive
CryptoManiac/DEM
65ec93eecf02ea47031c98a4d07db2c52380c529
edd45698c123b2195881f29c0b8592356ba171aa
refs/heads/master
2021-01-18T18:11:37.822041
2015-09-19T21:00:37
2015-09-19T21:00:37
42,783,371
0
0
null
2015-09-19T17:48:00
2015-09-19T17:47:59
null
UTF-8
C++
false
false
5,943
h
#ifndef BOUNTYCOINGUI_H #define BOUNTYCOINGUI_H #include <QMainWindow> #include <QSystemTrayIcon> #include "util.h" class TransactionTableModel; class ClientModel; class WalletModel; class TransactionView; class OverviewPage; class AddressBookPage; class SendCoinsDialog; class SignVerifyMessageDialog; class Notificator; class RPCConsole; QT_BEGIN_NAMESPACE class QLabel; class QLineEdit; class QTableView; class QAbstractItemModel; class QModelIndex; class QProgressBar; class QStackedWidget; class QUrl; QT_END_NAMESPACE /** eMark GUI main class. This class represents the main window of the eMark UI. It communicates with both the client and wallet models to give the user an up-to-date view of the current core state. */ class eMarkGUI : public QMainWindow { Q_OBJECT public: explicit eMarkGUI(QWidget *parent = 0); ~eMarkGUI(); /** Set the client model. The client model represents the part of the core that communicates with the P2P network, and is wallet-agnostic. */ void setClientModel(ClientModel *clientModel); /** Set the wallet model. The wallet model represents a eMark wallet, and offers access to the list of transactions, address book and sending functionality. */ void setWalletModel(WalletModel *walletModel); protected: void changeEvent(QEvent *e); void closeEvent(QCloseEvent *event); void dragEnterEvent(QDragEnterEvent *event); void dropEvent(QDropEvent *event); private: ClientModel *clientModel; WalletModel *walletModel; QStackedWidget *centralWidget; OverviewPage *overviewPage; QWidget *transactionsPage; AddressBookPage *addressBookPage; AddressBookPage *receiveCoinsPage; SendCoinsDialog *sendCoinsPage; SignVerifyMessageDialog *signVerifyMessageDialog; QLabel *labelEncryptionIcon; QLabel *labelStakingIcon; QLabel *labelConnectionsIcon; QLabel *labelBlocksIcon; QLabel *progressBarLabel; QProgressBar *progressBar; QMenuBar *appMenuBar; QAction *overviewAction; QAction *historyAction; QAction *quitAction; QAction *sendCoinsAction; QAction *addressBookAction; QAction *signMessageAction; QAction *verifyMessageAction; QAction *aboutAction; QAction *receiveCoinsAction; QAction *optionsAction; QAction *toggleHideAction; QAction *exportAction; QAction *encryptWalletAction; QAction *backupWalletAction; QAction *changePassphraseAction; QAction *unlockWalletAction; QAction *lockWalletAction; QAction *aboutQtAction; QAction *openRPCConsoleAction; QSystemTrayIcon *trayIcon; Notificator *notificator; TransactionView *transactionView; RPCConsole *rpcConsole; QMovie *syncIconMovie; uint64 nWeight; /** Create the main UI actions. */ void createActions(); /** Create the menu bar and sub-menus. */ void createMenuBar(); /** Create the toolbars */ void createToolBars(); /** Create system tray (notification) icon */ void createTrayIcon(); public slots: /** Set number of connections shown in the UI */ void setNumConnections(int count); /** Set number of blocks shown in the UI */ void setNumBlocks(int count, int nTotalBlocks); /** Set the encryption status as shown in the UI. @param[in] status current encryption status @see WalletModel::EncryptionStatus */ void setEncryptionStatus(int status); /** Notify the user of an error in the network or transaction handling code. */ void error(const QString &title, const QString &message, bool modal); /** Asks the user whether to pay the transaction fee or to cancel the transaction. It is currently not possible to pass a return value to another thread through BlockingQueuedConnection, so an indirected pointer is used. https://bugreports.qt-project.org/browse/QTBUG-10440 @param[in] nFeeRequired the required fee @param[out] payFee true to pay the fee, false to not pay the fee */ void askFee(qint64 nFeeRequired, bool *payFee); void handleURI(QString strURI); private slots: /** Switch to overview (home) page */ void gotoOverviewPage(); /** Switch to history (transactions) page */ void gotoHistoryPage(); /** Switch to address book page */ void gotoAddressBookPage(); /** Switch to receive coins page */ void gotoReceiveCoinsPage(); /** Switch to send coins page */ void gotoSendCoinsPage(); /** Show Sign/Verify Message dialog and switch to sign message tab */ void gotoSignMessageTab(QString addr = ""); /** Show Sign/Verify Message dialog and switch to verify message tab */ void gotoVerifyMessageTab(QString addr = ""); /** Show configuration dialog */ void optionsClicked(); /** Show about dialog */ void aboutClicked(); #ifndef Q_OS_MAC /** Handle tray icon clicked */ void trayIconActivated(QSystemTrayIcon::ActivationReason reason); #endif /** Show incoming transaction notification for new transactions. The new items are those between start and end inclusive, under the given parent item. */ void incomingTransaction(const QModelIndex & parent, int start, int end); /** Encrypt the wallet */ void encryptWallet(bool status); /** Backup the wallet */ void backupWallet(); /** Change encrypted wallet passphrase */ void changePassphrase(); /** Ask for passphrase to unlock wallet temporarily */ void unlockWallet(); void lockWallet(); /** Show window if hidden, unminimize when minimized, rise when obscured or show if hidden and fToggleHidden is true */ void showNormalIfMinimized(bool fToggleHidden = false); /** simply calls showNormalIfMinimized(true) for use in SLOT() macro */ void toggleHidden(); void updateWeight(); void updateStakingIcon(); }; #endif
[ "balthazar@yandex.ru" ]
balthazar@yandex.ru
1c58dd28a44c568232b955a4424326cb4be11ddf
f4279ff558845ac27b61467084ab81128e07a203
/Project1/Project1/array.h
b903b2534562231f12f9ae4269d7f65c833a08c6
[]
no_license
Serhii-elder/ClassWork
02d22ca0034fd4a89ffca82db0a825cc17843926
b296f7adb5dbd03b1e0be03fa9ec93b8418c9bc1
refs/heads/master
2020-05-25T03:31:35.598134
2019-10-08T09:04:21
2019-10-08T09:04:21
187,604,830
0
0
null
null
null
null
UTF-8
C++
false
false
221
h
#pragma once #include<iostream> using namespace std; class Array { private: int *arr; int size; int a; public: Array(); Array(int newValue,int newSize); void Print(); void AddFirst(); void DelIndex(); };
[ "dovmat@rivne.itstep.org" ]
dovmat@rivne.itstep.org
d201ed593682e9e7badb3e9807687bfef3804abf
bcd6c8aa8bba28c20bf2a23577718ce104804d06
/Gammou/Plugins/sampler.cpp
650fbdad35874c54689eb30dc5806e60a6c275ee
[ "BSD-3-Clause" ]
permissive
scrime-u-bordeaux/Gammou
26bacc74a4d47b0c734dc305edf22a5cbb91fb3b
07a109caace0a77772c78e891b3c8688737e3877
refs/heads/master
2020-04-24T05:51:28.025655
2019-01-21T21:19:08
2019-01-21T21:19:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,992
cpp
#include "plugin_helper.h" #include "wav.h" using namespace Gammou::Sound; class sampler_component : public sound_component { public: sampler_component( wav_t *sample, const unsigned int channel_count); ~sampler_component(); void process(const double input[]) override; void initialize_process() override; private: multi_channel_variable<double> m_current_pos; wav_t * m_sample; }; sampler_component::sampler_component( wav_t *sample, const unsigned int channel_count) : sound_component("sampler", 2, 1, channel_count), m_current_pos(this), m_sample(sample) { set_input_name("Speed", 0); set_input_name("Offset", 1); } sampler_component::~sampler_component() { wav_free(m_sample); } void sampler_component::initialize_process() { m_current_pos = 0.0; } void sampler_component::process(const double input[]) { const double pos = m_current_pos + input[1]; m_output[0] = wav_get_value(m_sample, pos, 0); m_current_pos += input[0] * get_sample_duration(); } class sampler_factory : public plugin_factory { public: sampler_factory() : plugin_factory("Sampler", "Sampler", sampler_id) {} ~sampler_factory() {} protected: std::unique_ptr<request_form> create_plugin_request_form() override { return create_request_form( request{"Sample", "", path_request{"wav"}}); } abstract_sound_component *create_sound_component( data_input_stream& source, const unsigned int channel_count) override { return nullptr; // todo } abstract_sound_component *create_sound_component( const answer_form& answer_form, const unsigned int channel_count) override { auto& answers = std::get<answer_list>(answer_form); const std::string& path = std::get<path_answer>(answers[0]).path; wav_t *sample = wav_load(path.c_str()); if (sample == nullptr) throw std::runtime_error("Unable to load " + path); return new sampler_component(sample, channel_count); } }; EXPORT_FACTORY(sampler_factory)
[ "aliefhooghe@enseirb-matmeca.fr" ]
aliefhooghe@enseirb-matmeca.fr
43856b74eb58339e2c0bb6fd296791666b7e2e38
f94ca9f5fd77d08442291909c89b3ecefe3bfb2b
/tests/stubs/notificationstatusindicator_stub.h
a03a4122035bdaac286bb88af62271867d4ed319
[]
no_license
dudochkin-victor/touch-systemui
d6921b371358a7428ac9c408789b03627ad08146
3a15ca779ebe41f091674c6b8c21d22eeac122b9
refs/heads/master
2021-01-15T16:17:27.083927
2013-05-16T06:35:27
2013-05-16T06:35:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,541
h
#ifndef NOTIFICATIONSTATUSINDICATOR_STUB #define NOTIFICATIONSTATUSINDICATOR_STUB #include "notificationstatusindicator.h" #include <stubbase.h> // 1. DECLARE STUB // FIXME - stubgen is not yet finished class NotificationStatusIndicatorStub : public StubBase { public: virtual void NotificationStatusIndicatorConstructor(QGraphicsItem *parent); virtual void NotificationStatusIndicatorDestructor(); virtual void setActive(bool active); }; // 2. IMPLEMENT STUB void NotificationStatusIndicatorStub::NotificationStatusIndicatorConstructor(QGraphicsItem *) { } void NotificationStatusIndicatorStub::NotificationStatusIndicatorDestructor() { } void NotificationStatusIndicatorStub::setActive(bool active) { QList<ParameterBase*> params; params.append( new Parameter<bool >(active)); stubMethodEntered("setActive",params); } // 3. CREATE A STUB INSTANCE NotificationStatusIndicatorStub gDefaultNotificationStatusIndicatorStub; NotificationStatusIndicatorStub* gNotificationStatusIndicatorStub = &gDefaultNotificationStatusIndicatorStub; // 4. CREATE A PROXY WHICH CALLS THE STUB NotificationStatusIndicator::NotificationStatusIndicator(QGraphicsItem *parent) { gNotificationStatusIndicatorStub->NotificationStatusIndicatorConstructor(parent); } NotificationStatusIndicator::~NotificationStatusIndicator() { gNotificationStatusIndicatorStub->NotificationStatusIndicatorDestructor(); } void NotificationStatusIndicator::setActive(bool active) { gNotificationStatusIndicatorStub->setActive(active); } #endif
[ "dudochkin.victor@gmail.com" ]
dudochkin.victor@gmail.com
bca08f9716ada9c9017eeb51ed7fb8ee7ace4b30
1cc17e9f4c3b6fba21aef3af5e900c80cfa98051
/chrome/browser/safe_browsing/safe_browsing_blocking_page.h
0f60da3a70d5377e655849bed347d84fa76be8e4
[ "BSD-3-Clause" ]
permissive
sharpglasses/BitPop
2643a39b76ab71d1a2ed5b9840217b0e9817be06
1fae4ecfb965e163f6ce154b3988b3181678742a
refs/heads/master
2021-01-21T16:04:02.854428
2013-03-22T02:12:27
2013-03-22T02:12:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,169
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Classes for managing the SafeBrowsing interstitial pages. // // When a user is about to visit a page the SafeBrowsing system has deemed to // be malicious, either as malware or a phishing page, we show an interstitial // page with some options (go back, continue) to give the user a chance to avoid // the harmful page. // // The SafeBrowsingBlockingPage is created by the SafeBrowsingService on the UI // thread when we've determined that a page is malicious. The operation of the // blocking page occurs on the UI thread, where it waits for the user to make a // decision about what to do: either go back or continue on. // // The blocking page forwards the result of the user's choice back to the // SafeBrowsingService so that we can cancel the request for the new page, or // or allow it to continue. // // A web page may contain several resources flagged as malware/phishing. This // results into more than one interstitial being shown. On the first unsafe // resource received we show an interstitial. Any subsequent unsafe resource // notifications while the first interstitial is showing is queued. If the user // decides to proceed in the first interstitial, we display all queued unsafe // resources in a new interstitial. #ifndef CHROME_BROWSER_SAFE_BROWSING_SAFE_BROWSING_BLOCKING_PAGE_H_ #define CHROME_BROWSER_SAFE_BROWSING_SAFE_BROWSING_BLOCKING_PAGE_H_ #include <map> #include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/time.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "content/public/browser/interstitial_page_delegate.h" #include "googleurl/src/gurl.h" class MalwareDetails; class MessageLoop; class SafeBrowsingBlockingPageFactory; namespace base { class DictionaryValue; } namespace content { class InterstitialPage; class WebContents; } class SafeBrowsingBlockingPage : public content::InterstitialPageDelegate { public: typedef std::vector<SafeBrowsingService::UnsafeResource> UnsafeResourceList; typedef std::map<content::WebContents*, UnsafeResourceList> UnsafeResourceMap; virtual ~SafeBrowsingBlockingPage(); // Shows a blocking page warning the user about phishing/malware for a // specific resource. // You can call this method several times, if an interstitial is already // showing, the new one will be queued and displayed if the user decides // to proceed on the currently showing interstitial. static void ShowBlockingPage( SafeBrowsingService* service, const SafeBrowsingService::UnsafeResource& resource); // Makes the passed |factory| the factory used to instanciate // SafeBrowsingBlockingPage objects. Usefull for tests. static void RegisterFactory(SafeBrowsingBlockingPageFactory* factory) { factory_ = factory; } // InterstitialPageDelegate method: virtual std::string GetHTMLContents() OVERRIDE; virtual void CommandReceived(const std::string& command) OVERRIDE; virtual void OverrideRendererPrefs( content::RendererPreferences* prefs) OVERRIDE; virtual void OnProceed() OVERRIDE; virtual void OnDontProceed() OVERRIDE; protected: friend class SafeBrowsingBlockingPageTest; FRIEND_TEST_ALL_PREFIXES(SafeBrowsingBlockingPageTest, ProceedThenDontProceed); void SetReportingPreference(bool report); // Don't instanciate this class directly, use ShowBlockingPage instead. SafeBrowsingBlockingPage(SafeBrowsingService* service, content::WebContents* web_contents, const UnsafeResourceList& unsafe_resources); // After a malware interstitial where the user opted-in to the // report but clicked "proceed anyway", we delay the call to // MalwareDetails::FinishCollection() by this much time (in // milliseconds), in order to get data from the blocked resource itself. int64 malware_details_proceed_delay_ms_; content::InterstitialPage* interstitial_page() const { return interstitial_page_; } private: FRIEND_TEST_ALL_PREFIXES(SafeBrowsingBlockingPageTest, MalwareReports); enum BlockingPageEvent { SHOW, PROCEED, DONT_PROCEED, }; // Fills the passed dictionary with the strings passed to JS Template when // creating the HTML. void PopulateMultipleThreatStringDictionary(base::DictionaryValue* strings); void PopulateMalwareStringDictionary(base::DictionaryValue* strings); void PopulatePhishingStringDictionary(base::DictionaryValue* strings); // A helper method used by the Populate methods above used to populate common // fields. void PopulateStringDictionary(base::DictionaryValue* strings, const string16& title, const string16& headline, const string16& description1, const string16& description2, const string16& description3); // Records a user action for this interstitial, using the form // SBInterstitial[Phishing|Malware|Multiple][Show|Proceed|DontProceed]. void RecordUserAction(BlockingPageEvent event); // Records the time it took for the user to react to the // interstitial. We won't double-count if this method is called // multiple times. void RecordUserReactionTime(const std::string& command); // Checks if we should even show the malware details option. For example, we // don't show it in incognito mode. bool CanShowMalwareDetailsOption(); // Called when the insterstitial is going away. If there is a // pending malware details object, we look at the user's // preferences, and if the option to send malware details is // enabled, the report is scheduled to be sent on the |sb_service_|. void FinishMalwareDetails(int64 delay_ms); // Returns the boolean value of the given |pref| from the PrefService of the // Profile associated with |web_contents_|. bool IsPrefEnabled(const char* pref); // A list of SafeBrowsingService::UnsafeResource for a tab that the user // should be warned about. They are queued when displaying more than one // interstitial at a time. static UnsafeResourceMap* GetUnsafeResourcesMap(); // Notifies the SafeBrowsingService on the IO thread whether to proceed or not // for the |resources|. static void NotifySafeBrowsingService(SafeBrowsingService* sb_service, const UnsafeResourceList& resources, bool proceed); // Returns true if the passed |unsafe_resources| is blocking the load of // the main page. static bool IsMainPageLoadBlocked( const UnsafeResourceList& unsafe_resources); friend class SafeBrowsingBlockingPageFactoryImpl; // For reporting back user actions. SafeBrowsingService* sb_service_; MessageLoop* report_loop_; // True if the interstitial is blocking the main page because it is on one // of our lists. False if a subresource is being blocked, or in the case of // client-side detection where the interstitial is shown after page load // finishes. bool is_main_frame_load_blocked_; // The index of a navigation entry that should be removed when DontProceed() // is invoked, -1 if not entry should be removed. int navigation_entry_index_to_remove_; // The list of unsafe resources this page is warning about. UnsafeResourceList unsafe_resources_; // A MalwareDetails object that we start generating when the // blocking page is shown. The object will be sent when the warning // is gone (if the user enables the feature). scoped_refptr<MalwareDetails> malware_details_; bool proceeded_; content::WebContents* web_contents_; GURL url_; content::InterstitialPage* interstitial_page_; // Owns us // Time when the interstitial was show. This variable is set in // GetHTMLContents() which is called right before the interstitial // is shown to the user. Will return is_null() once we reported the // user action. base::TimeTicks interstitial_show_time_; // True if the interstitial that is shown is a malware interstitial // and false if it's a phishing interstitial. If it's a multi-threat // interstitial we'll say it's malware. bool is_malware_interstitial_; // The factory used to instanciate SafeBrowsingBlockingPage objects. // Usefull for tests, so they can provide their own implementation of // SafeBrowsingBlockingPage. static SafeBrowsingBlockingPageFactory* factory_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingBlockingPage); }; // Factory for creating SafeBrowsingBlockingPage. Useful for tests. class SafeBrowsingBlockingPageFactory { public: virtual ~SafeBrowsingBlockingPageFactory() { } virtual SafeBrowsingBlockingPage* CreateSafeBrowsingPage( SafeBrowsingService* service, content::WebContents* web_contents, const SafeBrowsingBlockingPage::UnsafeResourceList& unsafe_resources) = 0; }; #endif // CHROME_BROWSER_SAFE_BROWSING_SAFE_BROWSING_BLOCKING_PAGE_H_
[ "vgachkaylo@crystalnix.com" ]
vgachkaylo@crystalnix.com
be5c36cde1e1e90a02700d1d19c039535eea1abe
9f9660f318732124b8a5154e6670e1cfc372acc4
/Case_save/Case20/case8/600/p
6ffbf51ce252d70438aad337b8e0fa1c1499fac5
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
4,907
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "600"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -2 0 0 0 0]; internalField nonuniform List<scalar> 459 ( 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101324 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101322 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101319 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101317 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101315 101312 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101313 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101310 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101308 101305 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101306 101304 101304 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101303 101304 101304 101304 101304 101304 101303 101303 101303 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101301 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 101299 ) ; boundaryField { floor { type zeroGradient; } ceiling { type zeroGradient; } sWall { type zeroGradient; } nWall { type zeroGradient; } sideWalls { type empty; } glass1 { type zeroGradient; } glass2 { type zeroGradient; } sun { type zeroGradient; } heatsource1 { type zeroGradient; } heatsource2 { type zeroGradient; } Table_master { type zeroGradient; } Table_slave { type zeroGradient; } inlet { type zeroGradient; } outlet { type fixedValue; value uniform 101325; } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
c59caabf3f1eeb20e3d5addfed10465d450419bb
9dfc68af6c2c010a31ff9d3418ccab2f221da448
/compat/defs.hpp
585c45d10cfa2b57197249f3db4bd6c065a6249c
[ "BSL-1.0" ]
permissive
sthalik/floormat
0180219c1a73d89d891d00b0330e154125c109db
125cb3c0feb94e51b830957fb44ccc709b6afa61
refs/heads/master
2023-08-16T12:40:27.569715
2023-07-22T16:56:19
2023-07-22T19:17:41
460,774,854
4
0
null
null
null
null
UTF-8
C++
false
false
2,664
hpp
#pragma once #ifdef _MSC_VER # define fm_FUNCTION_NAME __FUNCSIG__ #else # define fm_FUNCTION_NAME __PRETTY_FUNCTION__ #endif #define fm_begin(...) [&]{__VA_ARGS__}() #define fm_DECLARE_DEPRECATED_COPY_ASSIGNMENT(type) \ [[deprecated, maybe_unused]] type(const type&) noexcept = default; \ [[deprecated, maybe_unused]] type& operator=(const type&) noexcept = default #define fm_DECLARE_DEFAULT_COPY_ASSIGNMENT(type) \ [[maybe_unused]] constexpr type(const type&) noexcept = default; \ [[maybe_unused]] constexpr type& operator=(const type&) noexcept = default #define fm_DECLARE_DEFAULT_COPY_ASSIGNMENT_(type) \ [[maybe_unused]] type(const type&) noexcept = default; \ [[maybe_unused]] type& operator=(const type&) noexcept = default #define fm_DECLARE_DELETED_COPY_ASSIGNMENT(type) \ type(const type&) = delete; \ type& operator=(const type&) = delete #define fm_DECLARE_DELETED_MOVE_ASSIGNMENT(type) \ type(type&&) = delete; \ type& operator=(type&&) = delete #define fm_DECLARE_DEPRECATED_MOVE_ASSIGNMENT(type) \ [[deprecated, maybe_unused]] type(type&&) = default; \ [[deprecated, maybe_unused]] type& operator=(type&&) = default #define fm_DECLARE_DEFAULT_MOVE_ASSIGNMENT(type) \ [[maybe_unused]] constexpr type(type&&) noexcept = default; \ [[maybe_unused]] constexpr type& operator=(type&&) noexcept = default #define fm_DECLARE_DEFAULT_MOVE_ASSIGNMENT_(type) \ [[maybe_unused]] type(type&&) noexcept = default; \ [[maybe_unused]] type& operator=(type&&) noexcept = default #define fm_DECLARE_DEFAULT_MOVE_COPY_ASSIGNMENTS(type) \ [[maybe_unused]] fm_DECLARE_DEFAULT_MOVE_ASSIGNMENT(type); \ [[maybe_unused]] fm_DECLARE_DEFAULT_COPY_ASSIGNMENT(type) #define fm_DECLARE_DEFAULT_MOVE_COPY_ASSIGNMENTS_(type) \ [[maybe_unused]] fm_DECLARE_DEFAULT_MOVE_ASSIGNMENT_(type); \ [[maybe_unused]] fm_DECLARE_DEFAULT_COPY_ASSIGNMENT_(type) #ifdef _MSC_VER # define fm_noinline __declspec(noinline) #else # define fm_noinline __attribute__((noinline)) #endif
[ "sthalik@misaki.pl" ]
sthalik@misaki.pl
5177061130a1662bbb1f6730e861890ddf5a7da5
7eec7414b7bb45e5a1d70e577788de88693bf755
/Computing_III/Exc5_Point/Point.h
ee1994c8f5147f5d2be47709255c50fa700a3b97
[]
no_license
SPKB24/UML_Courses
7cc6b6a71d82ebe2f5d00e5d31d7f4691bf103ca
d54b031333618cfbf8eb7ef8dd01f79a9806ddf9
refs/heads/master
2021-01-18T22:58:21.397492
2016-06-25T03:14:16
2016-06-25T03:14:16
42,747,675
1
0
null
null
null
null
UTF-8
C++
false
false
845
h
#ifndef POINT_H #define POINT_H #include <iostream> using namespace std; class Point { public: // Default Constructor Point(int _dimension = 2); // Int and Array Constructor Point(int _dimension, double *_array); // Copy Constructor Point(const Point& rhs); // Operator() double operator[] (size_t index); // Assignment Operator Point& operator=(const Point& arg); // Addition Operator Point operator+(const Point &arg); // Sum Equals operator Point &operator+=(const Point &arg); // Print out all coordinates in the point void printAll(); // Destructor ~Point(); friend ostream & operator<<(ostream &output, const Point &arg) { for (int i = 0; i < arg.dimension; i++) cout << "Point " << i << " = " << arg.coordinates[i] << endl; return cout; } private: double *coordinates; int dimension; }; #endif
[ "sohitpal@outlook.com" ]
sohitpal@outlook.com
d1f76c57c7be87c57a31e716c8b81c9a81a4655a
6c133a78b9d22dce340376fb0df41eb760ffc7b0
/breath/diagnostics/assert.hpp
35cabd62216ee6ec79897f101b7c6515ebfa847e
[ "BSD-3-Clause" ]
permissive
seekaddo/breath
0620f09e98964f0cec18d0851256a780f968a57c
0795e1e0be88ac992ae9eaf0411bf732fdf83042
refs/heads/master
2022-12-04T23:57:51.381938
2020-08-24T08:49:23
2020-08-24T09:03:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,024
hpp
// =========================================================================== // Copyright 2006-2010 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ // //! \file //! \brief A basic assertion facility. // --------------------------------------------------------------------------- #ifndef BREATH_GUARD_k8gjtzbloTDgF7FRM6AWORSGsE1IHkXq #define BREATH_GUARD_k8gjtzbloTDgF7FRM6AWORSGsE1IHkXq #include "breath/top_level_namespace.hpp" namespace breath_ns { //! \cond implementation namespace assert_private { template< typename T > void block_non_bools( T ) = delete ; inline constexpr bool block_non_bools( bool b ) { return b ; } [[ noreturn ]] void fire( char const * expression_text, char const * file_name, unsigned long line_number ) noexcept ; } //! \endcond } // BREATH_ASSERT(): // ================ // //! \hideinitializer //! //! %BREATH_ASSERT() is a simple runtime assertion facility. //! Differently from the standard \c assert(), it has always the //! same expansion (regardless of \c NDEBUG). //! //! The code <code>BREATH_ASSERT( expr )</code> expands to an //! expression, let's call it \c assert_expr, which contains \c expr //! as a sub-expression. //! //! \c expr must have type bool or cv-qualified bool (this is a //! change from the past: we used to accept anything implicitly or //! explicitly convertible to bool; which means that e.g. \c expr //! could be the name of a \c std::optional---we think the new //! specification is safer). //! //! When \c assert_expr is evaluated: if \c expr is \c false, an //! assertion is triggered; if it is \c true, the evaluation of \c //! assert_expr has no effects besides the evaluation of the //! sub-expression \c expr. //! //! In this context, "triggering an assertion" means writing //! information related to the specific macro invocation (e.g. line //! number and source file name) to \c std::cerr, then flushing \c //! std::cerr, then calling \c std::abort(). //! //! Rationale //! --------- //! //! It has become "common practice" to define the macro \c NDEBUG //! when compiling the "release" version of code. Many IDEs do so //! silently. In fact, \c NDEBUG (or a logical complement of it, //! such as \c _DEBUG) has become the macro which is usually checked //! for by your library code to know which version of it //! (release/debug) you want to link with. //! //! We believe, though, that assertions must be left on in the //! release version of the product. So we wanted an assert macro //! decoupled from \c NDEBUG. (Thinking of it, there has been a //! fatal misunderstanding: the C committee thought of a macro to //! enable/disable assertions, but alas named it "NDEBUG", which //! suggests "no debug". And that's the meaning everyone seems to //! have assigned to it. Had they called it e.g. "NASSERT" all this //! wouldn't probably have happened.) // --------------------------------------------------------------------------- #define BREATH_ASSERT( expression ) \ ( \ breath::assert_private::block_non_bools( expression ) \ ? static_cast< void >( 0 ) \ : breath::assert_private::fire( # expression, __FILE__, __LINE__ ) \ ) /**/ #endif // Local Variables: // mode: c++ // indent-tabs-mode: nil // c-basic-offset: 4 // End: // vim: set ft=cpp et sts=4 sw=4:
[ "gennaro.prota+github@gmail.com" ]
gennaro.prota+github@gmail.com
d386de4e8f5088cfe63486354a3ffe2a7f97fc2f
2a5da186c8f903e1b35f4b2975b9832ae97aba0f
/BB-8/PagMaterial.h
a7571ce9d5f9649313f3817e7a747296bdf8e8b3
[]
no_license
ManuJGQ/BB-8
ac2001bfe8a92b3df22aeb9ded2fd80de0f7812b
b9b0dd5beec9b689fbe531c136a9d3ffed2bc452
refs/heads/master
2021-01-12T06:02:05.474283
2017-01-10T13:28:03
2017-01-10T13:28:03
77,277,936
0
0
null
null
null
null
UTF-8
C++
false
false
374
h
#pragma once #include <GL/glew.h> //glew SIEMPRE va antes del glfw #include <GLFW/glfw3.h> #include "gtc\matrix_transform.hpp" class PagMaterial{ glm::vec3 Ka; glm::vec3 Kd; public: PagMaterial(); PagMaterial(glm::vec3 _Ka, glm::vec3 _Kd); PagMaterial(const PagMaterial &orig); glm::vec3 getKa() { return Ka; } glm::vec3 getKd() { return Kd; } ~PagMaterial(); };
[ "manueljgq@gmail.com" ]
manueljgq@gmail.com
8c2c526708271b972bfb6afe2965e4535a0bcab7
05dddc9e12d11363a43e5581841a20e2ffa46c37
/BeeMaja/main.cpp
692e36afc0e8634ea5acf578761949003cfb32bd
[]
no_license
jcconnol/Programming-Challanges-Probs
2d98e891d63dfe5070b1b316ba5dfedd4c294ff7
4d4fec55c9c35da68b1ccab63f291d65a5f5f604
refs/heads/master
2020-04-04T17:32:36.634163
2018-11-10T19:21:16
2018-11-10T19:21:16
156,124,898
0
0
null
null
null
null
UTF-8
C++
false
false
1,984
cpp
/* * File: main.cpp * Author: John Connolly * * Created on April 14, 2018, 11:19 AM */ #include <cstdlib> #include <sstream> #include <iostream> #include <ios> #include <cstdio> #include <stdio.h> #include <string> #include <vector> #include <algorithm> #include <map> using namespace std; struct coord{ int x; int y; }; map<int, coord> mapping; void addToMap(int x, int y, int ring){ coord holder; holder.x = x; holder.y = y; mapping[ring] = holder; } void findingAndAdding(int input){ int ring = 1; int count = 0; while(ring < input){ count++; ring += 6*count; } int x = count; int y = 0; while(ring != input){ while(ring != input && y+count != 0){ addToMap(x, y, ring); y--,ring--; } while(ring != input && x != 0){ //addToMap(x, y, ring); x--,ring--; } while(ring != input && y != 0){ addToMap(x, y, ring); x--; y++; ring--; } while(ring != input && y != count){ addToMap(x, y, ring); y++; ring--; } while(ring != input && x != 0){ addToMap(x, y, ring); x++; ring--; } while(ring != input && x != count){ addToMap(x, y, ring); x++; y--; ring--; } } addToMap(x, y, ring); } int main(int argc, char** argv) { int input; while(scanf("%d", &input) != EOF){ if(mapping.count(input) > 0){ cout << mapping[input].x << " " << mapping[input].y << endl; } else{ findingAndAdding(input); //for (map<int,coord>::iterator it=mapping.begin(); it!=mapping.end(); ++it) // cout << it->first << " => " << it->second.x << " " << it->second.y << '\n'; cout << mapping[input].x << " " << mapping[input].y << endl; } } return 0; }
[ "jcconnol4@gmail.com" ]
jcconnol4@gmail.com
982dd51b438d8fa6df85ed1577cf0187fa66fd39
7a9ab3a236ecf4b2eddb6c4fe4c0c0c333a0fb26
/src/controller/include/property_base_handler.h
750795d3eac58330f88fb8b6e0ace00f8907847a
[ "Apache-2.0" ]
permissive
AO-StreetArt/CLyman
d7f2f434551a724c62ea6b80318028992ba2d1ef
b4f3c6fce1c41fb47a6a9d89bb40c05466d0d092
refs/heads/v2
2021-01-24T06:47:20.703805
2019-04-27T01:51:24
2019-04-27T01:51:24
55,323,959
1
0
NOASSERTION
2019-04-17T05:22:39
2016-04-03T01:20:47
C++
UTF-8
C++
false
false
8,102
h
/* Apache2 License Notice Copyright 2017 Alex Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This implements the Configuration Manager // This takes in a Command Line Interpreter, and based on the options provided, // decides how the application needs to be configured. It may configure either // from a configuration file, or from a Consul agent #include <iostream> #include <boost/cstdint.hpp> #include "app/include/clyman_utils.h" #include "app/include/event_sender.h" #include "app/include/cluster_manager.h" #include "db/include/db_manager_interface.h" #include "model/property/include/property_interface.h" #include "model/list/include/property_list_interface.h" #include "model/factory/include/json_factory.h" #include "model/factory/include/data_list_factory.h" #include "model/factory/include/data_factory.h" #include "clyman_handler.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #ifndef SRC_CONTROLLER_INCLUDE_PROPERTY_BASE_HANDLER_H_ #define SRC_CONTROLLER_INCLUDE_PROPERTY_BASE_HANDLER_H_ class PropertyBaseRequestHandler: public ClymanHandler, public Poco::Net::HTTPRequestHandler { std::string object_id; void process_create_message(PropertyInterface* in_doc, PropertyInterface* out_doc, PropertyListInterface *response_body) { // Persist the creation message std::string new_object_key; logger.information("Creating Property with Name: " + in_doc->get_name()); DatabaseResponse response; db_manager->create_property(response, in_doc, new_object_key); if (response.success) { out_doc->set_key(new_object_key); } else { response_body->set_error_code(PROCESSING_ERROR); response_body->set_error_message(response.error_message); } } void process_update_message(PropertyInterface* in_doc, PropertyListInterface *response_body) { // Persist the update message logger.information("Updating Property with Name: " + in_doc->get_name()); DatabaseResponse response; std::string key = in_doc->get_key(); db_manager->update_property(response, in_doc, key); if (!(response.success)) { if (response.error_code > NO_ERROR) { response_body->set_error_code(response.error_code); } else { response_body->set_error_code(PROCESSING_ERROR); } response_body->set_error_message(response.error_message); } } void process_query_message(PropertyInterface* in_doc, PropertyListInterface *response_body, int max_results) { logger.information("Processing Query Message"); // Execute the query message and build a result db_manager->property_query(response_body, in_doc, max_results); } public: PropertyBaseRequestHandler(AOSSL::KeyValueStoreInterface *conf, DatabaseManagerInterface *db, \ EventStreamPublisher *pub, ClusterManager *cluster, int mtype) : ClymanHandler(conf, db, pub, cluster, mtype) {} PropertyBaseRequestHandler(AOSSL::KeyValueStoreInterface *conf, DatabaseManagerInterface *db, \ EventStreamPublisher *pub, ClusterManager *cluster, int mtype, std::string id) : ClymanHandler(conf, db, pub, cluster, mtype) { object_id.assign(id); } void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response) { logger.debug("Responding to Property Request"); // parse the post input data into a Scene List rapidjson::Document doc; char *tmpStr = clyman_request_body_to_json_document(request, doc); PropertyListInterface *response_body = object_list_factory.build_json_property_list(); ClymanHandler::init_response(response, response_body); if (doc.HasParseError()) { logger.debug("Parsing Error Detected"); // Set up parse error response response.setStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); response_body->set_error_code(TRANSLATION_ERROR); response_body->set_error_message(rapidjson::GetParseError_En(doc.GetParseError())); std::ostream& ostr = response.send(); std::string response_body_string; response_body->to_msg_string(response_body_string); ostr << response_body_string; ostr.flush(); } else { // Convert the rapidjson doc to a scene list response.setStatus(Poco::Net::HTTPResponse::HTTP_OK); PropertyListInterface *inp_doc = nullptr; try { inp_doc = json_factory.build_property_list(doc); } catch (std::exception& e) { logger.error("Exception encountered building Property List"); logger.error(e.what()); response_body->set_error_code(TRANSLATION_ERROR); response_body->set_error_message(e.what()); } if (inp_doc) { // update the message type and process the post input data inp_doc->set_msg_type(msg_type); // Process the input objects // send downstream updates, and persist the result for (int i = 0; i < inp_doc->num_props(); i++) { // Add to the output message list PropertyInterface *new_out_doc = object_factory.build_property(); // get the object out of the input message list PropertyInterface* in_doc = inp_doc->get_prop(i); if (!(object_id.empty())) in_doc->set_key(object_id); // Execute the Mongo Queries try { if (msg_type == PROP_CRT) { process_create_message(in_doc, new_out_doc, response_body); response_body->add_prop(new_out_doc); } else if (msg_type == PROP_UPD) { process_update_message(in_doc, response_body); } else if (msg_type == PROP_QUERY) { process_query_message(in_doc, response_body, inp_doc->get_num_records()); } } catch (std::exception& e) { logger.error("Exception encountered during DB Operation"); response_body->set_error_message(e.what()); logger.error(response_body->get_error_message()); response_body->set_error_code(PROCESSING_ERROR); break; } // Send an update to downstream services if (msg_type == PROP_CRT || msg_type == PROP_UPD) { AOSSL::ServiceInterface *downstream = cluster_manager->get_ivan(); if (downstream) { std::string transform_str; in_doc->to_json(transform_str, msg_type); std::string message = in_doc->get_scene() + \ std::string("\n") + transform_str; logger.debug("Sending Event: " + message); publisher->publish_event(message.c_str(), \ downstream->get_address(), stoi(downstream->get_port())); } } } } if (response_body->get_error_code() == NOT_FOUND) { response.setStatus(Poco::Net::HTTPResponse::HTTP_NOT_FOUND); } else if (response_body->get_error_code() == TRANSLATION_ERROR) { response.setStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); } else if (response_body->get_error_code() != NO_ERROR) { response.setStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR); } // Set up the response std::ostream& ostr = response.send(); // Process the result std::string response_body_string; response_body->to_msg_string(response_body_string); ostr << response_body_string; ostr.flush(); delete inp_doc; } delete response_body; delete[] tmpStr; } }; #endif // SRC_CONTROLLER_INCLUDE_PROPERTY_BASE_HANDLER_H_
[ "aostreetart9@gmail.com" ]
aostreetart9@gmail.com
1fe6852f23d2152aacc2f75e9c659e8052e9a06c
747d050f06d7a0c8a224fcca64b2415dc501ae40
/src/Pyramid.cpp
8363fc48d56418a11dd96dd928fbf711700cf834
[]
no_license
Provmawn/Neuro
be4c3d8ab21443d0e9d69cad7edc2ba06471ae3e
dcdf15060c0a0fdd70be2f4d7e1ccb5797d1db97
refs/heads/master
2023-04-28T08:33:24.265965
2021-05-28T00:57:20
2021-05-28T00:57:20
353,966,689
0
0
null
null
null
null
UTF-8
C++
false
false
729
cpp
#include "Pyramid.h" #include <utility> // The Mesh class takes a std::vector of indices and vertices but this pyramid class // has an std::array of indices and vertices // so this constructor turns the std::array into a std::vector in the base class Pyramid::Pyramid(const glm::vec3 &position) : Mesh(std::move(std::vector<unsigned int>(s_indices.begin(), s_indices.end())) , std::move(std::vector<float>(s_vertices.begin(), s_vertices.end()))) , degrees(rand()) { m_position = position; } // this is a transform void Pyramid::Transform() { //++degrees; m_model_matrix = glm::translate(m_model_matrix, m_position); //m_model_matrix = glm::rotate(m_model_matrix, glm::radians(degrees), glm::vec3(1.0f, 0.0f, 0.0f)); }
[ "provmawn@gmail.com" ]
provmawn@gmail.com
fbd60e8cd29ba415c8dde4120a5c9046ae17b308
337186a71e9077bb7900c713b799ce2dfb0246a6
/newcoder/小白鼠排队(按序输出字符串)/Untitled2.cpp
c7e57a8bc8f8af25ba920fd52bdbc56d52a8c8cf
[]
no_license
L1B0/Algorithm-Training
907b388a8c7704bd25b6f00282671c79da822a43
ed6c35e9a3bb0b6200bf8d85c643043fc03f203a
refs/heads/master
2022-05-07T10:10:05.438550
2022-04-28T06:55:56
2022-04-28T06:55:56
195,180,189
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
#include<stdio.h> #include<string.h> char color[101][11]={0}; int main() { int n; while(scanf("%d",&n)!=EOF) { for(int i=0;i<n;i++) { int a; scanf("%d",&a); scanf("%s",color[a]); } for(int i=100;i>=0;i--) { if(strlen(color[i]) > 0) puts(color[i]); } } return 0;
[ "noreply@github.com" ]
noreply@github.com
bd04b421e4f130a83bf27013ee6290d592e77ec2
6f949d729afffa5efc9f548bbfb58cdef3779d68
/University/cse 330/factorization of a number.cpp
f5aa861e4a0ee157eb4672814c5004424c955645
[]
no_license
barjinderpaul/Programming
ce02ad97d5fae968172ca397c483cc539a4b83f1
e48f4825cbe90f28e173f27071e5b0dd8740a8ff
refs/heads/master
2020-08-04T07:13:41.479369
2019-11-16T09:16:34
2019-11-16T09:16:34
212,045,826
0
0
null
null
null
null
UTF-8
C++
false
false
194
cpp
#include<bits/stdc++.h> using namespace std; int factors(int n){ for(int i=1;i<=n;i++){ if(n%i==0) cout<<i<<" "; } } int main(){ int n; cin>>n; cout<<"Factors: " ; factors(n); }
[ "barjinderpaul.singh@gmail.com" ]
barjinderpaul.singh@gmail.com
e8c87d5fa6539305961e417f77a02638d3d2c894
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/components/sync/engine_impl/js_sync_encryption_handler_observer.cc
1be24de8bc8fdec75ec66cf763466b145291261b
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
4,099
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync/engine_impl/js_sync_encryption_handler_observer.h" #include <cstddef> #include "base/location.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "components/sync/base/cryptographer.h" #include "components/sync/base/model_type.h" #include "components/sync/base/time.h" #include "components/sync/engine/sync_string_conversions.h" #include "components/sync/js/js_event_details.h" #include "components/sync/js/js_event_handler.h" namespace syncer { JsSyncEncryptionHandlerObserver::JsSyncEncryptionHandlerObserver() {} JsSyncEncryptionHandlerObserver::~JsSyncEncryptionHandlerObserver() {} void JsSyncEncryptionHandlerObserver::SetJsEventHandler( const WeakHandle<JsEventHandler>& event_handler) { event_handler_ = event_handler; } void JsSyncEncryptionHandlerObserver::OnPassphraseRequired( PassphraseRequiredReason reason, const sync_pb::EncryptedData& pending_keys) { if (!event_handler_.IsInitialized()) { return; } base::DictionaryValue details; details.SetString("reason", PassphraseRequiredReasonToString(reason)); HandleJsEvent(FROM_HERE, "onPassphraseRequired", JsEventDetails(&details)); } void JsSyncEncryptionHandlerObserver::OnPassphraseAccepted() { if (!event_handler_.IsInitialized()) { return; } base::DictionaryValue details; HandleJsEvent(FROM_HERE, "onPassphraseAccepted", JsEventDetails(&details)); } void JsSyncEncryptionHandlerObserver::OnBootstrapTokenUpdated( const std::string& boostrap_token, BootstrapTokenType type) { if (!event_handler_.IsInitialized()) { return; } base::DictionaryValue details; details.SetString("bootstrapToken", "<redacted>"); details.SetString("type", BootstrapTokenTypeToString(type)); HandleJsEvent(FROM_HERE, "onBootstrapTokenUpdated", JsEventDetails(&details)); } void JsSyncEncryptionHandlerObserver::OnEncryptedTypesChanged( ModelTypeSet encrypted_types, bool encrypt_everything) { if (!event_handler_.IsInitialized()) { return; } base::DictionaryValue details; details.Set("encryptedTypes", ModelTypeSetToValue(encrypted_types)); details.SetBoolean("encryptEverything", encrypt_everything); HandleJsEvent(FROM_HERE, "onEncryptedTypesChanged", JsEventDetails(&details)); } void JsSyncEncryptionHandlerObserver::OnEncryptionComplete() { if (!event_handler_.IsInitialized()) { return; } base::DictionaryValue details; HandleJsEvent(FROM_HERE, "onEncryptionComplete", JsEventDetails()); } void JsSyncEncryptionHandlerObserver::OnCryptographerStateChanged( Cryptographer* cryptographer) { if (!event_handler_.IsInitialized()) { return; } base::DictionaryValue details; details.SetBoolean("ready", cryptographer->is_ready()); details.SetBoolean("hasPendingKeys", cryptographer->has_pending_keys()); HandleJsEvent(FROM_HERE, "onCryptographerStateChanged", JsEventDetails(&details)); } void JsSyncEncryptionHandlerObserver::OnPassphraseTypeChanged( PassphraseType type, base::Time explicit_passphrase_time) { if (!event_handler_.IsInitialized()) { return; } base::DictionaryValue details; details.SetString("passphraseType", PassphraseTypeToString(type)); details.SetInteger("explicitPassphraseTime", TimeToProtoTime(explicit_passphrase_time)); HandleJsEvent(FROM_HERE, "onPassphraseTypeChanged", JsEventDetails(&details)); } void JsSyncEncryptionHandlerObserver::OnLocalSetPassphraseEncryption( const SyncEncryptionHandler::NigoriState& nigori_state) {} void JsSyncEncryptionHandlerObserver::HandleJsEvent( const base::Location& from_here, const std::string& name, const JsEventDetails& details) { if (!event_handler_.IsInitialized()) { NOTREACHED(); return; } event_handler_.Call(from_here, &JsEventHandler::HandleJsEvent, name, details); } } // namespace syncer
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
59f27101e3ce11403691ec6bd5d63a99c958d36c
6468a3ff2e16cfd0222daad9eb5609ba692c1a61
/Validation/validate_fclk/validate_fclk.ino
17acb72871c3ddec75ce5fa03b086e59a7e585bd
[ "MIT" ]
permissive
mattgaidica/ARBO_Arduino
81ccd0511b95dfb62eecafcf9c448e31936bdadd
3b9226f0fbd7fee7d4bde5f824aba7d8ceb337fc
refs/heads/master
2020-05-30T02:27:05.411478
2020-01-31T21:10:30
2020-01-31T21:10:30
189,497,672
0
0
null
null
null
null
UTF-8
C++
false
false
1,093
ino
void setup() { pinMode(LED_BUILTIN, OUTPUT); clock_init(); } uint8_t i=0; void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(100); digitalWrite(LED_BUILTIN, LOW); delay(100); } void clock_init(void) { // from: https://forum.arduino.cc/index.php?topic=420611.0 REG_GCLK_GENCTRL = GCLK_GENCTRL_OE | // Enable the GCLK output GCLK_GENCTRL_IDC | // Set the duty cycle to 50/50 HIGH/LOW GCLK_GENCTRL_GENEN | // Enable GCLK 4 GCLK_GENCTRL_SRC_XOSC32K | // Set the clock source to the external 32.768kHz GCLK_GENCTRL_ID(2); // Set clock source on GCLK 4 while (GCLK->STATUS.bit.SYNCBUSY); // Wait for synchronization // Enable the port multiplexer on digital pin 6 PORT->Group[g_APinDescription[11].ulPort].PINCFG[g_APinDescription[11].ulPin].bit.PMUXEN = 1; // Switch the port multiplexer to peripheral H (GCLK_IO[4]) PORT->Group[g_APinDescription[11].ulPort].PMUX[g_APinDescription[11].ulPin >> 1].reg |= PORT_PMUX_PMUXE_H; }
[ "matt@gaidi.ca" ]
matt@gaidi.ca
bd750db7f571ad73bffdeaac39d49cb8816d35e4
cadbcb41ce04389a9b095308243407f029aa04a0
/EnemyManager.cpp
b7443661bb8959cee3b594432c4fc63c4aed447e
[]
no_license
hugo0345/Gamebuino-SuperSpaceShooter
db3f84d4055e85cac1bcc7e1fa3d5031bcef859f
c7617580f9a0eb38f2c084e28a1dbdc81515cbac
refs/heads/master
2021-01-17T07:38:48.961387
2014-07-27T11:47:09
2014-07-27T11:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,213
cpp
/* * File: EnemyManager.cpp * Author: Michael * * Created on 22 July 2014, 12:05 */ #include "EnemyManager.h" extern Gamebuino gb; EnemyManager::EnemyManager() { } EnemyManager::~EnemyManager() { } void EnemyManager::update(){ for(int8_t i = 0; i < MAX_ENEMIES; i++){ if(!enemies[i].isDead()){ enemies[i].update(); enemies[i].draw(); } } } void EnemyManager::createEnemy(int8_t x, int8_t y, ENEMY_TYPE type){ // not terribly efficient way to find an dead enemy int8_t i = 0; while(!enemies[i].isDead() && i < MAX_ENEMIES-1){ i++; } enemies[i].init(x, y, type); } bool EnemyManager::TestShot(int8_t x1, int8_t y1, int8_t x2, int8_t y2, int8_t x3, int8_t y3){ HitBox hb; for(uint8_t i = 0; i< MAX_ENEMIES; i++){ if(!enemies[i].isDead()){ hb = enemies[i].getCollisionBox(); if( gb.collidePointRect(x3,y3,hb.x,hb.y,hb.w,hb.h)|| gb.collidePointRect(x2,y2,hb.x,hb.y,hb.w,hb.h)|| gb.collidePointRect(x1,y1,hb.x,hb.y,hb.w,hb.h) ){ enemies[i].hit(); return true; } } } return false; }
[ "michael@sledgend.net" ]
michael@sledgend.net
c8b4c7bc355d4e92406fbbe641a00dd1ea0c7a80
2fcc9ad89cf0c85d12fa549f969973b6f4c68fdc
/SampleGraphics/Castle/Castle.cpp
049cabc17965fcc27fa28bc0b5863af17e5ded18
[ "BSL-1.0" ]
permissive
nmnghjss/WildMagic
9e111de0a23d736dc5b2eef944f143ca84e58bc0
b1a7cc2140dde23d8d9a4ece52a07bd5ff938239
refs/heads/master
2022-04-22T09:01:12.909379
2013-05-13T21:28:18
2013-05-13T21:28:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,189
cpp
// Geometric Tools, LLC // Copyright (c) 1998-2012 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.1.1 (2012/07/04) #include "Castle.h" WM5_WINDOW_APPLICATION(Castle); //---------------------------------------------------------------------------- Castle::Castle () : WindowApplication3("SampleGraphics/Castle", 0, 0, 800, 600, Float4(0.6f, 0.851f, 0.918f, 1.0f)), mTextColor(1.0f, 1.0f, 1.0f, 1.0f) { Environment::InsertDirectory(ThePath + "Geometry/"); Environment::InsertDirectory(ThePath + "Shaders/"); Environment::InsertDirectory(ThePath + "Textures/"); mPickMessage[0] = 0; mVerticalDistance = 5.0f; // Generate pick ray information. mNumRays = 5; mHalfAngle = 0.25f*Mathf::PI; mCos = new1<float>(mNumRays); mSin = new1<float>(mNumRays); mTolerance = new1<float>(mNumRays); float mult = 1.0f/(mNumRays/2); for (int i = 0; i < mNumRays; ++i) { float unit = i*mult - 1.0f; // in [-1,1] float angle = Mathf::HALF_PI + mHalfAngle*unit; mCos[i] = Mathf::Cos(angle); mSin[i] = Mathf::Sin(angle); mTolerance[i] = 2.0f - 1.5f*Mathf::FAbs(unit); // in [1/2,1] } } //---------------------------------------------------------------------------- Castle::~Castle () { delete1(mCos); delete1(mSin); delete1(mTolerance); } //---------------------------------------------------------------------------- bool Castle::OnInitialize () { if (!WindowApplication3::OnInitialize()) { return false; } mCamera->SetFrustum(45.0f, GetAspectRatio(), 1.0f, 44495.0f); CreateScene(); mScene->Update(); // Center-and-fit the scene. The hard-coded center/position are based // on a priori knowledge of the data set. APoint worldCenter(1.3778250f,-0.70154405f,2205.9973f); mTrnNode->LocalTransform.SetTranslate(-worldCenter); APoint camPosition(527.394f, 86.8992f, -2136.00f); AVector camDVector(1.0f, 0.0f, 0.0f); AVector camUVector(0.0f, 0.0f, 1.0f); AVector camRVector = camDVector.Cross(camUVector); mCamera->SetFrame(camPosition, camDVector, camUVector, camRVector); mScene->Update(); mCuller.SetCamera(mCamera); mCuller.ComputeVisibleSet(mScene); InitializeCameraMotion(0.5f, 0.001f); InitializeObjectMotion(mScene); MoveForward(); return true; } //---------------------------------------------------------------------------- void Castle::OnTerminate () { mPicker.Records.clear(); mScene = 0; mTrnNode = 0; mWireState = 0; mDLightRoot = 0; mDLight = 0; mOutWallMaterial = 0; mStoneMaterial = 0; mRiverMaterial = 0; mWallMaterial = 0; mStairsMaterial = 0; mInteriorMaterial = 0; mDoorMaterial = 0; mFloorMaterial = 0; mWoodCeilingMaterial = 0; mKeystoneMaterial = 0; mDrawBridgeMaterial = 0; mRoofMaterial = 0; mRampMaterial = 0; mWoodShieldMaterial = 0; mTorchHolderMaterial = 0; mTorchWoodMaterial = 0; mTorchHeadMaterial = 0; mBarrelBaseMaterial = 0; mBarrelMaterial = 0; mDoorFrameMaterial = 0; mBunkMaterial = 0; mBlanketMaterial = 0; mBenchMaterial = 0; mTableMaterial = 0; mBarrelRackMaterial = 0; mChestMaterial = 0; mLightwoodMaterial = 0; mMaterial26 = 0; mRopeMaterial = 0; mSquareTableMaterial = 0; mSimpleChairMaterial = 0; mMugMaterial = 0; mPortMaterial = 0; mSkyMaterial = 0; mWaterMaterial = 0; mGravel1Material = 0; mGravel2Material = 0; mGravelCornerNEMaterial = 0; mGravelCornerNWMaterial = 0; mGravelCornerSEMaterial = 0; mGravelCornerSWMaterial = 0; mGravelCapNEMaterial = 0; mGravelCapNWMaterial = 0; mGravelSideNMaterial = 0; mGravelSideSMaterial = 0; mGravelSideWMaterial = 0; mStone1Material = 0; mStone2Material = 0; mStone3Material = 0; mLargeStone1Material = 0; mLargerStone1Material = 0; mLargerStone2Material = 0; mLargestStone1Material = 0; mLargestStone2Material = 0; mHugeStone1Material = 0; mHugeStone2Material = 0; mOutWall = 0; mStone = 0; mRiver = 0; mWall = 0; mWallLightMap = 0; mSteps = 0; mDoor = 0; mFloor = 0; mWoodCeiling = 0; mKeystone = 0; mTilePlanks = 0; mRoof = 0; mRamp = 0; mShield = 0; mMetal = 0; mTorchWood = 0; mTorchHead = 0; mBarrelBase = 0; mBarrel = 0; mDoorFrame = 0; mBunkwood = 0; mBlanket = 0; mBench = 0; mTable = 0; mBarrelRack = 0; mChest = 0; mLightwood = 0; mRope = 0; mSquareTable = 0; mSimpleChair = 0; mMug = 0; mPort = 0; mSky = 0; mWater = 0; mGravel1 = 0; mGravel2 = 0; mGravelCornerNE = 0; mGravelCornerNW = 0; mGravelCornerSE = 0; mGravelCornerSW = 0; mGravelCapNE = 0; mGravelCapNW = 0; mGravelSideN = 0; mGravelSideS = 0; mGravelSideW = 0; mStone1 = 0; mStone2 = 0; mStone3 = 0; mLargeStone1 = 0; mLargerStone1 = 0; mLargerStone2 = 0; mLargestStone1 = 0; mLargestStone2 = 0; mHugeStone1 = 0; mHugeStone2 = 0; mWoodShieldMesh = 0; mTorchMetalMesh = 0; mTorchWoodMesh = 0; mTorchHeadMesh = 0; mVerticalSpoutMesh = 0; mHorizontalSpoutMesh = 0; mBarrelHolderMesh = 0; mBarrelMesh = 0; mDoorFrame01Mesh = 0; mDoorFrame53Mesh = 0; mDoorFrame61Mesh = 0; mDoorFrame62Mesh = 0; WindowApplication3::OnTerminate(); } //---------------------------------------------------------------------------- void Castle::OnIdle () { MeasureTime(); if (MoveCamera()) { mCuller.ComputeVisibleSet(mScene); } if (MoveObject()) { mScene->Update(); mCuller.ComputeVisibleSet(mScene); } if (mRenderer->PreDraw()) { mRenderer->ClearBuffers(); mRenderer->Draw(mCuller.GetVisibleSet()); DrawFrameRate(8, GetHeight()-8, mTextColor); if (mPickMessage[0]) { mRenderer->Draw(8, 16, mTextColor, mPickMessage); } mRenderer->PostDraw(); mRenderer->DisplayColorBuffer(); } UpdateFrameCount(); } //---------------------------------------------------------------------------- bool Castle::OnKeyDown (unsigned char key, int x, int y) { if (WindowApplication3::OnKeyDown(key, x, y)) { return true; } switch (key) { case 'w': case 'W': mWireState->Enabled = !mWireState->Enabled; return true; case '+': case '=': mVerticalDistance += 0.1f; AdjustVerticalDistance(); return true; case '-': case '_': mVerticalDistance -= 0.1f; AdjustVerticalDistance(); return true; } return false; } //---------------------------------------------------------------------------- bool Castle::OnMouseClick (int, int state, int x, int y, unsigned int) { if (state != MOUSE_DOWN && state != MOUSE_LEFT_BUTTON) { return false; } // Do a picking operation. APoint pos; AVector dir; if (mRenderer->GetPickRay(x, GetHeight() - 1 - y, pos, dir)) { mPicker.Execute(mScene, pos, dir, 0.0f, Mathf::MAX_REAL); if (mPicker.Records.size() > 0) { // Display the selected object's name. const PickRecord& record = mPicker.GetClosestNonnegative(); const Spatial* object = record.Intersected; sprintf(mPickMessage, "%s", object->GetName().c_str()); } else { mPickMessage[0] = 0; } } return true; } //---------------------------------------------------------------------------- void Castle::AdjustVerticalDistance () { // Retain vertical distance above "ground". APoint pos = mCamera->GetPosition(); AVector dir = -AVector::UNIT_Z; mPicker.Execute(mScene, pos, dir, 0.0f, Mathf::MAX_REAL); if (mPicker.Records.size() > 0) { const PickRecord& record = mPicker.GetClosestNonnegative(); TriMesh* mesh = DynamicCast<TriMesh>(record.Intersected); APoint tri[3]; mesh->GetWorldTriangle(record.Triangle, tri); APoint closest = record.Bary[0]*tri[0] + record.Bary[1]*tri[1] + record.Bary[2]*tri[2]; closest[2] += mVerticalDistance; mCamera->SetPosition(closest); } } //---------------------------------------------------------------------------- bool Castle::AllowMotion (float sign) { // Take a step forward or backward, depending on sign. Check if objects // are far enough away. If so take the step. If not, stay where you are. APoint pos = mCamera->GetPosition() + sign*mTrnSpeed*mWorldAxis[0] - 0.5f*mVerticalDistance*mWorldAxis[1]; for (int i = 0; i < mNumRays; ++i) { AVector dir = mCos[i]*mWorldAxis[2] + sign*mSin[i]*mWorldAxis[0]; mPicker.Execute(mScene, pos, dir, 0.0f, Mathf::MAX_REAL); if (mPicker.Records.size() > 0) { const PickRecord& record = mPicker.GetClosestNonnegative(); if (record.T <= mTolerance[i]) { return false; } } } return true; } //---------------------------------------------------------------------------- void Castle::MoveForward () { if (AllowMotion(1.0f)) { WindowApplication3::MoveForward(); AdjustVerticalDistance(); } } //---------------------------------------------------------------------------- void Castle::MoveBackward () { if (AllowMotion(-1.0f)) { WindowApplication3::MoveBackward(); AdjustVerticalDistance(); } } //---------------------------------------------------------------------------- void Castle::CreateScene () { mScene = new0 Node(); mTrnNode = new0 Node(); mScene->AttachChild(mTrnNode); mWireState = new0 WireState(); mRenderer->SetOverrideWireState(mWireState); CreateLights(); CreateEffects(); CreateTextures(); CreateSharedMeshes(); CreateWallTurret02(); CreateWallTurret01(); CreateWall02(); CreateWall01(); CreateQuadPatch01(); CreateMainGate01(); CreateMainGate(); CreateExterior(); CreateFrontHall(); CreateFrontRamp(); CreateDrawBridge(); CreateCylinder02(); CreateBridge(); CreateLargePort(); CreateSmallPort(1); CreateSmallPort(2); CreateRope(1); CreateRope(2); int i; for (i = 1; i <= 7; ++i) { CreateWoodShield(i); } for (i = 1; i <= 17; ++i) { CreateTorch(i); } for (i = 1; i <= 3; ++i) { CreateKeg(i); } for (i = 2; i <= 37; ++i) { CreateBarrel(i); } for (i = 1; i <= 48; ++i) { CreateDoorFrame(i); } for (i = 49; i <= 60; ++i) { CreateDoorFramePivotTrn(i); } CreateDoorFrame(61); CreateDoorFrameScalePivotTrn(62); CreateDoorFrameScalePivotTrn(63); for (i = 64; i <= 68; ++i) { CreateDoorFrame(i); } for (i = 69; i <= 78; ++i) { CreateDoorFramePivotTrn(i); } CreateDoorFrame(79); CreateDoorFrameScalePivotTrn(80); CreateDoorFrameScalePivotTrn(81); CreateDoorFramePivotTrn(82); CreateDoorFramePivotTrn(83); CreateDoorFramePivotTrn(73); CreateBunk(1); for (i = 4; i <= 20; ++i) { CreateBunk(i); } for (i = 1; i <= 36; ++i) { CreateBench(i); } for (i = 1; i <= 9; ++i) { CreateTable(i); } for (i = 1; i <= 4; ++i) { CreateBarrelRack(i); } for (i = 1; i <= 36; ++i) { CreateChest(i); } for (i = 1; i <= 3; ++i) { CreateCeilingLight(i); } for (i = 1; i <= 7; ++i) { CreateSquareTable(i); } for (i = 1; i <= 27; ++i) { CreateSimpleChair(i); } for (i = 1; i <= 42; ++i) { CreateMug(i); } for (i = 1; i <= 9; ++i) { CreateDoor(i); } CreateTerrain(); CreateSkyDome(); CreateWater(); CreateWater2(); } //---------------------------------------------------------------------------- void Castle::CreateLights () { mDLight = new0 Light(Light::LT_DIRECTIONAL); mDLight->Ambient = Float4(1.0f, 1.0f, 1.0f, 1.0f); mDLight->Diffuse = Float4(1.0f, 1.0f, 1.0f, 1.0f); mDLight->Specular = Float4(1.0f, 1.0f, 1.0f, 1.0f); LightNode* lightNode = new0 LightNode(mDLight); lightNode->LocalTransform.SetTranslate(APoint(1628.448730f, -51.877197f, 0.0f)); lightNode->LocalTransform.SetRotate(HMatrix(AVector(-1.0f, 0.0f, 0.0f), Mathf::HALF_PI)); mDLightRoot = new0 Node(); mDLightRoot->LocalTransform.SetTranslate(APoint(-1824.998657f, -1531.269775f, 3886.592773f)); mDLightRoot->LocalTransform.SetRotate(HMatrix(AVector(-0.494124f, 0.325880f, 0.806005f), 1.371538f)); mDLightRoot->AttachChild(lightNode); mDLightRoot->Update(); } //---------------------------------------------------------------------------- void Castle::CreateEffects () { std::string name = Environment::GetPathR("DLitMatTex.wmfx"); mDLitMatTexEffect = new0 DLitMatTexEffect(name); mDLitMatTexAlphaEffect = new0 DLitMatTexEffect(name); mDLitMatTexAlphaEffect->GetAlphaState(0, 0)->BlendEnabled = true; mTexEffect = new0 Texture2DEffect(Shader::SF_LINEAR_LINEAR, Shader::SC_REPEAT, Shader::SC_REPEAT); mMatEffect = new0 MaterialEffect(); Material* common0 = new0 Material(); common0->Emissive = Float4(0.0f, 0.0f, 0.0f, 1.0f); common0->Ambient = Float4(0.588235f, 0.588235f, 0.588235f, 1.0f); common0->Diffuse = Float4(0.0f, 0.0f, 0.0f, 1.0f); common0->Specular = Float4(0.0f, 0.0f, 0.0f, 2.0f); Material* common1 = new0 Material(); common1->Emissive = Float4(0.0f, 0.0f, 0.0f, 1.0f); common1->Ambient = Float4(0.213070f, 0.183005f, 0.064052f, 1.0f); common1->Diffuse = Float4(0.0f, 0.0f, 0.0f, 1.0f); common1->Specular = Float4(0.045f, 0.045f, 0.045f, 5.656854f); Material* water = new0 Material(); water->Emissive = Float4(0.0f, 0.0f, 0.0f, 1.0f); water->Ambient = Float4(0.088888f, 0.064052f, 0.181698f, 1.0f); water->Diffuse = Float4(0.0f, 0.0f, 0.0f, 1.0f); water->Specular = Float4(0.045f, 0.045f, 0.045f, 5.656854f); Material* roofsteps = new0 Material(); roofsteps->Emissive = Float4(0.0f, 0.0f, 0.0f, 1.0f); roofsteps->Ambient = Float4(0.1f, 0.1f, 0.1f, 1.0f); roofsteps->Diffuse = Float4(0.0f, 0.0f, 0.0f, 1.0f); roofsteps->Specular = Float4(0.045f, 0.045f, 0.045f, 5.656854f); // diffuse channel is outwall03.wmtf mOutWallMaterial = common1; // diffuse channel is stone01.wmtf mStoneMaterial = common1; // diffuse channel is river01.wmtf (has alpha) mRiverMaterial = water; // emissive channel is walllightmap.wmtf // diffuse channel is wall02.wmtf mWallMaterial = common1; // emissive channel is walllightmap.wmtf // diffuse channel is steps.wmtf mStairsMaterial = roofsteps; // diffuse channel is outwall03.wmtf mInteriorMaterial = common1; // emissive channel is walllightmap.wmtf // diffuse channel is door.wmtf mDoorMaterial = common0; // emissive channel is walllightmap.wmtf // diffuse channel is floor02.wmtf mFloorMaterial = common0; // emissive channel is walllightmap.wmtf // diffuse channel is woodceiling.wmtf mWoodCeilingMaterial = common0; // diffuse channel is keystone.wmtf mKeystoneMaterial = common1; // diffuse channel is tileplanks.wmtf mDrawBridgeMaterial = common1; // diffuse channel is rooftemp.wmtf mRoofMaterial = roofsteps; // diffuse channel is ramp03.wmtf mRampMaterial = common1; // diffuse channel is shield01.wmtf mWoodShieldMaterial = common1; // diffuse channel is metal01.wmtf mTorchHolderMaterial = new0 Material(); mTorchHolderMaterial->Emissive = Float4(0.0f, 0.0f, 0.0f, 1.0f); mTorchHolderMaterial->Ambient = Float4(0.213070f, 0.183005f, 0.064052f, 1.0f); mTorchHolderMaterial->Diffuse = Float4(0.0f, 0.0f, 0.0f, 1.0f); mTorchHolderMaterial->Specular = Float4(0.216f, 0.216f, 0.216f, 11.313708f); // diffuse channel is torchwood.wmtf mTorchWoodMaterial = common1; // emissive channel is torchhead.tga (same as .wmtf ???) // diffuse channel is torchhead.wmtf mTorchHeadMaterial = common0; // diffuse channel is barrelbase.wmtf mBarrelBaseMaterial = common0; // diffuse channel is barrelbase.wmtf mBarrelMaterial = common0; // emissive channel is walllightmap.wmtf // diffuse channel is doorframe.wmtf mDoorFrameMaterial = common1; // diffuse channel is bunkwood.wmtf mBunkMaterial = common1; // diffuse channel is blanket.wmtf mBlanketMaterial = common0; // diffuse channel is bunkwood.wmtf mBenchMaterial = common0; // diffuse channel is bunkwood.wmtf mTableMaterial = common0; mBarrelRackMaterial = mDrawBridgeMaterial; // diffuse channel is chest01.wmtf mChestMaterial = common1; // diffuse channel is tileplanks.wmtf mLightwoodMaterial = common1; // part of ceiling lights mMaterial26 = new0 Material(); mMaterial26->Emissive = Float4(0.0f, 0.0f, 0.0f, 1.0f); mMaterial26->Ambient = Float4(0.588235f, 0.588235f, 0.588235f, 1.0f); mMaterial26->Diffuse = Float4(0.588235f, 0.588235f, 0.588235f, 1.0f); mMaterial26->Specular = Float4(0.0f, 0.0f, 0.0f, 2.0f); // diffuse channel is rope.wmtf mRopeMaterial = common0; // diffuse channel is rope.wmtf mSquareTableMaterial = common0; mSimpleChairMaterial = mDrawBridgeMaterial; // diffuse channel is mug.wmtf mMugMaterial = common0; // diffuse channel is port.wmtf mPortMaterial = common1; // diffuse channel is skyline.wmtf mSkyMaterial = common0; // diffuse channel is river02.wmtf (has alpha) mWaterMaterial = water; // TERRAIN // diffuse channel is gravel01.wmtf mGravel1Material = common1; // diffuse channel is gravel02.wmtf mGravel2Material = common1; // diffuse channel is gravel_corner_ne.wmtf mGravelCornerNEMaterial = common1; // diffuse channel is gravel_corner_nw.wmtf mGravelCornerNWMaterial = common1; // diffuse channel is gravel_corner_se.wmtf mGravelCornerSEMaterial = common1; // diffuse channel is gravel_corner_sw.wmtf mGravelCornerSWMaterial = common1; // diffuse channel is gravel_cap_ne.wmtf mGravelCapNEMaterial = common1; // diffuse channel is gravel_cap_nw.wmtf mGravelCapNWMaterial = common1; // diffuse channel is gravel_side_n.wmtf mGravelSideNMaterial = common1; // diffuse channel is gravel_side_s.wmtf mGravelSideSMaterial = common1; // diffuse channel is gravel_side_w.wmtf mGravelSideWMaterial = common1; // diffuse channel is stone01.wmtf mStone1Material = common1; // diffuse channel is stone02.wmtf mStone2Material = common1; // diffuse channel is stone03.wmtf mStone3Material = common1; // diffuse channel is largestone01.wmtf mLargeStone1Material = common1; // diffuse channel is largerstone01.wmtf mLargerStone1Material = common1; // diffuse channel is largerstone02.wmtf mLargerStone2Material = common1; // diffuse channel is largeststone01.wmtf mLargestStone1Material = common1; // diffuse channel is largeststone02.wmtf mLargestStone2Material = common1; // diffuse channel is hugestone01.wmtf mHugeStone1Material = common1; // diffuse channel is hugestone02.wmtf mHugeStone2Material = common1; } //---------------------------------------------------------------------------- void Castle::CreateTextures () { std::string name = Environment::GetPathR("outwall03.wmtf"); mOutWall = Texture2D::LoadWMTF(name); mOutWall->GenerateMipmaps(); name = Environment::GetPathR("stone01.wmtf"); mStone = Texture2D::LoadWMTF(name); mStone->GenerateMipmaps(); name = Environment::GetPathR("river01.wmtf"); mRiver = Texture2D::LoadWMTF(name); mRiver->GenerateMipmaps(); name = Environment::GetPathR("wall02.wmtf"); mWall = Texture2D::LoadWMTF(name); mWall->GenerateMipmaps(); name = Environment::GetPathR("walllightmap.wmtf"); mWallLightMap = Texture2D::LoadWMTF(name); mWallLightMap->GenerateMipmaps(); name = Environment::GetPathR("steps.wmtf"); mSteps = Texture2D::LoadWMTF(name); mSteps->GenerateMipmaps(); name = Environment::GetPathR("door.wmtf"); mDoor = Texture2D::LoadWMTF(name); mDoor->GenerateMipmaps(); name = Environment::GetPathR("floor02.wmtf"); mFloor = Texture2D::LoadWMTF(name); mFloor->GenerateMipmaps(); name = Environment::GetPathR("woodceiling.wmtf"); mWoodCeiling = Texture2D::LoadWMTF(name); mWoodCeiling->GenerateMipmaps(); name = Environment::GetPathR("keystone.wmtf"); mKeystone = Texture2D::LoadWMTF(name); mKeystone->GenerateMipmaps(); name = Environment::GetPathR("tileplanks.wmtf"); mTilePlanks = Texture2D::LoadWMTF(name); mTilePlanks->GenerateMipmaps(); name = Environment::GetPathR("rooftemp.wmtf"); mRoof = Texture2D::LoadWMTF(name); mRoof->GenerateMipmaps(); name = Environment::GetPathR("ramp03.wmtf"); mRamp = Texture2D::LoadWMTF(name); mRamp->GenerateMipmaps(); name = Environment::GetPathR("shield01.wmtf"); mShield = Texture2D::LoadWMTF(name); mShield->GenerateMipmaps(); name = Environment::GetPathR("metal01.wmtf"); mMetal = Texture2D::LoadWMTF(name); mMetal->GenerateMipmaps(); name = Environment::GetPathR("torchwood.wmtf"); mTorchWood = Texture2D::LoadWMTF(name); mTorchWood->GenerateMipmaps(); name = Environment::GetPathR("torchhead.wmtf"); mTorchHead = Texture2D::LoadWMTF(name); mTorchHead->GenerateMipmaps(); name = Environment::GetPathR("barrelbase.wmtf"); mBarrelBase = Texture2D::LoadWMTF(name); mBarrelBase->GenerateMipmaps(); name = Environment::GetPathR("barrel.wmtf"); mBarrel = Texture2D::LoadWMTF(name); mBarrel->GenerateMipmaps(); name = Environment::GetPathR("doorframe.wmtf"); mDoorFrame = Texture2D::LoadWMTF(name); mDoorFrame->GenerateMipmaps(); name = Environment::GetPathR("bunkwood.wmtf"); mBunkwood = Texture2D::LoadWMTF(name); mBunkwood->GenerateMipmaps(); name = Environment::GetPathR("blanket.wmtf"); mBlanket = Texture2D::LoadWMTF(name); mBlanket->GenerateMipmaps(); mBench = mBunkwood; mTable = mBunkwood; mBarrelRack = mTilePlanks; name = Environment::GetPathR("chest01.wmtf"); mChest = Texture2D::LoadWMTF(name); mChest->GenerateMipmaps(); mLightwood = mTilePlanks; name = Environment::GetPathR("rope.wmtf"); mRope = Texture2D::LoadWMTF(name); mRope->GenerateMipmaps(); mSquareTable = mTilePlanks; mSimpleChair = mTilePlanks; name = Environment::GetPathR("mug.wmtf"); mMug = Texture2D::LoadWMTF(name); mMug->GenerateMipmaps(); name = Environment::GetPathR("port.wmtf"); mPort = Texture2D::LoadWMTF(name); mPort->GenerateMipmaps(); name = Environment::GetPathR("skyline.wmtf"); mSky = Texture2D::LoadWMTF(name); mSky->GenerateMipmaps(); name = Environment::GetPathR("river02.wmtf"); mWater = Texture2D::LoadWMTF(name); mWater->GenerateMipmaps(); // TERRAIN name = Environment::GetPathR("gravel01.wmtf"); mGravel1 = Texture2D::LoadWMTF(name); mGravel1->GenerateMipmaps(); name = Environment::GetPathR("gravel02.wmtf"); mGravel2 = Texture2D::LoadWMTF(name); mGravel2->GenerateMipmaps(); name = Environment::GetPathR("gravel_corner_se.wmtf"); mGravelCornerSE = Texture2D::LoadWMTF(name); mGravelCornerSE->GenerateMipmaps(); name = Environment::GetPathR("gravel_corner_ne.wmtf"); mGravelCornerNE = Texture2D::LoadWMTF(name); mGravelCornerNE->GenerateMipmaps(); name = Environment::GetPathR("gravel_corner_nw.wmtf"); mGravelCornerNW = Texture2D::LoadWMTF(name); mGravelCornerNW->GenerateMipmaps(); name = Environment::GetPathR("gravel_corner_sw.wmtf"); mGravelCornerSW = Texture2D::LoadWMTF(name); mGravelCornerSW->GenerateMipmaps(); mStone1 = mStone; name = Environment::GetPathR("stone02.wmtf"); mStone2 = Texture2D::LoadWMTF(name); mStone2->GenerateMipmaps(); name = Environment::GetPathR("stone03.wmtf"); mStone3 = Texture2D::LoadWMTF(name); mStone3->GenerateMipmaps(); name = Environment::GetPathR("gravel_cap_ne.wmtf"); mGravelCapNE = Texture2D::LoadWMTF(name); mGravelCapNE->GenerateMipmaps(); name = Environment::GetPathR("gravel_cap_nw.wmtf"); mGravelCapNW = Texture2D::LoadWMTF(name); mGravelCapNW->GenerateMipmaps(); name = Environment::GetPathR("gravel_side_s.wmtf"); mGravelSideS = Texture2D::LoadWMTF(name); mGravelSideS->GenerateMipmaps(); name = Environment::GetPathR("gravel_side_n.wmtf"); mGravelSideN = Texture2D::LoadWMTF(name); mGravelSideN->GenerateMipmaps(); name = Environment::GetPathR("gravel_side_w.wmtf"); mGravelSideW = Texture2D::LoadWMTF(name); mGravelSideW->GenerateMipmaps(); name = Environment::GetPathR("largestone01.wmtf"); mLargeStone1 = Texture2D::LoadWMTF(name); mLargeStone1->GenerateMipmaps(); name = Environment::GetPathR("largerstone01.wmtf"); mLargerStone1 = Texture2D::LoadWMTF(name); mLargerStone1->GenerateMipmaps(); name = Environment::GetPathR("largerstone02.wmtf"); mLargerStone2 = Texture2D::LoadWMTF(name); mLargerStone2->GenerateMipmaps(); name = Environment::GetPathR("largeststone01.wmtf"); mLargestStone1 = Texture2D::LoadWMTF(name); mLargestStone1->GenerateMipmaps(); name = Environment::GetPathR("largeststone02.wmtf"); mLargestStone2 = Texture2D::LoadWMTF(name); mLargestStone2->GenerateMipmaps(); name = Environment::GetPathR("hugestone01.wmtf"); mHugeStone1 = Texture2D::LoadWMTF(name); mHugeStone1->GenerateMipmaps(); name = Environment::GetPathR("hugestone02.wmtf"); mHugeStone2 = Texture2D::LoadWMTF(name); mHugeStone2->GenerateMipmaps(); name = Environment::GetPathR("gravel_corner_nw.wmtf"); mGravelCornerNW = Texture2D::LoadWMTF(name); mGravelCornerNW->GenerateMipmaps(); name = Environment::GetPathR("gravel_corner_sw.wmtf"); mGravelCornerSW = Texture2D::LoadWMTF(name); mGravelCornerSW->GenerateMipmaps(); } //---------------------------------------------------------------------------- void Castle::CreateSharedMeshes () { std::vector<TriMesh*> meshes; mWoodShieldMesh = LoadMeshPNT1("WoodShield01.txt"); mTorchMetalMesh = LoadMeshPNT1("Tube01.txt"); meshes = LoadMeshPNT1Multi("Sphere01.txt"); mTorchWoodMesh = meshes[0]; mTorchHeadMesh = meshes[1]; mVerticalSpoutMesh = LoadMeshPNT1("Cylinder03.txt"); mHorizontalSpoutMesh = LoadMeshPNT1("Cylinder02NCL.txt"); mBarrelHolderMesh = LoadMeshPNT1("Box01.txt"); mBarrelMesh = LoadMeshPNT1("Barrel01.txt"); } //----------------------------------------------------------------------------
[ "bazhenovc@bazhenovc-laptop" ]
bazhenovc@bazhenovc-laptop
148209f70ce059f267476742fcf55ef7151d0db1
1294ff7789d8cdd946bc78f50534cbecd56cf8c8
/Engine/VK/RefCountVk.cpp
00a8e3256ae759f414b006c76c1ef175c0ab2716
[ "MIT" ]
permissive
DrGr4f1x/Kodiak4
3071f9990ad81ef00b599aa5312104b46372131a
cc7bb3bcc5e189e3ce82dc15266b3231401f4ef0
refs/heads/master
2022-12-25T03:14:40.314942
2020-10-15T02:44:58
2020-10-15T02:44:58
264,319,036
0
0
null
null
null
null
UTF-8
C++
false
false
4,108
cpp
// // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // // Author: David Elder // #include "Stdafx.h" #include "VK\RefCountVk.h" using namespace Kodiak; using namespace std; InstanceRef::~InstanceRef() { vkDestroyInstance(m_instance, nullptr); m_instance = VK_NULL_HANDLE; } shared_ptr<InstanceRef> InstanceRef::Create(VkInstance instance) { shared_ptr<InstanceRef> ptr(new InstanceRef(instance)); return ptr; } PhysicalDeviceRef::~PhysicalDeviceRef() { m_physicalDevice = VK_NULL_HANDLE; } shared_ptr<PhysicalDeviceRef> PhysicalDeviceRef::Create(const shared_ptr<InstanceRef>& instance, VkPhysicalDevice physicalDevice) { shared_ptr<PhysicalDeviceRef> ptr(new PhysicalDeviceRef(instance, physicalDevice)); return ptr; } DebugUtilsMessengerRef::~DebugUtilsMessengerRef() { #if ENABLE_VULKAN_VALIDATION extern PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessenger; vkDestroyDebugUtilsMessenger(*Get<InstanceRef>(), m_messenger, nullptr); #endif m_messenger = VK_NULL_HANDLE; } shared_ptr<DebugUtilsMessengerRef> DebugUtilsMessengerRef::Create(const shared_ptr<InstanceRef>& instance, VkDebugUtilsMessengerEXT messenger) { shared_ptr<DebugUtilsMessengerRef> ptr(new DebugUtilsMessengerRef(instance, messenger)); return ptr; } SurfaceRef::~SurfaceRef() { vkDestroySurfaceKHR(*Get<InstanceRef>(), m_surface, nullptr); m_surface = VK_NULL_HANDLE; } shared_ptr<SurfaceRef> SurfaceRef::Create(const shared_ptr<InstanceRef>& instance, VkSurfaceKHR surface) { shared_ptr<SurfaceRef> ptr(new SurfaceRef(instance, surface)); return ptr; } DeviceRef::~DeviceRef() { vkDestroyDevice(m_device, nullptr); m_device = VK_NULL_HANDLE; } shared_ptr<DeviceRef> DeviceRef::Create(const shared_ptr<PhysicalDeviceRef>& physicalDevice, VkDevice device) { shared_ptr<DeviceRef> ptr(new DeviceRef(physicalDevice, device)); return ptr; } AllocatorRef::~AllocatorRef() { vmaDestroyAllocator(m_allocator); m_allocator = VK_NULL_HANDLE; } shared_ptr<AllocatorRef> AllocatorRef::Create( const shared_ptr<InstanceRef>& instance, const shared_ptr<PhysicalDeviceRef>& physicalDevice, const shared_ptr<DeviceRef>& device, VmaAllocator allocator) { shared_ptr<AllocatorRef> ptr(new AllocatorRef(instance, physicalDevice, device, allocator)); return ptr; } #if 0 FenceRef::~FenceRef() { vkDestroyFence(*Get<DeviceRef>(), m_fence, nullptr); m_fence = VK_NULL_HANDLE; } shared_ptr<FenceRef> FenceRef::Create(const shared_ptr<DeviceRef>& device, VkFence fence) { shared_ptr<FenceRef> ptr(new FenceRef(device, fence)); return ptr; } SemaphoreRef::~SemaphoreRef() { vkDestroySemaphore(*Get<DeviceRef>(), m_semaphore, nullptr); m_semaphore = VK_NULL_HANDLE; } shared_ptr<SemaphoreRef> SemaphoreRef::Create(const shared_ptr<DeviceRef>& device, VkSemaphore semaphore) { shared_ptr<SemaphoreRef> ptr(new SemaphoreRef(device, semaphore)); return ptr; } #endif ImageRef::~ImageRef() { if (m_allocation != VK_NULL_HANDLE) { vmaDestroyImage(*Get<AllocatorRef>(), m_image, m_allocation); m_allocation = VK_NULL_HANDLE; } m_image = VK_NULL_HANDLE; } shared_ptr<ImageRef> ImageRef::Create(const shared_ptr<DeviceRef>& device, VkImage image) { shared_ptr<ImageRef> ptr(new ImageRef(device, image)); return ptr; } shared_ptr<ImageRef> ImageRef::Create( const shared_ptr<DeviceRef>& device, const shared_ptr<AllocatorRef>& allocator, VkImage image, VmaAllocation allocation) { shared_ptr<ImageRef> ptr(new ImageRef(device, allocator, image, allocation)); return ptr; } SwapchainRef::~SwapchainRef() { extern PFN_vkDestroySwapchainKHR vkDestroySwapchain; vkDestroySwapchain(*Get<DeviceRef>(), m_swapchain, nullptr); m_swapchain = VK_NULL_HANDLE; } shared_ptr<SwapchainRef> SwapchainRef::Create(const shared_ptr<DeviceRef>& device, VkSwapchainKHR swapchain) { shared_ptr<SwapchainRef> ptr(new SwapchainRef(device, swapchain)); return ptr; }
[ "elddm1@gmail.com" ]
elddm1@gmail.com
d614644ea667b65b6d22e73f354376d4f67530c6
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/remoting/host/mac/host_service_main.cc
66c957fd1276034b33a18593fed90f49892b363e
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
13,723
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <signal.h> #include <unistd.h> #include <iostream> #include <string> #include "base/at_exit.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/mac/mac_util.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/process/process.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringize_macros.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "remoting/base/logging.h" #include "remoting/host/host_exit_codes.h" #include "remoting/host/logging.h" #include "remoting/host/mac/constants_mac.h" #include "remoting/host/switches.h" #include "remoting/host/username.h" #include "remoting/host/version.h" namespace remoting { namespace { constexpr char kSwitchDisable[] = "disable"; constexpr char kSwitchEnable[] = "enable"; constexpr char kSwitchSaveConfig[] = "save-config"; constexpr char kSwitchHostVersion[] = "host-version"; constexpr char kSwitchHostRunFromLaunchd[] = "run-from-launchd"; constexpr char kHostExeFileName[] = "remoting_me2me_host"; constexpr char kNativeMessagingHostPath[] = "Contents/MacOS/native_messaging_host"; // The exit code returned by 'wait' when a process is terminated by SIGTERM. constexpr int kSigtermExitCode = 128 + SIGTERM; // Constants controlling the host process relaunch throttling. constexpr base::TimeDelta kMinimumRelaunchInterval = base::TimeDelta::FromMinutes(1); constexpr int kMaximumHostFailures = 10; // Exit code 126 is defined by Posix to mean "Command found, but not // executable", and is returned if the process cannot be launched due to // parental control. constexpr int kPermissionDeniedParentalControl = 126; // This executable works as a proxy between launchd and the host. Signals of // interest to the host must be forwarded. constexpr int kSignalList[] = { SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGEMT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGPIPE, SIGALRM, SIGTERM, SIGURG, SIGTSTP, SIGCONT, SIGTTIN, SIGTTOU, SIGIO, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH, SIGINFO, SIGUSR1, SIGUSR2}; // Current host PID used to forward signals. 0 if host is not running. static base::ProcessId g_host_pid = 0; void HandleSignal(int signum) { if (g_host_pid) { // All other signals are forwarded to host then ignored except SIGTERM. // launchd sends SIGTERM when service is being stopped so both the host and // the host service need to terminate. HOST_LOG << "Forwarding signal " << signum << " to host process " << g_host_pid; kill(g_host_pid, signum); if (signum == SIGTERM) { HOST_LOG << "Host service is terminating upon reception of SIGTERM"; exit(kSigtermExitCode); } } else { HOST_LOG << "Signal " << signum << " will not be forwarded since host is not running."; exit(128 + signum); } } void RegisterSignalHandler() { struct sigaction action = {}; sigfillset(&action.sa_mask); action.sa_flags = 0; action.sa_handler = &HandleSignal; for (int signum : kSignalList) { if (sigaction(signum, &action, nullptr) == -1) { PLOG(DFATAL) << "Failed to register signal handler for signal " << signum; } } } class HostService { public: HostService(); ~HostService(); bool Disable(); bool Enable(); bool WriteStdinToConfig(); int RunHost(); void PrintHostVersion(); void PrintPid(); private: int RunHostFromOldScript(); // Runs the permission-checker built into the native-messaging host. Returns // true if all permissions were granted (or no permission check is needed for // the version of MacOS). bool CheckPermission(); bool HostIsEnabled(); base::FilePath old_host_helper_file_; base::FilePath enabled_file_; base::FilePath config_file_; base::FilePath host_exe_file_; base::FilePath native_messaging_host_exe_file_; }; HostService::HostService() { old_host_helper_file_ = base::FilePath(kOldHostHelperScriptPath); enabled_file_ = base::FilePath(kHostEnabledPath); config_file_ = base::FilePath(kHostConfigFilePath); base::FilePath host_service_dir; base::PathService::Get(base::DIR_EXE, &host_service_dir); host_exe_file_ = host_service_dir.AppendASCII(kHostExeFileName); native_messaging_host_exe_file_ = host_service_dir.AppendASCII(NATIVE_MESSAGING_HOST_BUNDLE_NAME) .AppendASCII(kNativeMessagingHostPath); } HostService::~HostService() = default; int HostService::RunHost() { // Mojave users updating from an older host likely have already granted a11y // permission to the old script. In this case we always delegate RunHost to // the old script so that they don't need to grant permission to a new app. if (base::mac::IsOS10_14() && base::PathExists(old_host_helper_file_)) { HOST_LOG << "RunHost will be delegated to the old host script."; return RunHostFromOldScript(); } if (geteuid() != 0 && HostIsEnabled()) { // Only check for non-root users, as the permission wizard is not actionable // at the login screen. Also, permission is only needed when host is // enabled - the launchd service should exit immediately if the host is // disabled. if (!CheckPermission()) { return 1; } } int host_failure_count = 0; base::TimeTicks host_start_time; while (true) { if (!HostIsEnabled()) { HOST_LOG << "Daemon is disabled."; return 0; } // If this is not the first time the host has run, make sure we don't // relaunch it too soon. if (!host_start_time.is_null()) { base::TimeDelta host_lifetime = base::TimeTicks::Now() - host_start_time; HOST_LOG << "Host ran for " << host_lifetime; if (host_lifetime < kMinimumRelaunchInterval) { // If the host didn't run for very long, assume it crashed. Relaunch // only after a suitable delay and increase the failure count. host_failure_count++; LOG(WARNING) << "Host failure count " << host_failure_count << "/" << kMaximumHostFailures; if (host_failure_count >= kMaximumHostFailures) { LOG(ERROR) << "Too many host failures. Giving up."; return 1; } base::TimeDelta relaunch_in = kMinimumRelaunchInterval - host_lifetime; HOST_LOG << "Relaunching in " << relaunch_in; base::PlatformThread::Sleep(relaunch_in); } else { // If the host ran for long enough, reset the crash counter. host_failure_count = 0; } } host_start_time = base::TimeTicks::Now(); base::CommandLine cmdline(host_exe_file_); cmdline.AppendSwitchPath("host-config", config_file_); std::string ssh_auth_sockname = "/tmp/chromoting." + GetUsername() + ".ssh_auth_sock"; cmdline.AppendSwitchASCII("ssh-auth-sockname", ssh_auth_sockname); base::Process process = base::LaunchProcess(cmdline, base::LaunchOptions()); if (!process.IsValid()) { LOG(ERROR) << "Failed to launch host process for unknown reason."; return 1; } g_host_pid = process.Pid(); int exit_code; process.WaitForExit(&exit_code); g_host_pid = 0; const char* exit_code_string_ptr = ExitCodeToStringUnchecked(exit_code); std::string exit_code_string = exit_code_string_ptr ? (std::string(exit_code_string_ptr) + " (" + base::NumberToString(exit_code) + ")") : base::NumberToString(exit_code); if (exit_code == 0 || exit_code == kSigtermExitCode || exit_code == kPermissionDeniedParentalControl || (exit_code >= kMinPermanentErrorExitCode && exit_code <= kMaxPermanentErrorExitCode)) { HOST_LOG << "Host returned permanent exit code " << exit_code_string << " at " << base::Time::Now(); if (exit_code == kInvalidHostIdExitCode || exit_code == kHostDeletedExitCode) { // The host was taken off-line remotely. To prevent the host being // restarted when the login context changes, try to delete the "enabled" // file. Since this requires root privileges, this is only possible when // this executable is launched in the "login" context. In the "aqua" // context, just exit and try again next time. HOST_LOG << "Host deleted - disabling"; Disable(); } return exit_code; } // Ignore non-permanent error-code and launch host again. Stop handling // signals temporarily in case the executable has to sleep to throttle host // relaunches. While throttling, there is no host process to which to // forward the signal, so the default behaviour should be restored. HOST_LOG << "Host returned non-permanent exit code " << exit_code_string << " at " << base::Time::Now(); } return 0; } bool HostService::Disable() { return base::DeleteFile(enabled_file_); } bool HostService::Enable() { // Ensure the config file is private whilst being written. base::DeleteFile(config_file_); if (!WriteStdinToConfig()) { return false; } if (!base::SetPosixFilePermissions(config_file_, 0600)) { LOG(ERROR) << "Failed to set posix permission"; return false; } // Ensure the config is readable by the user registering the host. // We don't seem to have API for adding Mac ACL entry for file. This code just // uses the chmod binary to do so. base::CommandLine chmod_cmd(base::FilePath("/bin/chmod")); chmod_cmd.AppendArg("+a"); chmod_cmd.AppendArg("user:" + GetUsername() + ":allow:read"); chmod_cmd.AppendArgPath(config_file_); std::string output; if (!base::GetAppOutputAndError(chmod_cmd, &output)) { LOG(ERROR) << "Failed to chmod file " << config_file_; return false; } if (!output.empty()) { HOST_LOG << "Message from chmod: " << output; } if (base::WriteFile(enabled_file_, nullptr, 0) < 0) { LOG(ERROR) << "Failed to write enabled file"; return false; } return true; } bool HostService::WriteStdinToConfig() { // Reads from stdin and writes it to the config file. std::istreambuf_iterator<char> begin(std::cin); std::istreambuf_iterator<char> end; std::string config(begin, end); if (base::WriteFile(config_file_, config.data(), config.size()) != static_cast<int>(config.size())) { LOG(ERROR) << "Failed to write config file"; return false; } return true; } void HostService::PrintHostVersion() { printf("%s\n", STRINGIZE(VERSION)); } void HostService::PrintPid() { // Caller running host service with privilege waits for the PID to continue, // so we need to flush it immediately. printf("%d\n", base::Process::Current().Pid()); fflush(stdout); } int HostService::RunHostFromOldScript() { base::CommandLine cmdline(old_host_helper_file_); cmdline.AppendSwitch(kSwitchHostRunFromLaunchd); base::LaunchOptions options; options.disclaim_responsibility = true; base::Process process = base::LaunchProcess(cmdline, options); if (!process.IsValid()) { LOG(ERROR) << "Failed to launch the old host script for unknown reason."; return 1; } g_host_pid = process.Pid(); int exit_code; process.WaitForExit(&exit_code); g_host_pid = 0; return exit_code; } bool HostService::CheckPermission() { LOG(INFO) << "Checking for host permissions."; base::CommandLine cmdLine(native_messaging_host_exe_file_); cmdLine.AppendSwitch(kCheckPermissionSwitchName); // No need to disclaim responsibility here - the native-messaging host already // takes care of that. base::Process process = base::LaunchProcess(cmdLine, base::LaunchOptions()); if (!process.IsValid()) { LOG(ERROR) << "Unable to launch native-messaging host process"; return false; } int exit_code; process.WaitForExit(&exit_code); if (exit_code != 0) { LOG(ERROR) << "A required permission was not granted."; return false; } LOG(INFO) << "All permissions granted!"; return true; } bool HostService::HostIsEnabled() { return base::PathExists(enabled_file_); } } // namespace } // namespace remoting int main(int argc, char const* argv[]) { base::AtExitManager exitManager; base::CommandLine::Init(argc, argv); remoting::InitHostLogging(); remoting::HostService service; auto* current_cmdline = base::CommandLine::ForCurrentProcess(); std::string pid = base::NumberToString(base::Process::Current().Pid()); if (current_cmdline->HasSwitch(remoting::kSwitchDisable)) { service.PrintPid(); if (!service.Disable()) { LOG(ERROR) << "Failed to disable"; return 1; } } else if (current_cmdline->HasSwitch(remoting::kSwitchEnable)) { service.PrintPid(); if (!service.Enable()) { LOG(ERROR) << "Failed to enable"; return 1; } } else if (current_cmdline->HasSwitch(remoting::kSwitchSaveConfig)) { service.PrintPid(); if (!service.WriteStdinToConfig()) { LOG(ERROR) << "Failed to save config"; return 1; } } else if (current_cmdline->HasSwitch(remoting::kSwitchHostVersion)) { service.PrintHostVersion(); } else if (current_cmdline->HasSwitch(remoting::kSwitchHostRunFromLaunchd)) { remoting::RegisterSignalHandler(); HOST_LOG << "Host started for user " << remoting::GetUsername() << " at " << base::Time::Now(); return service.RunHost(); } else { service.PrintPid(); return 1; } return 0; }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b73bb4d94e029da44b3970a1a088d3f66ab43b9c
03ad1519a026bab20519a1de4bd464e404c42901
/td/telegram/DialogAction.cpp
14d5b5490544630a0787d860bf39f307fbf022ee
[ "JSON", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
source-c/td
3ce013e31ef86b8fac0756074b3e362e23fec1cb
625fdd68104f61348b9f8296b5f92748cff5ead2
refs/heads/master
2022-09-15T19:08:12.368687
2022-08-30T10:52:01
2022-08-30T10:52:01
151,976,134
0
0
BSL-1.0
2019-09-28T21:54:33
2018-10-07T19:12:35
C++
UTF-8
C++
false
false
20,423
cpp
// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2022 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "td/telegram/DialogAction.h" #include "td/telegram/misc.h" #include "td/telegram/ServerMessageId.h" #include "td/utils/emoji.h" #include "td/utils/misc.h" #include "td/utils/Slice.h" #include "td/utils/SliceBuilder.h" #include "td/utils/utf8.h" namespace td { bool DialogAction::is_valid_emoji(string &emoji) { if (!clean_input_string(emoji)) { return false; } return is_emoji(emoji); } void DialogAction::init(Type type) { type_ = type; progress_ = 0; emoji_.clear(); } void DialogAction::init(Type type, int32 progress) { type_ = type; progress_ = clamp(progress, 0, 100); emoji_.clear(); } void DialogAction::init(Type type, string emoji) { if (is_valid_emoji(emoji)) { type_ = type; progress_ = 0; emoji_ = std::move(emoji); } else { init(Type::Cancel); } } void DialogAction::init(Type type, int32 message_id, string emoji, const string &data) { if (ServerMessageId(message_id).is_valid() && is_valid_emoji(emoji) && check_utf8(data)) { type_ = type; progress_ = message_id; emoji_ = PSTRING() << emoji << '\xFF' << data; } else { init(Type::Cancel); } } DialogAction::DialogAction(Type type, int32 progress) { init(type, progress); } DialogAction::DialogAction(td_api::object_ptr<td_api::ChatAction> &&action) { if (action == nullptr) { return; } switch (action->get_id()) { case td_api::chatActionCancel::ID: init(Type::Cancel); break; case td_api::chatActionTyping::ID: init(Type::Typing); break; case td_api::chatActionRecordingVideo::ID: init(Type::RecordingVideo); break; case td_api::chatActionUploadingVideo::ID: { auto uploading_action = move_tl_object_as<td_api::chatActionUploadingVideo>(action); init(Type::UploadingVideo, uploading_action->progress_); break; } case td_api::chatActionRecordingVoiceNote::ID: init(Type::RecordingVoiceNote); break; case td_api::chatActionUploadingVoiceNote::ID: { auto uploading_action = move_tl_object_as<td_api::chatActionUploadingVoiceNote>(action); init(Type::UploadingVoiceNote, uploading_action->progress_); break; } case td_api::chatActionUploadingPhoto::ID: { auto uploading_action = move_tl_object_as<td_api::chatActionUploadingPhoto>(action); init(Type::UploadingPhoto, uploading_action->progress_); break; } case td_api::chatActionUploadingDocument::ID: { auto uploading_action = move_tl_object_as<td_api::chatActionUploadingDocument>(action); init(Type::UploadingDocument, uploading_action->progress_); break; } case td_api::chatActionChoosingLocation::ID: init(Type::ChoosingLocation); break; case td_api::chatActionChoosingContact::ID: init(Type::ChoosingContact); break; case td_api::chatActionStartPlayingGame::ID: init(Type::StartPlayingGame); break; case td_api::chatActionRecordingVideoNote::ID: init(Type::RecordingVideoNote); break; case td_api::chatActionUploadingVideoNote::ID: { auto uploading_action = move_tl_object_as<td_api::chatActionUploadingVideoNote>(action); init(Type::UploadingVideoNote, uploading_action->progress_); break; } case td_api::chatActionChoosingSticker::ID: init(Type::ChoosingSticker); break; case td_api::chatActionWatchingAnimations::ID: { auto watching_animations_action = move_tl_object_as<td_api::chatActionWatchingAnimations>(action); init(Type::WatchingAnimations, std::move(watching_animations_action->emoji_)); break; } default: UNREACHABLE(); break; } } DialogAction::DialogAction(telegram_api::object_ptr<telegram_api::SendMessageAction> &&action) { switch (action->get_id()) { case telegram_api::sendMessageCancelAction::ID: init(Type::Cancel); break; case telegram_api::sendMessageTypingAction::ID: init(Type::Typing); break; case telegram_api::sendMessageRecordVideoAction::ID: init(Type::RecordingVideo); break; case telegram_api::sendMessageUploadVideoAction::ID: { auto upload_video_action = move_tl_object_as<telegram_api::sendMessageUploadVideoAction>(action); init(Type::UploadingVideo, upload_video_action->progress_); break; } case telegram_api::sendMessageRecordAudioAction::ID: init(Type::RecordingVoiceNote); break; case telegram_api::sendMessageUploadAudioAction::ID: { auto upload_audio_action = move_tl_object_as<telegram_api::sendMessageUploadAudioAction>(action); init(Type::UploadingVoiceNote, upload_audio_action->progress_); break; } case telegram_api::sendMessageUploadPhotoAction::ID: { auto upload_photo_action = move_tl_object_as<telegram_api::sendMessageUploadPhotoAction>(action); init(Type::UploadingPhoto, upload_photo_action->progress_); break; } case telegram_api::sendMessageUploadDocumentAction::ID: { auto upload_document_action = move_tl_object_as<telegram_api::sendMessageUploadDocumentAction>(action); init(Type::UploadingDocument, upload_document_action->progress_); break; } case telegram_api::sendMessageGeoLocationAction::ID: init(Type::ChoosingLocation); break; case telegram_api::sendMessageChooseContactAction::ID: init(Type::ChoosingContact); break; case telegram_api::sendMessageGamePlayAction::ID: init(Type::StartPlayingGame); break; case telegram_api::sendMessageRecordRoundAction::ID: init(Type::RecordingVideoNote); break; case telegram_api::sendMessageUploadRoundAction::ID: { auto upload_round_action = move_tl_object_as<telegram_api::sendMessageUploadRoundAction>(action); init(Type::UploadingVideoNote, upload_round_action->progress_); break; } case telegram_api::speakingInGroupCallAction::ID: init(Type::SpeakingInVoiceChat); break; case telegram_api::sendMessageHistoryImportAction::ID: { auto history_import_action = move_tl_object_as<telegram_api::sendMessageHistoryImportAction>(action); init(Type::ImportingMessages, history_import_action->progress_); break; } case telegram_api::sendMessageChooseStickerAction::ID: init(Type::ChoosingSticker); break; case telegram_api::sendMessageEmojiInteractionSeen::ID: { auto emoji_interaction_seen_action = move_tl_object_as<telegram_api::sendMessageEmojiInteractionSeen>(action); init(Type::WatchingAnimations, std::move(emoji_interaction_seen_action->emoticon_)); break; } case telegram_api::sendMessageEmojiInteraction::ID: { auto emoji_interaction_action = move_tl_object_as<telegram_api::sendMessageEmojiInteraction>(action); init(Type::ClickingAnimatedEmoji, emoji_interaction_action->msg_id_, std::move(emoji_interaction_action->emoticon_), emoji_interaction_action->interaction_->data_); break; } default: UNREACHABLE(); break; } } tl_object_ptr<telegram_api::SendMessageAction> DialogAction::get_input_send_message_action() const { switch (type_) { case Type::Cancel: return make_tl_object<telegram_api::sendMessageCancelAction>(); case Type::Typing: return make_tl_object<telegram_api::sendMessageTypingAction>(); case Type::RecordingVideo: return make_tl_object<telegram_api::sendMessageRecordVideoAction>(); case Type::UploadingVideo: return make_tl_object<telegram_api::sendMessageUploadVideoAction>(progress_); case Type::RecordingVoiceNote: return make_tl_object<telegram_api::sendMessageRecordAudioAction>(); case Type::UploadingVoiceNote: return make_tl_object<telegram_api::sendMessageUploadAudioAction>(progress_); case Type::UploadingPhoto: return make_tl_object<telegram_api::sendMessageUploadPhotoAction>(progress_); case Type::UploadingDocument: return make_tl_object<telegram_api::sendMessageUploadDocumentAction>(progress_); case Type::ChoosingLocation: return make_tl_object<telegram_api::sendMessageGeoLocationAction>(); case Type::ChoosingContact: return make_tl_object<telegram_api::sendMessageChooseContactAction>(); case Type::StartPlayingGame: return make_tl_object<telegram_api::sendMessageGamePlayAction>(); case Type::RecordingVideoNote: return make_tl_object<telegram_api::sendMessageRecordRoundAction>(); case Type::UploadingVideoNote: return make_tl_object<telegram_api::sendMessageUploadRoundAction>(progress_); case Type::SpeakingInVoiceChat: return make_tl_object<telegram_api::speakingInGroupCallAction>(); case Type::ImportingMessages: return make_tl_object<telegram_api::sendMessageHistoryImportAction>(progress_); case Type::ChoosingSticker: return make_tl_object<telegram_api::sendMessageChooseStickerAction>(); case Type::WatchingAnimations: return make_tl_object<telegram_api::sendMessageEmojiInteractionSeen>(emoji_); case Type::ClickingAnimatedEmoji: default: UNREACHABLE(); return nullptr; } } tl_object_ptr<secret_api::SendMessageAction> DialogAction::get_secret_input_send_message_action() const { switch (type_) { case Type::Cancel: return make_tl_object<secret_api::sendMessageCancelAction>(); case Type::Typing: return make_tl_object<secret_api::sendMessageTypingAction>(); case Type::RecordingVideo: return make_tl_object<secret_api::sendMessageRecordVideoAction>(); case Type::UploadingVideo: return make_tl_object<secret_api::sendMessageUploadVideoAction>(); case Type::RecordingVoiceNote: return make_tl_object<secret_api::sendMessageRecordAudioAction>(); case Type::UploadingVoiceNote: return make_tl_object<secret_api::sendMessageUploadAudioAction>(); case Type::UploadingPhoto: return make_tl_object<secret_api::sendMessageUploadPhotoAction>(); case Type::UploadingDocument: return make_tl_object<secret_api::sendMessageUploadDocumentAction>(); case Type::ChoosingLocation: return make_tl_object<secret_api::sendMessageGeoLocationAction>(); case Type::ChoosingContact: return make_tl_object<secret_api::sendMessageChooseContactAction>(); case Type::StartPlayingGame: return make_tl_object<secret_api::sendMessageTypingAction>(); case Type::RecordingVideoNote: return make_tl_object<secret_api::sendMessageRecordRoundAction>(); case Type::UploadingVideoNote: return make_tl_object<secret_api::sendMessageUploadRoundAction>(); case Type::SpeakingInVoiceChat: return make_tl_object<secret_api::sendMessageTypingAction>(); case Type::ImportingMessages: return make_tl_object<secret_api::sendMessageTypingAction>(); case Type::ChoosingSticker: return make_tl_object<secret_api::sendMessageTypingAction>(); case Type::WatchingAnimations: return make_tl_object<secret_api::sendMessageTypingAction>(); case Type::ClickingAnimatedEmoji: default: UNREACHABLE(); return nullptr; } } tl_object_ptr<td_api::ChatAction> DialogAction::get_chat_action_object() const { switch (type_) { case Type::Cancel: return td_api::make_object<td_api::chatActionCancel>(); case Type::Typing: return td_api::make_object<td_api::chatActionTyping>(); case Type::RecordingVideo: return td_api::make_object<td_api::chatActionRecordingVideo>(); case Type::UploadingVideo: return td_api::make_object<td_api::chatActionUploadingVideo>(progress_); case Type::RecordingVoiceNote: return td_api::make_object<td_api::chatActionRecordingVoiceNote>(); case Type::UploadingVoiceNote: return td_api::make_object<td_api::chatActionUploadingVoiceNote>(progress_); case Type::UploadingPhoto: return td_api::make_object<td_api::chatActionUploadingPhoto>(progress_); case Type::UploadingDocument: return td_api::make_object<td_api::chatActionUploadingDocument>(progress_); case Type::ChoosingLocation: return td_api::make_object<td_api::chatActionChoosingLocation>(); case Type::ChoosingContact: return td_api::make_object<td_api::chatActionChoosingContact>(); case Type::StartPlayingGame: return td_api::make_object<td_api::chatActionStartPlayingGame>(); case Type::RecordingVideoNote: return td_api::make_object<td_api::chatActionRecordingVideoNote>(); case Type::UploadingVideoNote: return td_api::make_object<td_api::chatActionUploadingVideoNote>(progress_); case Type::ChoosingSticker: return td_api::make_object<td_api::chatActionChoosingSticker>(); case Type::WatchingAnimations: return td_api::make_object<td_api::chatActionWatchingAnimations>(emoji_); case Type::ImportingMessages: case Type::SpeakingInVoiceChat: case Type::ClickingAnimatedEmoji: default: UNREACHABLE(); return td_api::make_object<td_api::chatActionCancel>(); } } bool DialogAction::is_canceled_by_message_of_type(MessageContentType message_content_type) const { if (message_content_type == MessageContentType::None) { return true; } if (type_ == Type::Typing) { return message_content_type == MessageContentType::Text || message_content_type == MessageContentType::Game || can_have_message_content_caption(message_content_type); } switch (message_content_type) { case MessageContentType::Animation: case MessageContentType::Audio: case MessageContentType::Document: return type_ == Type::UploadingDocument; case MessageContentType::ExpiredPhoto: case MessageContentType::Photo: return type_ == Type::UploadingPhoto; case MessageContentType::ExpiredVideo: case MessageContentType::Video: return type_ == Type::RecordingVideo || type_ == Type::UploadingVideo; case MessageContentType::VideoNote: return type_ == Type::RecordingVideoNote || type_ == Type::UploadingVideoNote; case MessageContentType::VoiceNote: return type_ == Type::RecordingVoiceNote || type_ == Type::UploadingVoiceNote; case MessageContentType::Contact: return type_ == Type::ChoosingContact; case MessageContentType::LiveLocation: case MessageContentType::Location: case MessageContentType::Venue: return type_ == Type::ChoosingLocation; case MessageContentType::Sticker: return type_ == Type::ChoosingSticker; case MessageContentType::Game: case MessageContentType::Invoice: case MessageContentType::Text: case MessageContentType::Unsupported: case MessageContentType::ChatCreate: case MessageContentType::ChatChangeTitle: case MessageContentType::ChatChangePhoto: case MessageContentType::ChatDeletePhoto: case MessageContentType::ChatDeleteHistory: case MessageContentType::ChatAddUsers: case MessageContentType::ChatJoinedByLink: case MessageContentType::ChatDeleteUser: case MessageContentType::ChatMigrateTo: case MessageContentType::ChannelCreate: case MessageContentType::ChannelMigrateFrom: case MessageContentType::PinMessage: case MessageContentType::GameScore: case MessageContentType::ScreenshotTaken: case MessageContentType::ChatSetTtl: case MessageContentType::Call: case MessageContentType::PaymentSuccessful: case MessageContentType::ContactRegistered: case MessageContentType::CustomServiceAction: case MessageContentType::WebsiteConnected: case MessageContentType::PassportDataSent: case MessageContentType::PassportDataReceived: case MessageContentType::Poll: case MessageContentType::Dice: case MessageContentType::ProximityAlertTriggered: case MessageContentType::GroupCall: case MessageContentType::InviteToGroupCall: case MessageContentType::ChatSetTheme: case MessageContentType::WebViewDataSent: case MessageContentType::WebViewDataReceived: case MessageContentType::GiftPremium: return false; default: UNREACHABLE(); return false; } } DialogAction DialogAction::get_uploading_action(MessageContentType message_content_type, int32 progress) { switch (message_content_type) { case MessageContentType::Animation: case MessageContentType::Audio: case MessageContentType::Document: return DialogAction(Type::UploadingDocument, progress); case MessageContentType::Photo: return DialogAction(Type::UploadingPhoto, progress); case MessageContentType::Video: return DialogAction(Type::UploadingVideo, progress); case MessageContentType::VideoNote: return DialogAction(Type::UploadingVideoNote, progress); case MessageContentType::VoiceNote: return DialogAction(Type::UploadingVoiceNote, progress); default: return DialogAction(); } } DialogAction DialogAction::get_typing_action() { return DialogAction(Type::Typing, 0); } DialogAction DialogAction::get_speaking_action() { return DialogAction(Type::SpeakingInVoiceChat, 0); } int32 DialogAction::get_importing_messages_action_progress() const { if (type_ != Type::ImportingMessages) { return -1; } return progress_; } string DialogAction::get_watching_animations_emoji() const { if (type_ == Type::WatchingAnimations) { return emoji_; } return string(); } DialogAction::ClickingAnimateEmojiInfo DialogAction::get_clicking_animated_emoji_action_info() const { ClickingAnimateEmojiInfo result; if (type_ == Type::ClickingAnimatedEmoji) { auto pos = emoji_.find('\xFF'); CHECK(pos < emoji_.size()); result.message_id = progress_; result.emoji = emoji_.substr(0, pos); result.data = emoji_.substr(pos + 1); } return result; } StringBuilder &operator<<(StringBuilder &string_builder, const DialogAction &action) { string_builder << "ChatAction"; const char *type = [action_type = action.type_] { switch (action_type) { case DialogAction::Type::Cancel: return "Cancel"; case DialogAction::Type::Typing: return "Typing"; case DialogAction::Type::RecordingVideo: return "RecordingVideo"; case DialogAction::Type::UploadingVideo: return "UploadingVideo"; case DialogAction::Type::RecordingVoiceNote: return "RecordingVoiceNote"; case DialogAction::Type::UploadingVoiceNote: return "UploadingVoiceNote"; case DialogAction::Type::UploadingPhoto: return "UploadingPhoto"; case DialogAction::Type::UploadingDocument: return "UploadingDocument"; case DialogAction::Type::ChoosingLocation: return "ChoosingLocation"; case DialogAction::Type::ChoosingContact: return "ChoosingContact"; case DialogAction::Type::StartPlayingGame: return "StartPlayingGame"; case DialogAction::Type::RecordingVideoNote: return "RecordingVideoNote"; case DialogAction::Type::UploadingVideoNote: return "UploadingVideoNote"; case DialogAction::Type::SpeakingInVoiceChat: return "SpeakingInVoiceChat"; case DialogAction::Type::ImportingMessages: return "ImportingMessages"; case DialogAction::Type::ChoosingSticker: return "ChoosingSticker"; case DialogAction::Type::WatchingAnimations: return "WatchingAnimations"; case DialogAction::Type::ClickingAnimatedEmoji: return "ClickingAnimatedEmoji"; default: UNREACHABLE(); return "Cancel"; } }(); string_builder << type << "Action"; if (action.type_ == DialogAction::Type::ClickingAnimatedEmoji) { auto pos = action.emoji_.find('\xFF'); CHECK(pos < action.emoji_.size()); string_builder << '(' << action.progress_ << ")(" << Slice(action.emoji_).substr(0, pos) << ")(" << Slice(action.emoji_).substr(pos + 1) << ')'; } else { if (action.progress_ != 0) { string_builder << '(' << action.progress_ << "%)"; } if (!action.emoji_.empty()) { string_builder << '(' << action.emoji_ << ')'; } } return string_builder; } } // namespace td
[ "levlam@telegram.org" ]
levlam@telegram.org
e7045d5b1ff03d5b4433b4dc476ab23b868210ed
608aefe4234248cbb8f0c1614caeb3a2c215cceb
/10684 - The jackpot.cpp
c504b8966ea567230edce434fe2fa7649fa08012
[]
no_license
MahtabTanim/UVA
06ab16b19c229c1b85e3d0f07b8344b1deb335a7
46992933b8909e013944c48d06cb47aded32246d
refs/heads/master
2023-02-07T16:23:36.012410
2021-01-01T06:47:57
2021-01-01T06:47:57
259,660,819
0
0
null
null
null
null
UTF-8
C++
false
false
638
cpp
#include<bits/stdc++.h> using namespace std; #define mod 1000000007 #define pb push_back #define mp make_pair #define MP ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define ll long long int #define maxn 1000000 #define FP ff.open("output.txt") fstream ff; ll a,b,c,d,k,h,e,f,t,m,n,i,j,x,y,count,tcase=0; string s; int main() { FP; while(cin>>n and n) { bool win =false; ll ans =0, points = 0; while(n--) { cin>>a; points += a; ans = max(ans,points); if(points<0) points=0; } if(ans==0) cout<<"Losing streak.\n"; else cout<<"The maximum winning streak is "<<ans<<"."<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
962c6fde4d6f028f0c5eab1211abb14175f55772
578ec8878814b5753f612c2fabdf6fe8d52ae2d1
/binary_tree.h
45c2058930bb3145a10d357ee0c356f005f85345
[]
no_license
migumigu/binary_tree
aa2cbb6be0f800f32493553c9551339925375371
157eba0f00466f9462c1fdf34a38965c393e6f83
refs/heads/master
2021-01-13T02:12:04.559232
2014-02-10T13:45:54
2014-02-10T13:45:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,088
h
#include<iostream> //#include"utility.h" #include"List.h" #include"Queue.h" using namespace std; ///////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// template <class Entry> struct Binary_node { // data members: Entry data; Binary_node<Entry> *left; Binary_node<Entry> *right; // constructors: Binary_node(); Binary_node(const Entry &x); }; ////////////////////////////////////////////////////////////////////////////////// template <class Entry> class Binary_tree { public: Binary_tree(); bool empty() const; void preorder(void (*visit)(Entry &)); void inorder(void (*visit)(Entry &)); void postorder(void (*visit)(Entry &)); void recursive_inorder(Binary_node<Entry> *sub_root,void (*visit)(Entry &)); void recursive_preorder(Binary_node<Entry> *sub_root,void (*visit)(Entry &)); void recursive_postorder(Binary_node<Entry> *sub_root,void (*visit)(Entry &)); void A(void (*visit)(Entry &)); void B(void (*visit)(Entry &)); int size();// const; int size1(const Binary_node<Entry> *root1); void clear(); void clear1(const Binary_node<Entry> *&root1); int height() ; int height1(const Binary_node<Entry> *root1); void insert(const Entry &); int MAX(int x,int y)const; void print()const; Binary_tree (const Binary_tree<Entry> &original); Binary_tree & operator =(const Binary_tree<Entry> &original); ~Binary_tree(); Binary_node<Entry> *xungen(); protected: // Add auxiliary function prototypes here. Binary_node<Entry> *root; }; //////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// //************************************************************* //************************************************************** template <class Entry> Binary_node<Entry>::Binary_node() { left = NULL; right = NULL; } //*********************************************************** template <class Entry> Binary_node<Entry>::Binary_node(const Entry &x) { data = x; left = NULL; right = NULL; } template <class Entry> Binary_node<Entry> *Binary_tree<Entry>::xungen() { return root; } //***************************************************************** template <class Entry> Binary_tree<Entry>::~Binary_tree() { clear(); } //*************************************************************** template <class Entry> Binary_tree<Entry>::Binary_tree() /* Post: An empty binary tree has been created. */ { root = NULL; } template <class Entry> bool Binary_tree<Entry>::empty() const /* Post: A result of true is returned if the binary tree is empty. Otherwise, false is returned. */ { return root == NULL; } template <class Entry> void Binary_tree<Entry>::inorder(void (*visit)(Entry &)) /* Post: The tree has been traversed in inorder sequence. Uses: The function recursive_inorder */ { recursive_inorder(root, visit); } template <class Entry> void Binary_tree<Entry>::recursive_inorder(Binary_node<Entry> *sub_root, void (*visit)(Entry &)) /* Pre: sub_root is either NULL or points to a subtree of the Binary_tree. Post: The subtree has been traversed in inorder sequence. Uses: The function recursive_inorder recursively */ { if (sub_root != NULL) { recursive_inorder(sub_root->left, visit); (*visit)(sub_root->data); recursive_inorder(sub_root->right, visit); } } template <class Entry> void Binary_tree<Entry>::recursive_preorder(Binary_node<Entry> *sub_root, void (*visit)(Entry &)) /* Pre: sub_root is either NULL or points to a subtree of the Binary_tree. Post: The subtree has been traversed in preorder sequence. Uses: The function recursive_preorder recursively */ { if (sub_root != NULL) { (*visit)(sub_root->data); recursive_preorder(sub_root->left, visit); recursive_preorder(sub_root->right, visit); } } template <class Entry> void Binary_tree<Entry>::recursive_postorder(Binary_node<Entry> *sub_root, void (*visit)(Entry &)) /* Pre: sub_root is either NULL or points to a subtree of the Binary_tree. Post: The subtree has been traversed in postorder sequence. Uses: The function recursive_postorder recursively */ { if (sub_root != NULL) { recursive_postorder(sub_root->left, visit); recursive_postorder(sub_root->right, visit); (*visit)(sub_root->data); } } template <class Entry> void Binary_tree<Entry>::A(void (*visit)(Entry &)) { if (root != NULL) { (*visit)(root->data); root->left.B(visit); root->right.B(visit); } } template <class Entry> void Binary_tree<Entry>::B(void (*visit)(Entry &)) { if (root != NULL) { root->left.A(visit); (*visit)(root->data); root->right.A(visit); } } template <class Entry> int Binary_tree<Entry>::size() //const { return size1(root); } template <class Entry> int Binary_tree<Entry>::size1(const Binary_node<Entry> *root1) { if(root1 == NULL) return 0; if(root1 ->left == NULL&&root1->right == NULL) return 1; return size1(root1->left) + size1(root1->right)+1; } template <class Entry> void Binary_tree<Entry>::clear() { clear1(root); delete root; root = NULL; } template <class Entry> void Binary_tree<Entry>::clear1(const Binary_node<Entry> * &root1) { if(root1==NULL||root1->left == NULL&&root->right == NULL) return; Binary_node<Entry> *p= root1->left,*q= root1->right; if(p!=NULL){ if (p->left != NULL||p->right != NULL) clear1(p); delete p; } if(q!=NULL){ if(q->left != NULL||q->right != NULL) clear1(q); delete q; } } template <class Entry> int Binary_tree<Entry>::height() { Binary_node<Entry> *root1=root; return height1(root1); } template <class Entry> int Binary_tree<Entry>::height1(const Binary_node<Entry> *root1) { if(root1 == NULL) return 0; if(root1->left == NULL&&root1->right==NULL) return 1; return MAX(height1(root1->left),height1(root1->right))+1; } template <class Entry> int Binary_tree<Entry>::MAX(int x,int y)const { if(x > y) return x; else return y; } template <class Entry> void Binary_tree<Entry>::insert(const Entry &entry) { Binary_node<Entry> *root1; Binary_node<Entry> *ss=new Binary_node<Entry>; ss->data=entry; ss->left = ss->right =NULL; if(root == NULL){ root = ss; } else{ root1 = root; while(root1 != NULL){ if(entry < root1->data){ if(root1 ->left == NULL){ root1->left = ss; root1 = NULL; } else root1 = root1->left; } else if(entry > root1->data){ if(root1 ->right == NULL){ root1->right = ss; root1 = NULL; } else root1 = root1->right; } else root1 = NULL; } } } template <class Entry> void Binary_tree<Entry>::print()const { Queue QQ; QQ.append(root); Binary_node<Entry>* p; QQ.retrieve(p); while(!QQ.empty()){ cout<<p->data<<' '; QQ.serve(); if(p->left!=NULL) QQ.append(p->left); if(p->right!=NULL) QQ.append(p->right); QQ.retrieve(p); } } /* template <class Entry> Binary_tree<Entry>::insert(const Entry &entry) { Binary_node<Entry> ss=3,aa=2,bb=3; root=&ss; root->left = &aa; root->right = &bb; } */ //template <class Entry> //Binary_tree<Entry>::Binary_tree (const Binary_tree<Entry> &original); //template <class Entry> //Binary_tree<Entry>::Binary_tree & operator =(const Binary_tree<Entry> &original); class Key { protected: int key; public: static int comparisons; Key( int x = 0); int the_key() const; }; Key::Key( int x ) { key = x; } int Key:: the_key() const { return key; } bool operator ==(const Key &x,const Key &y); bool operator >(const Key &x,const Key &y); bool operator <(const Key &x,const Key &y); bool operator >=(const Key &x,const Key &y); bool operator <=(const Key &x,const Key &y); bool operator !=(const Key &x,const Key &y); bool operator ==(const Key &x, const Key &y) { Key::comparisons++; return x.the_key() == y.the_key(); } bool operator <(const Key &x, const Key &y) { Key::comparisons++; return x.the_key() < y.the_key(); } bool operator >(const Key &x, const Key &y) { Key::comparisons++; return x.the_key() > y.the_key(); } bool operator >=(const Key &x, const Key &y) { Key::comparisons++; return x.the_key() >= y.the_key(); } bool operator <=(const Key &x, const Key &y) { Key::comparisons++; return x.the_key() <= y.the_key(); } bool operator !=(const Key &x, const Key &y) { Key::comparisons++; return x.the_key() != y.the_key(); } int Key::comparisons = 0; typedef Key Record; ///////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// template <class Record> class Search_tree: public Binary_tree<Record> { public: Error_code insert(const Record &new_data); Error_code remove(const Record &old_data); Error_code tree_search(Record &target) const; Binary_node<Record> *search_for_node(Binary_node<Record>* sub_root, const Record &target) const; Error_code search_and_insert(Binary_node<Record> *&sub_root, const Record &new_data); Error_code remove_root(Binary_node<Record>*&sub_root); Error_code search_and_destroy(Binary_node<Record>* &sub_root, const Record &target); private: // Add auxiliary function prototypes here. }; //////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// template <class Record> Binary_node<Record> *Search_tree<Record>::search_for_node( Binary_node<Record>* sub_root, const Record &target) const { if (sub_root == NULL || sub_root->data == target) return sub_root; else if (sub_root->data < target) return search_for_node(sub_root->right, target); else return search_for_node(sub_root->left, target); } template <class Record> Error_code Search_tree<Record>::tree_search(Record &target) const /* Post: If there is an entry in the tree whose key matches that in target, the parameter target is replaced by the corresponding record from the tree and a code of success is returned. Otherwise a code of not_present is returned. Uses: function search_for_node */ { Error_code result = success; Binary_node<Record> *found = search_for_node(root, target); if (found == NULL) result = not_present; else target = found->data; return result; } template <class Record> Error_code Search_tree<Record>::insert(const Record &new_data) { return search_and_insert(root, new_data); } template <class Record> Error_code Search_tree<Record>::search_and_insert( Binary_node<Record> *&sub_root, const Record &new_data) { if (sub_root == NULL) { sub_root = new Binary_node<Record>(new_data); return success; } else if (new_data < sub_root->data) return search_and_insert(sub_root->left, new_data); else if (new_data > sub_root->data) return search_and_insert(sub_root->right, new_data); else return duplicate_error; } template <class Record> Error_code Search_tree<Record>::remove_root(Binary_node<Record> *&sub_root) /* Pre: sub_root is either NULL or points to a subtree of the Search_tree. Post: If sub_root is NULL, a code of not_present is returned. Otherwise, the root of the subtree is removed in such a way that the properties of a binary search tree are preserved. The parameter sub_root is reset as the root of the modified subtree, and success is returned. */ { if (sub_root == NULL) return not_present; Binary_node<Record> *to_delete = sub_root; // Remember node to delete at end. if (sub_root->right == NULL) sub_root = sub_root->left; else if (sub_root->left == NULL) sub_root = sub_root->right; else { // Neither subtree is empty. to_delete = sub_root->left; // Move left to find predecessor. Binary_node<Record> *parent = sub_root; // parent of to_delete while (to_delete->right != NULL) { // to_delete is not the predecessor. parent = to_delete; to_delete = to_delete->right; } sub_root->data = to_delete->data; // Move from to_delete to root. if (parent == sub_root) sub_root->left = to_delete->left; else parent->right = to_delete->left; } delete to_delete; // Remove to_delete from tree. return success; } template <class Record> Error_code Search_tree<Record>::remove(const Record &target) /* Post: If a Record with a key matching that of target belongs to the Search_tree, a code of success is returned, and the corresponding node is removed from the tree. Otherwise, a code of not_present is returned. Uses: Function search_and_destroy */ { return search_and_destroy(root, target); } template <class Record> Error_code Search_tree<Record>::search_and_destroy( Binary_node<Record>* &sub_root, const Record &target) /* Pre: sub_root is either NULL or points to a subtree of the Search_tree. Post: If the key of target is not in the subtree, a code of not_present is returned. Otherwise, a code of success is returned and the subtree node containing target has been removed in such a way that the properties of a binary search tree have been preserved. Uses: Functions search_and_destroy recursively and remove_root */ { if (sub_root == NULL || sub_root->data == target) return remove_root(sub_root); else if (target < sub_root->data) return search_and_destroy(sub_root->left, target); else return search_and_destroy(sub_root->right, target); } // Section 10.3: //////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// template <class Record> class Buildable_tree: public Search_tree<Record> { public: Error_code build_tree(const List<Record> &supply); void build_insert(int count,const Record &new_data,List<Binary_node<Record>*> &last_node); Binary_node<Record> *find_root(List<Binary_node<Record>*> &last_node); void connect_trees(const List<Binary_node<Record>*> &last_node); private: // Add auxiliary function prototypes here. }; //////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// template <class Record> Error_code Buildable_tree<Record>::build_tree(const List<Record> &supply) /* Post: If the entries of supply are in increasing order, a code of success is returned and the Search_tree is built out of these entries as a balanced tree. Otherwise, a code of fail is returned and a balanced tree is constructed from the longest increasing sequence of entries at the start of supply. Uses: The methods of class List and the functions build_insert, connect_subtrees, and find_root */ { Error_code ordered_data = success; // Set this to fail if keys do not increase. int count = 0; // number of entries inserted so far Record x, last_x; List<Binary_node<Record> *> last_node; // pointers to last nodes on each level Binary_node<Record> *none = NULL; last_node.insert(0, none); // permanently NULL (for children of leaves) while (supply.retrieve(count, x) == success) { if (count > 0 && x <= last_x) { ordered_data = fail; break; } build_insert(++count, x, last_node); last_x = x; } root = find_root(last_node); connect_trees(last_node); return ordered_data; // Report any data-ordering problems back to client. } template <class Record> void Buildable_tree<Record>::build_insert(int count, const Record &new_data, List<Binary_node<Record>*> &last_node) /* Post: A new node, containing the Record new_data, has been inserted as the rightmost node of a partially completed binary search tree. The level of this new node is one more than the highest power of 2 that divides count. Uses: Methods of class List */ { int level; // level of new node above the leaves, counting inclusively for (level = 1; count % 2 == 0; level++) count /= 2; // Use count to calculate level of next_node. Binary_node<Record> *next_node = new Binary_node<Record>(new_data), *parent; // one level higher in last_node last_node.retrieve(level - 1, next_node->left); if (last_node.size() <= level) last_node.insert(level, next_node); else last_node.replace(level, next_node); if (last_node.retrieve(level + 1, parent) == success && parent->right == NULL) parent->right = next_node; } template <class Record> Binary_node<Record> *Buildable_tree<Record>::find_root( List<Binary_node<Record>*> &last_node) /* Pre: The list last_node contains pointers to the last node on each occupied level of the binary search tree. Post: A pointer to the root of the newly created binary search tree is returned. Uses: Methods of class List */ { Binary_node<Record> *high_node; last_node.retrieve(last_node.size() - 1, high_node); // Find root in the highest occupied level in last_node. return high_node; } template <class Record> void Buildable_tree<Record>::connect_trees( const List<Binary_node<Record>*> &last_node) /* Pre: The nearly-completed binary search tree has been initialized. The List last_node has been initialized and contains links to the last node on each level of the tree. Post: The final links have been added to complete the binary search tree. Uses: Methods of class List */ { Binary_node<Record> *high_node, // from last_node with NULL right child *low_node; // candidate for right child of high_node int high_level = last_node.size() - 1, low_level; while (high_level > 2) { // Nodes on levels 1 and 2 are already OK. last_node.retrieve(high_level, high_node); if (high_node->right != NULL) high_level--; // Search down for highest dangling node. else { // Case: undefined right tree low_level = high_level; do { // Find the highest entry not in the left subtree. last_node.retrieve(--low_level, low_node); } while (low_node != NULL && low_node->data < high_node->data); high_node->right = low_node; high_level = low_level; } } } // Section 10.4: /* enum Balance_factor { left_higher, equal_height, right_higher }; template <class Record> struct AVL_node: public Binary_node<Record> { // additional data member: Balance_factor balance; // constructors: AVL_node(); AVL_node(const Record &x); // overridden virtual functions: void set_balance(Balance_factor b); Balance_factor get_balance() const; }; template <class Record> void AVL_node<Record>::set_balance(Balance_factor b) { balance = b; } template <class Record> Balance_factor AVL_node<Record>::get_balance() const { return balance; } template <class Entry> struct Binary_node { // data members: Entry data; Binary_node<Entry> *left; Binary_node<Entry> *right; // constructors: Binary_node(); Binary_node(const Entry &x); // virtual methods: virtual void set_balance(Balance_factor b); virtual Balance_factor get_balance() const; }; template <class Entry> void Binary_node<Entry>::set_balance(Balance_factor b) { } template <class Entry> Balance_factor Binary_node<Entry>::get_balance() const { return equal_height; } template <class Record> class AVL_tree: public Search_tree<Record> { public: Error_code insert(const Record &new_data); Error_code remove(const Record &old_data); private: // Add auxiliary function prototypes here. }; template <class Record> Error_code AVL_tree<Record>::insert(const Record &new_data) /* Post: If the key of new_data is already in the AVL_tree, a code of duplicate_error is returned. Otherwise, a code of success is returned and the Record new_data is inserted into the tree in such a way that the properties of an AVL tree are preserved. Uses: avl_insert. * { bool taller; return avl_insert(root, new_data, taller); } template <class Record> Error_code AVL_tree<Record>::avl_insert(Binary_node<Record> *&sub_root, const Record &new_data, bool &taller) /* Pre: sub_root is either NULL or points to a subtree of the AVL_tree Post: If the key of new_data is already in the subtree, a code of duplicate_error is returned. Otherwise, a code of success is returned and the Record new_data is inserted into the subtree in such a way that the properties of an AVL tree have been preserved. If the subtree is increased in height, the parameter taller is set to true; otherwise it is set to false. Uses: Methods of struct AVL_node; functions avl_insert recursively, left_balance, and right_balance. * { Error_code result = success; if (sub_root == NULL) { sub_root = new AVL_node<Record>(new_data); taller = true; } else if (new_data == sub_root->data) { result = duplicate_error; taller = false; } else if (new_data < sub_root->data) { // Insert in left subtree. result = avl_insert(sub_root->left, new_data, taller); if (taller == true) switch (sub_root->get_balance()) {// Change balance factors. case left_higher: left_balance(sub_root); taller = false; // Rebalancing always shortens the tree. break; case equal_height: sub_root->set_balance(left_higher); break; case right_higher: sub_root->set_balance(equal_height); taller = false; break; } } else { // Insert in right subtree. result = avl_insert(sub_root->right, new_data, taller); if (taller == true) switch (sub_root->get_balance()) { case left_higher: sub_root->set_balance(equal_height); taller = false; break; case equal_height: sub_root->set_balance(right_higher); break; case right_higher: right_balance(sub_root); taller = false; // Rebalancing always shortens the tree. break; } } return result; } template <class Record> void AVL_tree<Record>::rotate_left(Binary_node<Record> *&sub_root) /* Pre: sub_root points to a subtree of the AVL_tree. This subtree has a nonempty right subtree. Post: sub_root is reset to point to its former right child, and the former sub_root node is the left child of the new sub_root node. * { if (sub_root == NULL || sub_root->right == NULL) // impossible cases cout << "WARNING: program error detected in rotate_left" << endl; else { Binary_node<Record> *right_tree = sub_root->right; sub_root->right = right_tree->left; right_tree->left = sub_root; sub_root = right_tree; } } template <class Record> void AVL_tree<Record>::right_balance(Binary_node<Record> *&sub_root) /* Pre: sub_root points to a subtree of an AVL_tree that is doubly unbalanced on the right. Post: The AVL properties have been restored to the subtree. Uses: Methods of struct AVL_node; functions rotate_right and rotate_left. * { Binary_node<Record> *&right_tree = sub_root->right; switch (right_tree->get_balance()) { case right_higher: // single rotation left sub_root->set_balance(equal_height); right_tree->set_balance(equal_height); rotate_left(sub_root); break; case equal_height: // impossible case cout << "WARNING: program error detected in right_balance" << endl; case left_higher: // double rotation left Binary_node<Record> *sub_tree = right_tree->left; switch (sub_tree->get_balance()) { case equal_height: sub_root->set_balance(equal_height); right_tree->set_balance(equal_height); break; case left_higher: sub_root->set_balance(equal_height); right_tree->set_balance(right_higher); break; case right_higher: sub_root->set_balance(left_higher); right_tree->set_balance(equal_height); break; } sub_tree->set_balance(equal_height); rotate_right(right_tree); rotate_left(sub_root); break; } } // Section 10.5: template <class Record> class Splay_tree:public Search_tree<Record> { public: Error_code splay(const Record &target); private: // Add auxiliary function prototypes here. }; template <class Record> void Splay_tree<Record>::link_right(Binary_node<Record> *&current, Binary_node<Record> *&first_large) /* Pre: The pointer first_large points to an actual Binary_node (in particular, it is not NULL). The three-way invariant holds. Post: The node referenced by current (with its right subtree) is linked to the left of the node referenced by first_large. The pointer first_large is reset to current. The three-way invariant continues to hold. * { first_large->left = current; first_large = current; current = current->left; } template <class Record> void Splay_tree<Record>::link_left(Binary_node<Record> *&current, Binary_node<Record> *&last_small) /* Pre: The pointer last_small points to an actual Binary_node (in particular, it is not NULL). The three-way invariant holds. Post: The node referenced by current (with its left subtree) is linked to the right of the node referenced by last_small. The pointer last_small is reset to current. The three-way invariant continues to hold. * { last_small->right = current; last_small = current; current = current->right; } template <class Record> void Splay_tree<Record>::rotate_right(Binary_node<Record> *&current) /* Pre: current points to the root node of a subtree of a Binary_tree. This subtree has a nonempty left subtree. Post: current is reset to point to its former left child, and the former current node is the right child of the new current node. * { Binary_node<Record> *left_tree = current->left; current->left = left_tree->right; left_tree->right = current; current = left_tree; } template <class Record> void Splay_tree<Record>::rotate_left(Binary_node<Record> *&current) /* Pre: current points to the root node of a subtree of a Binary_tree. This subtree has a nonempty right subtree. Post: current is reset to point to its former right child, and the former current node is the left child of the new current node. * { Binary_node<Record> *right_tree = current->right; current->right = right_tree->left; right_tree->left = current; current = right_tree; } template <class Record> Error_code Splay_tree<Record>::splay(const Record &target) /* Post: If a node of the splay tree has a key matching that of target, it has been moved by splay operations to be the root of the tree, and a code of entry_found is returned. Otherwise, a new node containing a copy of target is inserted as the root of the tree, and a code of entry_inserted is returned. * { Binary_node<Record> *dummy = new Binary_node<Record>; Binary_node<Record> *current = root, *child, *last_small = dummy, *first_large = dummy; // Search for target while splaying the tree. while (current != NULL && current->data != target) if (target < current->data) { child = current->left; if (child == NULL || target == child->data) // zig move link_right(current, first_large); else if (target < child->data) { // zig-zig move rotate_right(current); link_right(current, first_large); } else { // zig-zag move link_right(current, first_large); link_left(current, last_small); } } else { // case: target > current->data child = current->right; if (child == NULL || target == child->data) link_left(current, last_small); // zag move else if (target > child->data) { // zag-zag move rotate_left(current); link_left(current, last_small); } else { // zag-zig move link_left(current, last_small); link_right(current, first_large); } } // Move root to the current node, which is created if necessary. Error_code result; if (current == NULL) { // Search unsuccessful: make a new root. current = new Binary_node<Record>(target); result = entry_inserted; last_small->right = first_large->left = NULL; } else { // successful search result = entry_found; last_small->right = current->left; // Move remaining central nodes. first_large->left = current->right; } root = current; // Define the new root. root->right = dummy->left; // root of larger-key subtree root->left = dummy->right; // root of smaller-key subtree delete dummy; return result; } /*************************************************************************/ typedef Binary_node<int>* Queue_entry; const int maxqueue=10; class Queue{ public: Queue(); bool empty() const; Error_code serve(); Error_code append(const Queue_entry &item); Error_code retrieve(Queue_entry &item) const; int size(); protected: int count; int front,rear; Queue_entry entry[maxqueue]; }; Queue::Queue() { count=0; rear=maxqueue-1; front=0; } bool Queue::empty() const { return count==0; } Error_code Queue::append(const Queue_entry &item) { if(count>=maxqueue) return overflow; count++; rear=((rear+1)==maxqueue)?0:(rear+1); entry[rear]=item; return success; } Error_code Queue::serve() { if(count<=0) return underflow; count--; front=((front+1)==maxqueue)?0:(front+1); return success; } Error_code Queue::retrieve(Queue_entry &item) const { if(count<=0) return overflow; item=entry[front]; return success; } int Queue::size() { return count; }
[ "aidedaijiayang@126.com" ]
aidedaijiayang@126.com
d1cedb07ace7cf9813fd0dfa4958d1ec048dedff
fbbf0cd2ae78703683926ecec28270393713a82d
/15. 3Sum/3sum.cpp
85a09133662109dcdfb8664788b8d14d1d225eeb
[]
no_license
BGMer7/LeetCode
869fde712a058b0fe9fa8c08b691b889ad65ddc0
7505b55ffd9a4819ece0bd9f723e4c63a9e0c1c6
refs/heads/master
2023-07-25T02:00:36.428625
2023-07-12T09:05:10
2023-07-12T09:05:10
234,691,935
0
0
null
null
null
null
GB18030
C++
false
false
1,311
cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> ans; int n = nums.size(); for (int i = 0; i < n - 2; i++) { if (nums[i] > 0) break; if (i > 0 && nums[i] == nums[i - 1]) continue; //Apply Binary search int left = i + 1; int right = n - 1; while (left < right) { //found a triplet //update left and right if (nums[i] + nums[left] + nums[right] == 0) { ans.push_back({ nums[i], nums[left], nums[right] }); left++; right--; //avoid duplicates while (left < right && nums[left] == nums[left - 1]) left++; while (left < right && nums[right] == nums[right + 1]) right--; } else if (nums[i] + nums[left] + nums[right] < 0) { left++; } else { right--; } } } return ans; } }; int main() { Solution s; int a[6] = { 1,-1,-3,3,0,6 }; vector<int> b; //将a的所有元素插入到b中 b.insert(b.begin(), a, a + 7); vector<vector<int>> ans; ans = s.threeSum(b); cout << ans.size() << endl; for (vector<vector<int>>::iterator it = ans.begin(); it != ans.end(); ++it) { for (int i = 0; i < (*it).size(); ++i) { cout << (*it)[i] << " "; } } }
[ "Caijinyang98@gmail.com" ]
Caijinyang98@gmail.com
b6d2c88782e29904e324646a937dab9fe4bb49ac
b3d0347e903799a71a46ab6fa786a88575ed5dc4
/Pion_gen.cc
93fd3da4228e49d4ec53ec6b7ca7a5b781dcc4d0
[]
no_license
danielepannozzo/HNL-start
d86ef58f4d67f5a7d9ca557f9b7c5fd652ffac83
9893463d7ecc225f7ba9833edaee547cecf9753b
refs/heads/main
2023-03-19T09:57:40.402077
2021-03-10T13:14:58
2021-03-10T13:14:58
341,534,355
0
0
null
null
null
null
UTF-8
C++
false
false
2,458
cc
#include <iostream> #include <cmath> #include "TVector3.h" #include "TFile.h" #include "HNLClass.h" #include "TChain.h" #include "TH1F.h" #include "TCanvas.h" #include "TLorentzVector.h" #include "math.h" int main() { TChain* cosa = new TChain("Events"); cosa->Add("HNLDP.root"); HNLClass signal; signal.Init(cosa); int i=0,j=0,l=0; /*TH1F *pt = new TH1F("Pi(all)_pt","Pt of all pions",250,0.,20.0); TH1F *eta = new TH1F("Pi(all)_eta", "Eta of all pions", 250, -6.5,6.5); TH1F *pt_n = new TH1F("Pi(/HNL)_pt", "Pt of pions not from HNL", 250, 0., 20.); TH1F *eta_n = new TH1F("Pi(/HNL)_eta", "Eta of pions not from HNL", 250, -6.5,6.5);*/ TH1F *Npi = new TH1F("#E", "# of pions in the event", 5000, 0., 12.3); //TCanvas *PtEta = new TCanvas("PtEta","Pion pt eta", 1280, 1024); //PtEta->Divide(2,2); TCanvas *c2 = new TCanvas("c2","Number of pions", 1280, 1024); for(i=0;i<signal.fChain->GetEntries();i++) { signal.fChain->GetEntry(i); l=0; for(j=0;j<signal.nGenPart;j++){ if(abs(signal.GenPart_pdgId[j])==211){ l+=1; //pt->Fill(signal.GenPart_pt[j]); //eta->Fill(signal.GenPart_eta[j]); }; /*if(abs(signal.GenPart_pdgId[j])==211 && abs(signal.GenPart_pdgId[signal.GenPart_genPartIdxMother[j]])!=9900015){ pt_n->Fill(signal.GenPart_pt[j]); eta_n->Fill(signal.GenPart_eta[j]); };*/ }; Npi->Fill(l); }; /*PtEta->cd(1); pt->GetXaxis()->SetTitle("Pt [GeV]"); pt->GetYaxis()->SetTitle("Number of entries"); pt->Draw("HIST"); PtEta->cd(2); eta->GetXaxis()->SetTitle("Eta"); eta->GetYaxis()->SetTitle("Number of entries"); eta->Draw("HIST"); PtEta->cd(3); pt_n->GetXaxis()->SetTitle("Pt [GeV]"); pt_n->GetYaxis()->SetTitle("Number of entries"); pt_n->Draw("HIST"); PtEta->cd(4); eta_n->GetXaxis()->SetTitle("Eta"); eta_n->GetYaxis()->SetTitle("Number of entries"); eta_n->Draw("HIST");*/ c2->cd(1); Npi->GetXaxis()->SetTitle("# electrons in the event"); Npi->GetYaxis()->SetTitle("# entries"); Npi->Draw("HIST"); //PtEta->SaveAs("Pi_pt_eta.png"); c2->SaveAs("Numb_Pi.png"); delete cosa; return 0; };
[ "noreply@github.com" ]
noreply@github.com
640034f4ad5ecf4d9000e9f9dae82b585ab02eb5
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5688567749672960_1/C++/Stonefeang/zad.cpp
f960ebd1f94094d535ed3baac7b46c129d547b1b
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,196
cpp
#include <cstdio> #include <queue> #include <cmath> using namespace std; int t; long long n; int tab[1000007]; long long rew(long long v) { long long ret=0; while(v) { ret*=10; ret+=v%10; v/=10; } return ret; } int ilec(long long v) { int ret=0; while(v) { ret++; v/=10; } return ret; } queue <int> kol; int u; long long wyn; long long v; long long wyn1, wyn2; long long pier, pier2; int main() { for (int i=1; i<=1000000; i++) { tab[i]=i+1; } kol.push(0); while(!kol.empty()) { u=kol.front(); kol.pop(); if (tab[u+1]>tab[u]+1) { tab[u+1]=tab[u]+1; kol.push(u+1); } if (tab[rew(u)]>tab[u]+1) { tab[rew(u)]=tab[u]+1; kol.push(rew(u)); } } scanf("%d", &t); for (int i=1; i<=t; i++) { scanf("%lld", &n); if (n<=10000) { printf("Case #%d: %d\n", i, tab[n]); continue; } v=10000; wyn=tab[10000]; while(1) { if (ilec(v)<ilec(n)) { if (ilec(v)&1) { pier=sqrt(v); pier2=sqrt(v*100); } else { pier=sqrt(v*10); pier2=pier; } wyn+=pier+pier2-1; //printf("%lld %lld %lld %d\n", pier, pier2, v, ilec(v)); v*=10; continue; } wyn1=wyn+n-v; if (ilec(v)&1) { pier=sqrt(v); pier2=sqrt(v*100); } else { pier=sqrt(v*10); pier2=pier; } //printf("%lld %lld %lld %d\n", pier, pier2, v, ilec(v)); //printf("%lld %lld\n", (n%pier), (rew(n)%pier2)); wyn2=wyn+(n%pier)+(rew(n)%pier2); v=n; break; } printf("Case #%d: %lld\n", i, min(wyn1, wyn2)); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
25e13c33c71d87fd582961ed5db26dd8a740e88e
5d499c419cbf398ba8f97a51f747368f58a3f8cf
/Pendulum_practical_2/Pendulum_practical_2.ino
966b99d8e888da8d7c3c060eb28f46b79f538698
[]
no_license
Jankd90/Arduino
9e0fce06f2aa55c6a70a0873e094e1df531a0d4f
c7e1bc4955c0f3347128b76e5002e5574c550df2
refs/heads/master
2022-07-17T13:41:19.170080
2020-05-14T14:56:40
2020-05-14T14:56:40
263,942,961
0
0
null
null
null
null
UTF-8
C++
false
false
1,731
ino
/* Include the library */ #include "HCMotor.h" /* Pins used to drive the motors */ #define MOTOR_PINA 8 //For HCMODU0033 connect to A-IA, for HCARDU0013 connect to IN1 #define MOTOR_PINB 9 //For HCMODU0033 connect to A-IB, for HCARDU0013 connect to IN2 int incomingByte = 0; int tik = 0; int dif = 2000; int d, on, speed = 0; /* Create an instance of the library */ HCMotor HCMotor; void setup() { pinMode(LED_BUILTIN, OUTPUT); /* Initialise the library */ HCMotor.Init(); Serial.begin(115200); /* Attach motor 0 to digital pins 8 & 9. The first parameter specifies the motor number, the second is the motor type, and the third and forth are the digital pins that will control the motor */ HCMotor.attach(0, DCMOTOR_H_BRIDGE, MOTOR_PINA, MOTOR_PINB); /* Set the duty cycle of the PWM signal in 100uS increments. Here 100 x 100uS = 1mS duty cycle. */ HCMotor.DutyCycle(0, 100); } void loop() { if (Serial.available() > 0) { // read the incoming byte: int incomingByte = Serial.parseInt(); Serial.println("byte"); Serial.println(incomingByte); if(incomingByte > 0){ if((incomingByte/10000)-1 == 0){ d = REVERSE; on = (incomingByte % 10000); speed = incomingByte %100; } else{ d = FORWARD; on = (incomingByte % 20000); speed = incomingByte %100; } HCMotor.Direction(0, d); HCMotor.OnTime(0,200); delay(on); HCMotor.OnTime(0,0); } // say what you got: Serial.println("ON"); Serial.println(on); Serial.println("Speed"); Serial.println(speed); digitalWrite(LED_BUILTIN, HIGH); digitalWrite(LED_BUILTIN, LOW); } }
[ "jan@kaios.ai" ]
jan@kaios.ai
b40a47379087ae7a532f6cb8d79bf09b26d33b62
05f7573db159e870fb26c847991c4cb8c407ed4c
/VBF/Source/VBF_CORE4.0/VBF_Interface/Types/VBF_ConvexPlanarPolygon.h
8270404782adaff256dff757965e4eee6dc52045
[]
no_license
riyue625/OneGIS.ModelingTool
e126ef43429ce58d22c65832d96dbd113eacbf85
daf3dc91584df7ecfed6a51130ecdf6671614ac4
refs/heads/master
2020-05-28T12:12:43.543730
2018-09-06T07:42:00
2018-09-06T07:42:00
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,401
h
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #ifndef OSG_CONVEXPLANARPOLYGON #define OSG_CONVEXPLANARPOLYGON 1 #include <Types/VBF_Plane.h> #include <vector> namespace osg { /** A class for representing components of convex clipping volumes. */ class OSG_EXPORT ConvexPlanarPolygon { public: ConvexPlanarPolygon(){}// IE¿ÉÄÜ´íÎó typedef std::vector<osg::Vec3> VertexList; void add(const Vec3& v) { _vertexList.push_back(v); } void setVertexList(const VertexList& vertexList) { _vertexList=vertexList; } VertexList& getVertexList() { return _vertexList; } const VertexList& getVertexList() const { return _vertexList; } protected: VertexList _vertexList; }; } // end of namespace #endif
[ "robertsam@126.com" ]
robertsam@126.com
4d574ac15dbc19618745d827bb219269dfd655de
cf4558af4c716ec1e5a7870b31409334c72f8ca9
/prj/Rollover.cpp
9066bcadd6a8ad2f30100fe4da4bdb6a5ea01caf
[]
no_license
Dartanum/Course_Task
5fccc1b8e2fc7b8e28af23bc1b968555aa21ba21
e0fa74eecfbc203fe8084139f1511f2426775dd5
refs/heads/master
2023-03-27T06:57:05.495930
2021-03-27T09:43:04
2021-03-27T09:43:04
324,534,887
0
0
null
null
null
null
UTF-8
C++
false
false
2,649
cpp
#include "Rollover.h" Rollover::Rollover(Texture* textureLine, Texture* textureSlider, IntRect rectSlider, Vector2f sizeLine, int beginProcess, Font& font, int charSize) { line.setSize(sizeLine); line.setOrigin(0, sizeLine.y / 2); line.setTexture(textureLine); length = sizeLine.x; slider.setTexture(textureSlider); slider.setTextureRect(rectSlider); slider.setSize(Vector2f(line.getSize().x / 10, line.getSize().x / 8)); slider.setOrigin(slider.getSize().x / 2, 0); process = beginProcess; processText.setFont(font); processText.setFillColor(Color::Black); processText.setString(std::to_string(process)); processText.setCharacterSize(charSize); processText.setOrigin(processText.getGlobalBounds().width / 2, processText.getGlobalBounds().height / 2); isPressed = false; } void Rollover::setPos(Vector2f pos) { position = pos; line.setPosition(pos); processText.setPosition(position.x + length + slider.getSize().x * 2, position.y); slider.setPosition(setCurrentVolume(process), position.y); containerSlider = IntRect(slider.getPosition().x - slider.getSize().x / 2, slider.getPosition().y, slider.getSize().x, slider.getSize().y); containerLine = IntRect(line.getPosition().x, line.getPosition().y - line.getSize().y / 2, line.getSize().x, line.getSize().y); finishLineX = position.x + length; } void Rollover::updateContainer() { containerSlider = IntRect(slider.getPosition().x - slider.getSize().x / 2, slider.getPosition().y, slider.getSize().x, slider.getSize().y); } void Rollover::listen(RenderWindow& window, Event& event) { if (event.type == Event::MouseButtonPressed && containerSlider.contains(Mouse::getPosition(window)) && event.mouseButton.button == Mouse::Left) { slider.setFillColor(Color::Green); isPressed = true; } if (event.type == Event::MouseButtonReleased) { slider.setFillColor(Color::White); isPressed = false; } if (event.type == Event::MouseMoved && isPressed) { if (event.mouseMove.x >= finishLineX) { slider.setPosition(finishLineX, position.y); } else if (event.mouseMove.x <= position.x) { slider.setPosition(position.x, position.y); } else slider.setPosition(event.mouseMove.x, position.y); updateContainer(); updateProcess(); } } float Rollover::setCurrentVolume(int volume) { return line.getPosition().x + (length / 100.0 * volume); } int Rollover::getCurrentVolume(float currentPos) { return 100.0 / length * (slider.getPosition().x - position.x); } void Rollover::updateProcess() { process = getCurrentVolume(slider.getPosition().x); processText.setString(std::to_string(process)); }
[ "dartanum2@yandex.ru" ]
dartanum2@yandex.ru
6f76def82342297c96f42f8efd028f1f92d9befe
59b2f9eb7695ef8292c0833ab4df2e96397f98b4
/src/shader_s.h
ab8280a934efcea2e13f0bb879956e5b83a76e30
[]
no_license
lanyu1zhi/LearnOpenGL
3124e09b05cea8be62fd56b7a2a888e247e52ed6
f54c8e8e37b47180fd9ce16fa196464d966683f8
refs/heads/main
2023-07-08T18:42:27.713473
2021-08-15T06:28:24
2021-08-15T06:28:24
387,725,550
0
0
null
null
null
null
UTF-8
C++
false
false
4,917
h
#pragma once #include "glad/glad.h" #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include <string> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <direct.h> class Shader { public: unsigned int ID; Shader(const char* vertexPath, const char* fragmentPath) { // retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::ifstream vShaderFile; std::ifstream fShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch(std::ifstream::failure& a) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char* fShaderCode = fragmentCode.c_str(); // compile shaders unsigned int vertex, fragment; // vertex shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); checkCompileErrors(vertex, "VERTEX"); // fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); checkCompileErrors(fragment, "FRAGMENT"); // shader Program ID = glCreateProgram(); glAttachShader(ID, vertex); glAttachShader(ID, fragment); glLinkProgram(ID); checkCompileErrors(ID, "PROGRAM"); // delete the shaders as they're linked into our program now and no longer necessary glDeleteShader(vertex); glDeleteShader(fragment); } void use() { glUseProgram(ID); } void setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value); } void setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(ID, name.c_str()), value); } void setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(ID, name.c_str()), value); } void setMat4(const std::string &name, glm::mat4 mat) const { glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, glm::value_ptr(mat)); } void setVec3(const std::string &name, float x, float y, float z) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z); } void setVec3(const std::string &name, glm::vec3 vec3) const { glUniform3f(glGetUniformLocation(ID, name.c_str()), vec3.x, vec3.y, vec3.z); } private: // utility function for checking shader compilation/linking errors. void checkCompileErrors(unsigned int shader, std::string type) { int success; char infoLog[1024]; if(type != "PROGRAM") { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if(!success) { glGetProgramInfoLog(shader, 1024, NULL, infoLog); std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl; } } } };
[ "790872105@qq.com" ]
790872105@qq.com
ba2abdeb2084b12bfaeeee2d78b38705b0ad6b91
8465159705a71cede7f2e9970904aeba83e4fc6c
/build/src_gen/F_SUB_DATE_DATE_gen.cpp
ceaa271ca68f25bb580e531b0d9db287b222ba3a
[]
no_license
TuojianLYU/forte_IO_OPCUA_Integration
051591b61f902258e3d0d6608bf68e2302f67ac1
4a3aed7b89f8a7d5f9554ac5937cf0a93607a4c6
refs/heads/main
2023-08-20T16:17:58.147635
2021-10-27T05:34:43
2021-10-27T05:34:43
419,704,624
1
0
null
null
null
null
UTF-8
C++
false
false
1,060
cpp
/******************************************************************************* * Copyright (c) 2012 Profactor GmbH * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Michael Hofmann * - initial API and implementation and/or initial documentation *******************************************************************************/ //!!!autogenerated code - DO NOT EDIT!!! extern const CStringDictionary::TStringId g_nStringIdCNF; extern const CStringDictionary::TStringId g_nStringIdDATE; extern const CStringDictionary::TStringId g_nStringIdF_SUB_DATE_DATE; extern const CStringDictionary::TStringId g_nStringIdIN1; extern const CStringDictionary::TStringId g_nStringIdIN2; extern const CStringDictionary::TStringId g_nStringIdOUT; extern const CStringDictionary::TStringId g_nStringIdREQ; extern const CStringDictionary::TStringId g_nStringIdTIME;
[ "tuojianlyu@gmail.com" ]
tuojianlyu@gmail.com
8d01560c9199b33b7c94d32cb45bf2ed9321f7e6
10a22b62a6df5464cec7d03b1ee9f3e388bdc6ea
/Programme Drone/Fonction.h
723004c83ffdb48394571bc2770e2faa78f8798d
[]
no_license
MorS25/ELVIS-ArDrone-Recongnition-OpenCV-NodeJS
a0d5253b3f6db50c2dd95a6544cd0e962848b3f6
98bded8e64b8254be9ce4859ab5f95093b3b3957
refs/heads/master
2020-04-09T01:22:23.959498
2015-02-09T15:19:18
2015-02-09T15:19:18
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,903
h
#ifndef FONCTION_H #define FONCTION_H #include "opencv\cv.h" #include "opencv\cxcore.h" #include "opencv\highgui.h" #include "opencv2\core\core.hpp" #include "iostream" #include <fstream> #include "Windows.h" using namespace std; using namespace cv; #define SEUIL 65 //fonction de creation d image FTMP IplImage CreationImageFTMP(IplImage *src,IplImage *templ)//src=image camera ,templ=image de reference (une des fleches) { //définition de la taille(largeur, hauteur) de l'image ftmp int iwidth = src->width - templ->width + 1; int iheight = src->height - templ->height + 1; //Creer un pointeur d'image ftmp de type IplImage et de taille iwidth et iheight IplImage *ftmp = cvCreateImage(cvSize(iwidth,iheight),IPL_DEPTH_32F,1); return *ftmp; } IplImage CreationImageFTMP_2(IplImage *src,IplImage *templ_2)//src=image camera ,templ=image de reference (une des fleches) { //définition de la taille(largeur, hauteur) de l'image ftmp int iwidth = src->width - templ_2->width + 1; int iheight = src->height - templ_2->height + 1; //Creer un pointeur d'image ftmp de type IplImage et de taille iwidth et iheight IplImage *ftmp_2 = cvCreateImage(cvSize(iwidth,iheight),IPL_DEPTH_32F,1); return *ftmp_2; } IplImage CreationImageFTMP_3(IplImage *src,IplImage *templ_3)//src=image camera ,templ=image de reference (une des fleches) { //définition de la taille(largeur, hauteur) de l'image ftmp int iwidth = src->width - templ_3->width + 1; int iheight = src->height - templ_3->height + 1; //Creer un pointeur d'image ftmp de type IplImage et de taille iwidth et iheight IplImage *ftmp_3 = cvCreateImage(cvSize(iwidth,iheight),IPL_DEPTH_32F,1); return *ftmp_3; } IplImage CreationImageFTMP_4(IplImage *src,IplImage *templ_4)//src=image camera ,templ=image de reference (une des fleches) { //définition de la taille(largeur, hauteur) de l'image ftmp int iwidth = src->width - templ_4->width + 1; int iheight = src->height - templ_4->height + 1; //Creer un pointeur d'image ftmp de type IplImage et de taille iwidth et iheight IplImage *ftmp_4 = cvCreateImage(cvSize(iwidth,iheight),IPL_DEPTH_32F,1); return *ftmp_4; } //Creation du cadre de détection CvPoint cadre_pt0(IplImage *src,IplImage *templ) { CvPoint cadre_pt1 = cvPoint( (src->width - templ->width) / 2 , (src->height - templ->height) / 2); return cadre_pt1; } CvPoint cadre_ptbis(IplImage *src,IplImage *templ,CvPoint cadre_pt1) { CvPoint cadre_pt2 = cvPoint(cadre_pt1.x + templ->width , cadre_pt1.y + templ->height); return cadre_pt2; } //fonction d'ouverture et création de fenetre void fonctionOuvertureFenetre(IplImage *src, IplImage *templ_2) { //ouverture et creation des fenetre cvNamedWindow( "out", CV_WINDOW_AUTOSIZE ); cvShowImage( "out", src ); /*cvNamedWindow( "template", CV_WINDOW_AUTOSIZE ); cvShowImage( "template", templ ); cvNamedWindow( "template_2", CV_WINDOW_AUTOSIZE ); cvShowImage( "template_2", templ_2 ); */ } //destruction de toutes les fenetres void DESTRUCTEUR(CvCapture *capture) { // DESTRUCTEUR cvDestroyAllWindows(); cvReleaseCapture(&capture); return ; } //Fonction altitude int altitude() { //Initialisation de la variable valeur int valeur = 0; //Lecture du fichier ALTITUDE.txt ifstream fichier("ALTITUDE.txt", ios::in); //Si le fichier existe if(fichier) { //Creation de la variable data qui contiendra la valeur //de l'altitude int data; //On rempli la variable data par le contenu du fichier fichier >> data; //Condition selon la valeur de l'altitude if(data<=500) valeur = 100; else if((500<data)&&(data<1100)) valeur = 50; else if((1100<data)&&(data<1600)) valeur = 25; else if((1600<data)&&(data<2200)) valeur = 13; else valeur = 6; } //On retourne la valeur pour qu'elle soit lu return valeur; } #endif
[ "yonath-g@hotmail.fr" ]
yonath-g@hotmail.fr
af7417e8cd2d644c4110178020800c920ca5409f
95199fe51adce35381ad34f174d2ac96e8bf757a
/CakeServer/main.cpp
d732563ad5a1e5247bb36e140bfb3cf1c1f59dfa
[]
no_license
lichgo/CakeServer
de2b1567487fb65effe53b23c8df78d1038a6c24
468b9889fdf918e02638c4ca707e661360751c6d
refs/heads/master
2021-03-13T00:04:14.088391
2014-07-17T15:11:21
2014-07-17T15:11:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
210
cpp
#include "cs_types.h" #include "server.h" using namespace cakeserver; int main(int argc, char* argv[]) { cout << "CakeServer start.\n"; Server::getInstance().run(); cout << "CakeServer stop.\n"; }
[ "lichgo88@gmail.com" ]
lichgo88@gmail.com
b94787697e4410e74e673fefa4a8b2ac249d56c4
1dbf007249acad6038d2aaa1751cbde7e7842c53
/frs/include/huaweicloud/frs/v2/model/DetectLiveFaceByUrlRequest.h
f1afa74b6d7833697e773c4a4c05e7c81b2ae442
[]
permissive
huaweicloud/huaweicloud-sdk-cpp-v3
24fc8d93c922598376bdb7d009e12378dff5dd20
71674f4afbb0cd5950f880ec516cfabcde71afe4
refs/heads/master
2023-08-04T19:37:47.187698
2023-08-03T08:25:43
2023-08-03T08:25:43
324,328,641
11
10
Apache-2.0
2021-06-24T07:25:26
2020-12-25T09:11:43
C++
UTF-8
C++
false
false
2,713
h
#ifndef HUAWEICLOUD_SDK_FRS_V2_MODEL_DetectLiveFaceByUrlRequest_H_ #define HUAWEICLOUD_SDK_FRS_V2_MODEL_DetectLiveFaceByUrlRequest_H_ #include <huaweicloud/frs/v2/FrsExport.h> #include <huaweicloud/core/utils/ModelBase.h> #include <huaweicloud/core/http/HttpResponse.h> #include <huaweicloud/frs/v2/model/LiveDetectFaceUrlReq.h> #include <string> namespace HuaweiCloud { namespace Sdk { namespace Frs { namespace V2 { namespace Model { using namespace HuaweiCloud::Sdk::Core::Utils; using namespace HuaweiCloud::Sdk::Core::Http; /// <summary> /// Request Object /// </summary> class HUAWEICLOUD_FRS_V2_EXPORT DetectLiveFaceByUrlRequest : public ModelBase { public: DetectLiveFaceByUrlRequest(); virtual ~DetectLiveFaceByUrlRequest(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; bool fromJson(const web::json::value& json) override; ///////////////////////////////////////////// /// DetectLiveFaceByUrlRequest members /// <summary> /// 企业项目ID。FRS支持通过企业项目管理(EPS)对不同用户组和用户的资源使用,进行分账。当前仅支持按需计费模式。 获取方法:进入“[企业项目管理](https://console.huaweicloud.com/eps/?region&#x3D;cn-north-4#/projects/list)”页面,单击企业项目名称,在企业项目详情页获取Enterprise-Project-Id(企业项目ID)。 企业项目创建步骤请参见用户指南。 &gt; 说明: 创建企业项目后,在传参时,有以下三类场景。 - 携带正确的ID,正常使用FRS服务,账单归到企业ID对应的企业项目中。 - 携带错误的ID,正常使用FRS服务,账单的企业项目会被分类为“未归集”。 - 不携带ID,正常使用FRS服务,账单的企业项目会被分类为“未归集”。 /// </summary> std::string getEnterpriseProjectId() const; bool enterpriseProjectIdIsSet() const; void unsetenterpriseProjectId(); void setEnterpriseProjectId(const std::string& value); /// <summary> /// /// </summary> LiveDetectFaceUrlReq getBody() const; bool bodyIsSet() const; void unsetbody(); void setBody(const LiveDetectFaceUrlReq& value); protected: std::string enterpriseProjectId_; bool enterpriseProjectIdIsSet_; LiveDetectFaceUrlReq body_; bool bodyIsSet_; #ifdef RTTR_FLAG RTTR_ENABLE() public: DetectLiveFaceByUrlRequest& dereference_from_shared_ptr(std::shared_ptr<DetectLiveFaceByUrlRequest> ptr) { return *ptr; } #endif }; } } } } } #endif // HUAWEICLOUD_SDK_FRS_V2_MODEL_DetectLiveFaceByUrlRequest_H_
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
f59b728284dd938bbb409ba18be8e249729bd363
c8029ea41c7dcdde4330bcd6d7ef4f9fe248b75d
/src/kbase/registry.cpp
5fa1b4cb56e74fc9f54e56fefd95359f20257d12
[ "MIT" ]
permissive
ExpLife0011/KBase
e956181c735fd469ba616c8c6547daa394181398
c012339344b35394f6eba23a32d408c80beb8e8f
refs/heads/master
2020-03-20T03:49:02.847354
2018-02-16T07:44:08
2018-02-16T07:44:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,409
cpp
/* @ 0xCCCCCCCC */ #include "kbase/registry.h" #include <Shlwapi.h> #include "kbase/error_exception_util.h" #include "kbase/logging.h" #include "kbase/scope_guard.h" #include "kbase/string_encoding_conversions.h" #include "kbase/string_util.h" namespace kbase { RegKey::RegKey() noexcept : key_(nullptr) {} RegKey::RegKey(HKEY rootkey, const wchar_t* subkey, REGSAM access, DWORD& disposition) : key_(nullptr) { auto rv = RegCreateKeyExW(rootkey, subkey, 0, nullptr, REG_OPTION_NON_VOLATILE, access, nullptr, &key_, &disposition); LOG_IF(WARNING, rv != ERROR_SUCCESS) << "Failed to create instance for key " << kbase::WideToUTF8(subkey) << "; Error: " << rv; if (rv == ERROR_SUCCESS) { subkey_name_ = subkey; } } RegKey::RegKey(RegKey&& other) noexcept : key_(other.Release()), subkey_name_(std::move(other.subkey_name_)) {} RegKey& RegKey::operator=(RegKey&& other) noexcept { Close(); key_ = other.Release(); subkey_name_ = std::move(other.subkey_name_); return *this; } RegKey::~RegKey() { Close(); } // static RegKey RegKey::Create(HKEY rootkey, const wchar_t* subkey, REGSAM access) { DWORD ignored; return Create(rootkey, subkey, access, ignored); } // static RegKey RegKey::Create(HKEY rootkey, const wchar_t* subkey, REGSAM access, DWORD& disposition) { ENSURE(CHECK, subkey != nullptr).Require(); return RegKey(rootkey, subkey, access, disposition); } void RegKey::Open(const wchar_t* subkey, REGSAM access) { Open(key_, subkey, access); } void RegKey::Open(HKEY rootkey, const wchar_t* subkey, REGSAM access) { ENSURE(CHECK, rootkey != nullptr && subkey != nullptr).Require(); HKEY new_key = nullptr; auto rv = RegOpenKeyExW(rootkey, subkey, 0, access, &new_key); LOG_IF(WARNING, rv != ERROR_SUCCESS) << "Failed to create instance for key " << kbase::WideToUTF8(subkey) << "; Error: " << rv; Close(); key_ = new_key; if (rv == ERROR_SUCCESS) { subkey_name_ = subkey; } } HKEY RegKey::Get() const noexcept { return key_; } HKEY RegKey::Release() noexcept { HKEY key = key_; key_ = nullptr; return key; } void RegKey::Close() noexcept { if (key_) { RegCloseKey(key_); key_ = nullptr; } subkey_name_.clear(); } // static bool RegKey::KeyExists(HKEY rootkey, const wchar_t* subkey, WOW6432Node node_mode) { REGSAM access = KEY_READ; if (node_mode == Force32KeyOnWOW64) { access |= KEY_WOW64_32KEY; } else if (node_mode == Force64KeyOnWOW64) { access |= KEY_WOW64_64KEY; } HKEY key = nullptr; auto rv = RegOpenKeyExW(rootkey, subkey, 0, access, &key); if (rv == ERROR_SUCCESS) { RegCloseKey(key); return true; } ENSURE(THROW, rv == ERROR_FILE_NOT_FOUND)(rv).Require(); return false; } bool RegKey::HasValue(const wchar_t* value_name) const { ENSURE(THROW, IsValid()).Require(); auto rv = RegQueryValueExW(key_, value_name, nullptr, nullptr, nullptr, nullptr); if (rv == ERROR_SUCCESS) { return true; } ENSURE(THROW, rv == ERROR_FILE_NOT_FOUND)(rv).Require(); return false; } size_t RegKey::GetValueCount() const { ENSURE(THROW, IsValid()).Require(); DWORD value_count = 0; auto rv = RegQueryInfoKeyW(key_, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &value_count, nullptr, nullptr, nullptr, nullptr); ENSURE(THROW, rv == ERROR_SUCCESS)(rv).Require(); return static_cast<size_t>(value_count); } void RegKey::GetValueNameAt(size_t index, std::wstring& value_name) const { ENSURE(THROW, IsValid()).Require(); wchar_t buf[MAX_PATH + 1]; DWORD buf_size = _countof(buf); auto rv = RegEnumValueW(key_, static_cast<DWORD>(index), buf, &buf_size, nullptr, nullptr, nullptr, nullptr); ENSURE(THROW, rv == ERROR_SUCCESS)(rv).Require(); value_name = buf; } void RegKey::DeleteKey(const wchar_t* key_name) const { ENSURE(THROW, IsValid()).Require(); auto rv = RegDeleteTreeW(key_, key_name); ENSURE(THROW, rv == ERROR_SUCCESS)(rv).Require(); } void RegKey::DeleteValue(const wchar_t* value_name) const { ENSURE(THROW, IsValid()).Require(); auto rv = RegDeleteValueW(key_, value_name); ENSURE(THROW, rv == ERROR_SUCCESS)(rv).Require(); } void RegKey::ReadRawValue(const wchar_t* value_name, void* data, DWORD& data_size, DWORD& data_type) const { ENSURE(THROW, IsValid()).Require(); auto rv = RegGetValueW(key_, nullptr, value_name, 0, &data_type, data, &data_size); ENSURE(THROW, rv == ERROR_SUCCESS)(rv).Require(); } void RegKey::ReadRawValue(const wchar_t* value_name, DWORD restricted_type, void* data, DWORD& data_size) const { ENSURE(THROW, IsValid()).Require(); auto rv = RegGetValueW(key_, nullptr, value_name, restricted_type, nullptr, data, &data_size); ENSURE(THROW, rv == ERROR_SUCCESS)(rv).Require(); } void RegKey::ReadValue(const wchar_t* value_name, std::wstring& value) const { ENSURE(THROW, IsValid()).Require(); constexpr DWORD kCharSize = sizeof(wchar_t); // Length including null. DWORD str_length = 1024; // It seems that automatic expansion for environment strings in RegGetValue // behaves incorrect when using std::basic_string as its buffer. // Therefore, does expansions on our own. DWORD restricted_type = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ | RRF_NOEXPAND; DWORD data_type = 0; DWORD data_size = 0; std::wstring raw_data; long rv = 0; do { wchar_t* data_ptr = WriteInto(raw_data, str_length); data_size = str_length * kCharSize; rv = RegGetValueW(key_, nullptr, value_name, restricted_type, &data_type, data_ptr, &data_size); if (rv == ERROR_SUCCESS) { if (data_type == REG_SZ) { size_t written_length = data_size / kCharSize - 1; value.assign(data_ptr, written_length); return; } if (data_type == REG_EXPAND_SZ) { std::wstring expanded; wchar_t* ptr = WriteInto(expanded, str_length); DWORD size = ExpandEnvironmentStringsW(data_ptr, ptr, str_length); ENSURE(THROW, size > 0)(LastError()).Require(); if (size > str_length) { data_size = size * kCharSize; rv = ERROR_MORE_DATA; } else { value.assign(ptr, size - 1); return; } } } } while (rv == ERROR_MORE_DATA && (str_length = data_size / kCharSize, true)); ENSURE(THROW, NotReached())(rv).Require(); } void RegKey::ReadValue(const wchar_t* value_name, std::vector<std::wstring>& values) const { ENSURE(THROW, IsValid()).Require(); constexpr size_t kCharSize = sizeof(wchar_t); DWORD restricted_type = RRF_RT_REG_MULTI_SZ; DWORD data_size = 0; // Acquires the data size, in bytes. ReadRawValue(value_name, restricted_type, nullptr, data_size); std::wstring raw_data; wchar_t* data_ptr = WriteInto(raw_data, data_size / kCharSize); ReadRawValue(value_name, restricted_type, data_ptr, data_size); SplitString(raw_data, std::wstring(1, L'\0'), values); } void RegKey::ReadValue(const wchar_t* value_name, DWORD& value) const { DWORD restricted_type = RRF_RT_DWORD; DWORD tmp = 0; DWORD data_size = sizeof(DWORD); ReadRawValue(value_name, restricted_type, &tmp, data_size); ENSURE(CHECK, data_size == sizeof(DWORD))(data_size).Require(); value = tmp; } void RegKey::ReadValue(const wchar_t* value_name, DWORD64& value) const { DWORD restricted_type = RRF_RT_QWORD; DWORD64 tmp = 0; DWORD data_size = sizeof(DWORD64); ReadRawValue(value_name, restricted_type, &tmp, data_size); ENSURE(CHECK, data_size == sizeof(DWORD64))(data_size).Require(); value = tmp; } void RegKey::WriteValue(const wchar_t* value_name, DWORD value) const { WriteValue(value_name, &value, sizeof(DWORD), REG_DWORD); } void RegKey::WriteValue(const wchar_t* value_name, DWORD64 value) const { WriteValue(value_name, &value, sizeof(DWORD64), REG_QWORD); } void RegKey::WriteValue(const wchar_t* value_name, const wchar_t* value, size_t length) const { // Data size includes terminating-null character. WriteValue(value_name, value, sizeof(wchar_t) * (length + 1), REG_SZ); } void RegKey::WriteValue(const wchar_t* value_name, const void* data, size_t data_size, DWORD data_type) const { ENSURE(CHECK, data && data_size > 0).Require(); auto rv = RegSetValueExW(key_, value_name, 0, data_type, static_cast<const BYTE*>(data), static_cast<DWORD>(data_size)); ENSURE(THROW, rv == ERROR_SUCCESS)(rv).Require(); } // -*- RegKeyIterator::Impl implementations -*- class RegKeyIterator::Impl { public: // Will take the ownership of `key`. Impl(HKEY key, int subkey_count); ~Impl(); DISALLOW_COPY(Impl); DISALLOW_MOVE(Impl); // Returns true, if successfully advanced to the next key. // Returns false, if there is no more key to iterate. bool Next(); const value_type& subkey() const noexcept { return subkey_; } private: HKEY key_; int next_index_; int subkey_count_; value_type subkey_; }; RegKeyIterator::Impl::Impl(HKEY key, int subkey_count) : key_(key), next_index_(0), subkey_count_(subkey_count) { ENSURE(CHECK, key != nullptr && subkey_count > 0)(key)(subkey_count).Require(); Next(); } RegKeyIterator::Impl::~Impl() { if (key_) { RegCloseKey(key_); } } bool RegKeyIterator::Impl::Next() { if (next_index_ >= subkey_count_) { return false; } wchar_t name_buf[MAX_PATH + 1]; DWORD name_buf_size = _countof(name_buf); auto rv = RegEnumKeyExW(key_, next_index_, name_buf, &name_buf_size, nullptr, nullptr, nullptr, nullptr); ENSURE(THROW, rv == ERROR_SUCCESS)(rv).Require(); // Be careful, opening some registry keys may fail due to lack of administrator privilege. subkey_.Open(key_, name_buf, KEY_READ | KEY_SET_VALUE); ++next_index_; return true; } // -*- RegKeyIterator implementations -*- RegKeyIterator::RegKeyIterator(HKEY rootkey, const wchar_t* subkey) { HKEY key = nullptr; auto rv = RegOpenKeyExW(rootkey, subkey, 0, KEY_READ, &key); if (rv != ERROR_SUCCESS) { LOG(WARNING) << "Failed to construct RegKeyIterator on " << subkey << "; Error: " << rv; return; } auto guard = MAKE_SCOPE_GUARD { RegCloseKey(key); }; DWORD subkey_count = 0; rv = RegQueryInfoKeyW(key, nullptr, nullptr, nullptr, &subkey_count, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); if (rv != ERROR_SUCCESS) { LOG(WARNING) << "Failed to query count of subkey for " << subkey << "; Error: " << rv; return; } if (subkey_count > 0) { impl_ = std::make_shared<Impl>(key, static_cast<int>(subkey_count)); guard.Dismiss(); } } RegKeyIterator::RegKeyIterator(const RegKey& regkey) { if (!regkey) { return; } HKEY key = SHRegDuplicateHKey(regkey.Get()); auto guard = MAKE_SCOPE_GUARD { RegCloseKey(key); }; DWORD subkey_count = 0; auto result = RegQueryInfoKeyW(key, nullptr, nullptr, nullptr, &subkey_count, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); if (result != ERROR_SUCCESS) { LOG(WARNING) << "Failed to query count of subkey; Error: " << result; return; } if (subkey_count > 0) { impl_ = std::make_shared<Impl>(key, static_cast<int>(subkey_count)); guard.Dismiss(); } } RegKeyIterator& RegKeyIterator::operator++() { if (!impl_->Next()) { impl_ = nullptr; } return *this; } RegKeyIterator::reference RegKeyIterator::operator*() const noexcept { return impl_->subkey(); } RegKeyIterator::pointer RegKeyIterator::operator->() const noexcept { return &impl_->subkey(); } } // namespace kbase
[ "kingsamchen@gmail.com" ]
kingsamchen@gmail.com
a0f51714ea813ff22fb0fd8c9921ccdff0870e10
06945dd959ddf9d4865bb96c088ce0a630edf38e
/media.cpp
cfad71db40f3d81b2024c05c29980dafe8f24be9
[]
no_license
GabrielSchenato/algoritmos
0acc240f1d66237b5b096b3c4f3fd661e0cef47e
750531e459239faaeee8298616370458939d94b9
refs/heads/master
2020-12-06T11:02:26.597398
2020-01-08T00:57:21
2020-01-08T00:57:21
232,447,205
0
0
null
null
null
null
UTF-8
C++
false
false
481
cpp
#include <iostream> using namespace std; main () { float valor1,valor2,valor3,media; cout<<"Ola, Seja bem vindo"; while (1){ cout<<"\n\n\nPor favor, digite o primeiro valor: "; cin>>valor1; cout<<"\n\nPor favor, digite o segundo valor: "; cin>>valor2; cout<<"\n\nPor favor, digite o terceiro valor: "; cin>>valor3; media=(valor1+valor2+valor3)/3; cout<<"\n\nOperacao realizada com sucesso!" "\n\nO valor da media eh: "; cout<<media; } return 0; }
[ "gabrielschenato152@hotmail.com" ]
gabrielschenato152@hotmail.com
188aae153506f5ca866b8f9004840c918cb67217
6289647a5adef83a0c5a9a445aa435e4469d1a58
/CarDetection/src/GUI/GUIUtils.cpp
25c2f45b582daffb40d1aeeb326881a216ca0f65
[ "MIT" ]
permissive
wycjl/Car-Detection
705f78c3ce6906b076f7d2ed3b5c5f688e903674
2c2c8e2172fb606f7e2b974a7e9f46de0e4199a2
refs/heads/master
2020-04-16T23:30:30.388180
2017-12-19T19:15:58
2017-12-19T19:15:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,793
cpp
#include "GUIUtils.h" // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <GUIUtils> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< void GUIUtils::drawImageLabel(string text, Mat& image, const Rect& signBoundingRect) { int textBoxHeight = (int)(signBoundingRect.height * 0.15); int fontface = cv::FONT_HERSHEY_SIMPLEX; double scale = (double)textBoxHeight / 46.0; int thickness = (std::max)(1, (int)(textBoxHeight * 0.05)); int baseline = 0; Rect textBoundingRect = signBoundingRect; textBoundingRect.height = (std::max)(textBoxHeight, TEXT_MIN_SIZE); //textBoundingRect.y -= textBoundingRect.height; cv::Size textSize = cv::getTextSize(text, fontface, scale, thickness, &baseline); cv::Point textBottomLeftPoint(textBoundingRect.x + (textBoundingRect.width - textSize.width) / 2, textBoundingRect.y + (textBoundingRect.height + textSize.height) / 2); cv::rectangle(image, signBoundingRect, COLOR_LABEL_BOX_HSV, 2); cv::rectangle(image, textBoundingRect, COLOR_LABEL_BOX_HSV, 2); cv::putText(image, text, textBottomLeftPoint, fontface, scale, COLOR_LABEL_TEXT_HSV, thickness); } pair< pair<int, int>, pair<int, int> > GUIUtils::addHighGUIWindow(int column, int row, string windowName, int imageWidth, int imageHeight, int screenWidth, int screenHeight, int xOffset, int yOffset, int numberColumns, int numberRows) { if (numberColumns < 1 || numberRows < 1) return pair< pair<int, int>, pair<int, int> >(pair<int, int>(0, 0), pair<int, int>(0, 0)); int imageWidthFinal = imageWidth; if (imageWidthFinal < 10) imageWidthFinal = (screenWidth - WINDOW_OPTIONS_WIDTH) / 2; int imageHeightFinal = imageHeight; if (imageHeightFinal < 10) imageHeightFinal = (screenHeight - WINDOW_DIGITS_HEIGHT) / 2; int windowHeightFinal = ((screenHeight - WINDOW_DIGITS_HEIGHT) / numberRows); int windowWidthFinal = (imageWidthFinal * windowHeightFinal / imageHeightFinal); if ((windowWidthFinal * numberColumns + WINDOW_OPTIONS_WIDTH) > screenWidth) { windowWidthFinal = ((screenWidth - WINDOW_OPTIONS_WIDTH) / numberColumns); windowHeightFinal = imageHeightFinal * windowWidthFinal / imageWidthFinal; } namedWindow(windowName, CV_WINDOW_NORMAL | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED); resizeWindow(windowName, windowWidthFinal - 2 * WINDOW_FRAME_THICKNESS, windowHeightFinal - WINDOW_FRAME_THICKNESS - WINDOW_HEADER_HEIGHT); int x = 0; if (column != 0) { x = windowWidthFinal * column; } int y = 0; if (row != 0) { y = windowHeightFinal * row; } x += xOffset; y += yOffset; moveWindow(windowName, x, y); return pair< pair<int, int>, pair<int, int> >(pair<int, int>(x, y), pair<int, int>(windowWidthFinal, windowHeightFinal)); } pair< pair<int, int>, pair<int, int> > GUIUtils::addHighGUITrackBarWindow(string windowName, int numberTrackBars, int cumulativeTrackBarPosition, int trackBarWindowNumber, int screenWidth, int xOffset, int yOffset) { namedWindow(windowName, CV_WINDOW_NORMAL | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED); int width = WINDOW_OPTIONS_WIDTH - WINDOW_FRAME_THICKNESS * 2; int height = numberTrackBars * WINDOW_OPTIONS_TRACKBAR_HEIGHT; resizeWindow(windowName, width, height); int x = (screenWidth - WINDOW_OPTIONS_WIDTH) + xOffset; int y = ((WINDOW_HEADER_HEIGHT + WINDOW_FRAME_THICKNESS) * trackBarWindowNumber + WINDOW_OPTIONS_TRACKBAR_HEIGHT * cumulativeTrackBarPosition) + yOffset; moveWindow(windowName, x, y); return pair< pair<int, int>, pair<int, int> >(pair<int, int>(x, y), pair<int, int>(width, height)); } // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </GUIUtils> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
[ "carloscosta.cmcc@gmail.com" ]
carloscosta.cmcc@gmail.com