text
stringlengths
8
6.88M
#include <vector> class VT100Client; class VT100 { public: VT100(VT100Client*); void parseBuffer(const char* start, const char* end); private: VT100Client* m_client; int cs; int unsignedValue; std::vector<int> numberStack; };
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_ORDERBOOKDB_H_INCLUDED #define RIPPLE_ORDERBOOKDB_H_INCLUDED /* TODO ---- - Add typedefs (in src/ripple/types) for usage of the following primitives: * uint64 * uint160 * uint256 Each typedef should make it clear what the semantics of the value are, and have a javadoc comment. Examples: RippleCurrencyHash RippleIssuerHash - Add a new struct OrderBookKey with these fields: * issuerPays * issuerGets * currencyPays * currencyGets Use this struct as the key to map order books to the book listeners, instead of passing the four parameters around everywhere. Change all function signatures and container types to use this key instead of the four parameters. - Add typedefs for all containers, choose a descriptive name that follows the coding style, add a Javadoc comment explaining what it holds. - Rename currencyIssuer_ct to follow the coding style. e.g. CurrencyPair - Replace C11X with a suitable Beast macro - Move BookListeners to its own header file - Add documentation explaining what each class does */ // VFALCO TODO Rename this type and give the key and value typedefs. typedef std::pair<uint160, uint160> currencyIssuer_t; // VFALCO TODO Replace C11X with a suitable Beast macro #ifdef C11X typedef std::pair<const uint160&, const uint160&> currencyIssuer_ct; #else typedef std::pair<uint160, uint160> currencyIssuer_ct; // C++ defect 106 #endif //------------------------------------------------------------------------------ // VFALCO TODO Add Javadoc comment explaining what this class does class BookListeners { public: typedef boost::shared_ptr<BookListeners> pointer; BookListeners (); void addSubscriber (InfoSub::ref sub); void removeSubscriber (uint64 sub); void publish (Json::Value& jvObj); private: typedef RippleRecursiveMutex LockType; typedef LockType::ScopedLockType ScopedLockType; LockType mLock; // VFALCO TODO Use a typedef for the uint64 // Use a typedef for the container boost::unordered_map<uint64, InfoSub::wptr> mListeners; }; //------------------------------------------------------------------------------ // VFALCO TODO Add Javadoc comment explaining what this class does class OrderBookDB : public Stoppable , public LeakChecked <OrderBookDB> { public: explicit OrderBookDB (Stoppable& parent); void setup (Ledger::ref ledger); void update (Ledger::pointer ledger); void invalidate (); void addOrderBook(const uint160& takerPaysCurrency, const uint160& takerGetsCurrency, const uint160& takerPaysIssuer, const uint160& takerGetsIssuer); // return list of all orderbooks that want this issuerID and currencyID void getBooksByTakerPays (const uint160& issuerID, const uint160& currencyID, std::vector<OrderBook::pointer>& bookRet); void getBooksByTakerGets (const uint160& issuerID, const uint160& currencyID, std::vector<OrderBook::pointer>& bookRet); bool isBookToXRP (const uint160& issuerID, const uint160& currencyID); BookListeners::pointer getBookListeners (const uint160& currencyPays, const uint160& currencyGets, const uint160& issuerPays, const uint160& issuerGets); BookListeners::pointer makeBookListeners (const uint160& currencyPays, const uint160& currencyGets, const uint160& issuerPays, const uint160& issuerGets); // see if this txn effects any orderbook void processTxn (Ledger::ref ledger, const AcceptedLedgerTx& alTx, Json::Value& jvObj); private: boost::unordered_map< currencyIssuer_t, std::vector<OrderBook::pointer> > mSourceMap; // by ci/ii boost::unordered_map< currencyIssuer_t, std::vector<OrderBook::pointer> > mDestMap; // by co/io boost::unordered_set< currencyIssuer_t > mXRPBooks; // does an order book to XRP exist typedef RippleRecursiveMutex LockType; typedef LockType::ScopedLockType ScopedLockType; LockType mLock; // VFALCO TODO Replace with just one map / unordered_map with a struct for the key // issuerPays, issuerGets, currencyPays, currencyGets std::map<uint160, std::map<uint160, std::map<uint160, std::map<uint160, BookListeners::pointer> > > > mListeners; uint32 mSeq; }; #endif // vim:ts=4
#include "path_utils.hxx" #include <algorithm> using namespace std::placeholders; PathNode::PathNode(Vec2 coordinates_, PathNode* parent_) { parent = parent_; coordinates = coordinates_; G = H = 0; } uint PathNode::getScore() { return G + H; } Generator::Generator() { setDiagonalMovement(false); setHeuristic(&Heuristic::manhattan); direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {-1, -1}, {1, 1}, {-1, 1}, {1, -1}}; } void Generator::setWorldSize(Vec2 worldSize_) { worldSize = worldSize_; } void Generator::setDiagonalMovement(bool enable_) { directions = (enable_ ? 8 : 4); } void Generator::setHeuristic(HeuristicFunction heuristic_) { heuristic = std::bind(heuristic_, _1, _2); } void Generator::addCollision(Vec2 coordinates_) { walls.push_back(coordinates_); } void Generator::addCollisionList(std::vector<Point> coordinates_) { walls.swap(coordinates_); } void Generator::addCollisionList(TmxObject& tmx_object, const string& layer) { addCollisionList(tmx_object.collistions_map_.at(layer)); } void Generator::removeCollision(Vec2 coordinates_) { auto it = std::find(walls.begin(), walls.end(), coordinates_); if (it != walls.end()) { walls.erase(it); } } void Generator::clearCollisions() { walls.clear(); } void Generator::findPath(Vec2 source_, Vec2 target_, deque<Point>& queue, int limit) { PathNode* current = nullptr; NodeSet openSet, closedSet; openSet.insert(new PathNode(source_)); while (!openSet.empty()) { current = *openSet.begin(); for (auto node : openSet) { if (node->getScore() <= current->getScore()) { current = node; } } if (current->coordinates == target_) break; closedSet.insert(current); openSet.erase(std::find(openSet.begin(), openSet.end(), current)); for (uint i = 0; i < directions; ++i) { Vec2 newCoordinates(current->coordinates + direction[i]); if (detectCollision(newCoordinates) || findNodeOnList(closedSet, newCoordinates)) { continue; } uint totalCost = current->G + ((i < 4) ? 10 : 14); PathNode* successor = findNodeOnList(openSet, newCoordinates); if (successor == nullptr) { successor = new PathNode(newCoordinates, current); successor->G = totalCost; successor->H = heuristic(successor->coordinates, target_); openSet.insert(successor); } else if (totalCost < successor->G) { successor->parent = current; successor->G = totalCost; } } } while (current != nullptr) { queue.emplace_front(current->coordinates); current = current->parent; } while (queue.size() > limit) { queue.pop_back(); } releaseNodes(openSet); releaseNodes(closedSet); } PathNode* Generator::findNodeOnList(NodeSet& nodes_, Vec2 coordinates_) { for (auto node : nodes_) { if (node->coordinates == coordinates_) { return node; } } return nullptr; } void Generator::releaseNodes(NodeSet& nodes_) { for (auto it = nodes_.begin(); it != nodes_.end();) { delete *it; it = nodes_.erase(it); } } bool Generator::detectCollision(Vec2 coordinates_) { return coordinates_.x < 0 || coordinates_.x >= worldSize.x || coordinates_.y < 0 || coordinates_.y >= worldSize.y || std::find(walls.begin(), walls.end(), coordinates_) != walls.end(); } Vec2 Heuristic::getDelta(Vec2 source_, Vec2 target_) { return {abs(source_.x - target_.x), abs(source_.y - target_.y)}; } uint Heuristic::manhattan(Vec2 source_, Vec2 target_) { auto delta = std::move(getDelta(source_, target_)); return static_cast<uint>((delta.x + delta.y)); } uint Heuristic::euclidean(Vec2 source_, Vec2 target_) { auto delta = std::move(getDelta(source_, target_)); return static_cast<uint>(10 * sqrt(pow(delta.x, 2) + pow(delta.y, 2))); } uint Heuristic::octagonal(Vec2 source_, Vec2 target_) { auto delta = std::move(getDelta(source_, target_)); return 10 * (delta.x + delta.y) + (-6) * std::min(delta.x, delta.y); }
/* * This file is left empty on purpose * It provides CMake the knowledge of * What langue it is compiling */
#include <iostream> #include "hypertext.hpp" // print top of html page void printPageTop(const std::string& header) { std::cout << "<!DOCTYPE HTML>\n"; std::cout << "<html>\n"; std::cout << "<head>\n"; std::cout << "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n"; std::cout << "<link rel='stylesheet' media='all' href='/includes/gradienttable.css'>\n"; std::cout << "<title>" << header << "</title>\n"; std::cout << "</head>\n"; std::cout << "<body>\n"; std::cout << "<header><p>" << header << "</p></header>\n"; std::cout << "<p></p>\n"; std::cout << "<div><a href=\"/index.php\">Home</a></div>\n"; std::cout << "<p></p>\n"; } // print form radio button void printButton(const std::string& name, const std::string& value, const std::string& msg, bool checked) { std::cout << "<div><label><input type='radio' name='" << name << "' value='" << value; if (checked) std::cout << "' checked>"; else std::cout << "'>"; std::cout << value; std::cout << "</label></div>\n"; } // print bottom of html page void printPageBottom() { std::cout << "<p></p>\n"; std::cout << "<div><a href=\"/index.php\">Home</a></div>\n"; std::cout << "<footer><p>Copyright (c) 2017 Josh Roybal.</p></footer>\n"; std::cout << "<p></p>\n"; std::cout << "</body>\n"; std::cout << "</html>\n"; }
#include "gtest/gtest.h" #include "wali/wfa/WFA.hpp" #include "wali/LongestSaturatingPathSemiring.hpp" #include "wali/domains/binrel/ProgramBddContext.hpp" #include "wali/domains/binrel/BinRel.hpp" #include "fixtures.hpp" #include "fixtures/SimpleWeights.hpp" namespace sh_distance = testing::ShortestPathWeights; namespace wali { namespace wfa { std::string clamp(std::string const & str) { const size_t maxlen = 50; if (str.size() < maxlen) { return str; } else { return str.substr(0, maxlen-3) + "..."; } } ::testing::AssertionResult assert_accessibleStateMaps_equal(char const * left_expr, char const * right_expr, WFA::AccessibleStateMap const & left, WFA::AccessibleStateMap const & right) { if (left.size() != right.size()) { return ::testing::AssertionFailure() << "Epsilon closure results are different sizes:\n" << " " << left_expr << " has " << left.size() << " states\n" << " " << right_expr << " has " << right.size() << " states"; } for (WFA::AccessibleStateMap::const_iterator left_entry = left.begin(), right_entry = right.begin(); left_entry != left.end(); ++left_entry, ++right_entry) { if (left_entry->first != right_entry->first) { assert(right.find(left_entry->first) == right.end()); return ::testing::AssertionFailure() << "Epsilon closure results have a different set of states;\n" << " " << left_expr << " contains state " << key2str(left_entry->first) << " (" << left_entry->first << ")\n" << " while " << right_expr << " does not"; } if (!left_entry->second->equal(right_entry->second)) { std::string left_weight_str = clamp(left_entry->second->to_string()), right_weight_str = clamp(right_entry->second->to_string()); return ::testing::AssertionFailure() << "Epsilon closure results have a different weight for a state;\n" << " the state is " << key2str(left_entry->first) << " (" << left_entry->first << ")\n" << " which for " << left_expr << " has weight " << left_weight_str << "\n" << " and for " << right_expr << " has weight " << right_weight_str; } } return ::testing::AssertionSuccess(); } WFA::AccessibleStateMap checkedEpsilonClose(WFA const & wfa, Key state) { WFA::AccessibleStateMap default_close = wfa.epsilonClose(state), mohri_close = wfa.epsilonClose_Mohri(state), fwpds_close = wfa.epsilonClose_Fwpds(state); EXPECT_PRED_FORMAT2(assert_accessibleStateMaps_equal, default_close, mohri_close); EXPECT_PRED_FORMAT2(assert_accessibleStateMaps_equal, default_close, fwpds_close); return default_close; } ::testing::AssertionResult assert_epsilonCloseCache_equal(char const * left_expr, char const * right_expr, WFA::EpsilonCloseCache const & left, WFA::EpsilonCloseCache const & right) { if (left.size() != right.size()) { return ::testing::AssertionFailure() << "The two expressions below have epsilon closure information for a differing number of states\n" << " " << left_expr << " reports e-closures for " << left.size() << " states\n" << " " << right_expr << " reports e-closures for " << right.size() << " states"; } for (WFA::EpsilonCloseCache::const_iterator left_entry = left.begin(), right_entry = right.begin(); left_entry != left.end(); ++left_entry, ++right_entry) { if (left_entry->first != right_entry->first) { if (right.find(left_entry->first) == right.end()) { return ::testing::AssertionFailure() << "The two expressions below report epsilon closure information for a differing set of states\n" << " " << left_expr << " reports an e-close for state " << key2str(left_entry->first) << " (" << left_entry->first << ")\n" << " while " << right_expr << " does not"; } else { assert(left.find(right_entry->first) == left.end()); return ::testing::AssertionFailure() << "The two expressions below report epsilon closure information for a differing set of states\n" << " " << left_expr << " does NOT report an e-close for state " << key2str(left_entry->first) << " (" << left_entry->first << ")\n" << " while " << right_expr << " DOES"; } } std::stringstream left_ss, right_ss; left_ss << left_expr << " [from " << key2str(left_entry->first) << " (" << left_entry->first << ")]"; right_ss << right_expr << " [from " << key2str(right_entry->first) << " (" << right_entry->first << ")]"; std::string full_left_expr = left_ss.str(), full_right_expr = right_ss.str(); ::testing::AssertionResult result_closures = assert_accessibleStateMaps_equal(full_left_expr.c_str(), full_right_expr.c_str(), left_entry->second, right_entry->second); if (!result_closures) { return ::testing::AssertionFailure() << "The epsilon closures differ for a state:\n" << result_closures.message(); } } return ::testing::AssertionSuccess(); } ::testing::AssertionResult check_all_source_epsilon_closure(char const * UNUSED_PARAMETER(expr), WFA const & wfa) { WFA::EpsilonCloseCache mohri_closures, fwpds_singles_closures, fwpds_multi_closures; wfa.epsilonCloseCached_MohriAll(wfa.getInitialState(), mohri_closures); wfa.epsilonCloseCached_FwpdsAllSingles(wfa.getInitialState(), fwpds_singles_closures); wfa.epsilonCloseCached_FwpdsAllMulti(wfa.getInitialState(), fwpds_multi_closures); ::testing::AssertionResult eq12 = assert_epsilonCloseCache_equal("mohri_closures", "fwpds_singles_closures", mohri_closures, fwpds_singles_closures), eq13 = assert_epsilonCloseCache_equal("mohri_closures", "fwpds_multi_closures", mohri_closures, fwpds_multi_closures); if (!eq12) { return eq12; } else { return eq13; } } #define EXPECT_CONSISTENT_EPSILON_CLOSURES(wfa) \ EXPECT_PRED_FORMAT1(check_all_source_epsilon_closure, wfa) #define EXPECT_CONTAINS(container, value) EXPECT_FALSE(container.end() == container.find(value)) TEST(wali$wfa$$epsilonClose, EpsilonTransitionToMiddleToEpsilonToAccepting) { EpsilonTransitionToMiddleToEpsilonToAccepting fixture; Key start = getKey("start"); Key middle = getKey("middle"); Key almost = getKey("almost"); Key accept = getKey("accept"); WFA::AccessibleStateMap start_closure = checkedEpsilonClose(fixture.wfa, start); WFA::AccessibleStateMap middle_closure = checkedEpsilonClose(fixture.wfa, middle); WFA::AccessibleStateMap almost_closure = checkedEpsilonClose(fixture.wfa, almost); WFA::AccessibleStateMap accept_closure = checkedEpsilonClose(fixture.wfa, accept); EXPECT_CONSISTENT_EPSILON_CLOSURES(fixture.wfa); WFA::AccessibleStateMap::const_iterator iter; EXPECT_EQ(2u, start_closure.size()); EXPECT_CONTAINS(start_closure, start); EXPECT_CONTAINS(start_closure, middle); EXPECT_EQ(1u, middle_closure.size()); EXPECT_CONTAINS(middle_closure, middle); EXPECT_EQ(2u, almost_closure.size()); EXPECT_CONTAINS(almost_closure, almost); EXPECT_CONTAINS(almost_closure, accept); EXPECT_EQ(1u, accept_closure.size()); EXPECT_CONTAINS(accept_closure, accept); } void check_shortest_distance_eq(unsigned expected, sem_elem_t actual_rp) { ShortestPathSemiring * actual = dynamic_cast<ShortestPathSemiring*>(actual_rp.get_ptr()); ASSERT_TRUE(actual != NULL); EXPECT_EQ(expected, actual->getNum()); } TEST(wali$wfa$$epsilonClose, weightFromOneEpsilonTrans) { // eps(d2) // -->o-------->(o) // Create the automaton Key start = getKey("start"); Key accept = getKey("accept"); WFA wfa; wfa.addState(start, sh_distance::dist0); wfa.addState(accept, sh_distance::dist0); wfa.setInitialState(start); wfa.addFinalState(accept); wfa.addTrans(start, WALI_EPSILON, accept, sh_distance::dist2); // Create the queries WFA::AccessibleStateMap start_zero, start_ten; start_zero[start] = sh_distance::dist0; // Issue queries WFA::AccessibleStateMap end_from_zero = checkedEpsilonClose(wfa, start); EXPECT_CONSISTENT_EPSILON_CLOSURES(wfa); // Check the answers EXPECT_EQ(2u, end_from_zero.size()); ASSERT_TRUE(end_from_zero.find(start) != end_from_zero.end()); ASSERT_TRUE(end_from_zero.find(accept) != end_from_zero.end()); check_shortest_distance_eq(0u, end_from_zero[start]); check_shortest_distance_eq(2u, end_from_zero[accept]); } TEST(wali$wfa$$epsilonClose, weightFromTwoEpsilonTransInSequence) { // eps(d1) eps(d2) // -->o-------->o------->(o) // Create the automaton Key start = getKey("start"); Key middle = getKey("middle"); Key accept = getKey("accept"); WFA wfa; wfa.addState(start, sh_distance::dist0); wfa.addState(middle, sh_distance::dist0); wfa.addState(accept, sh_distance::dist0); wfa.setInitialState(start); wfa.addFinalState(accept); wfa.addTrans(start, WALI_EPSILON, middle, sh_distance::dist1); wfa.addTrans(middle, WALI_EPSILON, accept, sh_distance::dist2); // Create the queries WFA::AccessibleStateMap start_zero, start_ten; start_zero[start] = sh_distance::dist0; // Issue queries WFA::AccessibleStateMap end_from_zero = checkedEpsilonClose(wfa, start); EXPECT_CONSISTENT_EPSILON_CLOSURES(wfa); // Check the answers EXPECT_EQ(3u, end_from_zero.size()); ASSERT_TRUE(end_from_zero.find(start) != end_from_zero.end()); ASSERT_TRUE(end_from_zero.find(middle) != end_from_zero.end()); ASSERT_TRUE(end_from_zero.find(accept) != end_from_zero.end()); check_shortest_distance_eq(0u, end_from_zero[start]); check_shortest_distance_eq(1u, end_from_zero[middle]); check_shortest_distance_eq(3u, end_from_zero[accept]); } TEST(wali$wfa$$epsilonClose, weightOnDiamond) { // The goal of this test is to make sure that: // // 1. The weight on C is set to 2, not 11, despite 11 // (hopefully) being encountered first // // 2. The weight on E is set to 3, not 12, despite E(12) // (hopefully) being encountered before even C(2). This // makes sure that C was reinserted onto the worklist when // we saw that the weight changed. // // All transitions are epsilon; given are weights // 1 10 1 // -->A-------->B-------->C------->E // | /\ [anti-multi-line comment] // | | // \-------->D---------/ // 1 1 // Create the automaton Key A = getKey("A"); Key B = getKey("B"); Key C = getKey("C"); Key D = getKey("D"); Key E = getKey("E"); if (C < B) { // Makes "sure" that we pull B off the worklist before C std::swap(C, B); } if (D < C) { std::swap(D, C); } WFA wfa; wfa.addState(A, sh_distance::dist0); wfa.addState(B, sh_distance::dist0); wfa.addState(C, sh_distance::dist0); wfa.addState(D, sh_distance::dist0); wfa.addState(E, sh_distance::dist0); wfa.setInitialState(A); wfa.addFinalState(E); wfa.addTrans(A, WALI_EPSILON, B, sh_distance::dist1); wfa.addTrans(A, WALI_EPSILON, D, sh_distance::dist1); wfa.addTrans(B, WALI_EPSILON, C, sh_distance::dist10); wfa.addTrans(D, WALI_EPSILON, C, sh_distance::dist1); wfa.addTrans(C, WALI_EPSILON, E, sh_distance::dist1); // Create the queries WFA::AccessibleStateMap start_zero; start_zero[A] = sh_distance::dist0; // Issue queries WFA::AccessibleStateMap end_from_zero = checkedEpsilonClose(wfa, A); EXPECT_CONSISTENT_EPSILON_CLOSURES(wfa); // Check the answers EXPECT_EQ(5u, end_from_zero.size()); ASSERT_TRUE(end_from_zero.find(A) != end_from_zero.end()); ASSERT_TRUE(end_from_zero.find(B) != end_from_zero.end()); ASSERT_TRUE(end_from_zero.find(C) != end_from_zero.end()); ASSERT_TRUE(end_from_zero.find(D) != end_from_zero.end()); ASSERT_TRUE(end_from_zero.find(E) != end_from_zero.end()); check_shortest_distance_eq(0u, end_from_zero[A]); check_shortest_distance_eq(1u, end_from_zero[B]); check_shortest_distance_eq(2u, end_from_zero[C]); check_shortest_distance_eq(1u, end_from_zero[D]); check_shortest_distance_eq(3u, end_from_zero[E]); } TEST(wali$wfa$$epsilonClose, epsilonCycleKeepsIterating) { // eps // A <------> B Key A = getKey("A"); Key B = getKey("B"); sem_elem_t distance_one = new LongestSaturatingPathSemiring(1, 10); test_semelem_impl(distance_one); WFA wfa; wfa.addState(A, distance_one); wfa.addState(B, distance_one); wfa.setInitialState(A); wfa.addTrans(A, WALI_EPSILON, B, distance_one); wfa.addTrans(B, WALI_EPSILON, A, distance_one); WFA::AccessibleStateMap accessible = checkedEpsilonClose(wfa, A); EXPECT_CONSISTENT_EPSILON_CLOSURES(wfa); EXPECT_EQ(2u, accessible.size()); EXPECT_NE(accessible.find(A), accessible.end()); EXPECT_NE(accessible.find(B), accessible.end()); LongestSaturatingPathSemiring * w_a = dynamic_cast<LongestSaturatingPathSemiring*>(accessible[A].get_ptr()), * w_b = dynamic_cast<LongestSaturatingPathSemiring*>(accessible[B].get_ptr()); ASSERT_TRUE(w_a != 0); ASSERT_TRUE(w_b != 0); EXPECT_EQ(10u, w_a->getNum()); // 0 max (1+1) max (1+1+1+1) max ...max 10 EXPECT_EQ(10u, w_b->getNum()); // 1 max (1+1+1) max (1+1+1+1+1) max ... max 10 } TEST(wali$wfa$$epsilonClose, closureExtendsDoneInCorrectOrder) { using namespace wali::domains::binrel; // I need something that is non-commutative. ProgramBddContext voc; voc.addIntVar("x", 4); // Make the weights: // to_zero * havoc = havoc // havoc * to_zero = to_zero sem_elem_t to_zero = new BinRel(&voc, voc.Assign("x", voc.Const(0))); sem_elem_t havoc = new BinRel(&voc, voc.True()); // The following is needed because of some extra stuff that // Prathmesh does that I don't understand. // // to_zero starts out as: <x':0> // havoc starts out as: <__regSize:2, __regA':1> // thus havoc*to_zero is: <x':0, __regSize:2, __regA':1> // // The following line deals with those extra regSize/regA things // so that they are present in to_zero as well. to_zero = havoc->extend(to_zero); ASSERT_TRUE(to_zero->equal(havoc->extend(to_zero))); ASSERT_TRUE(!havoc->equal(havoc->extend(to_zero))); // Make the WFA // eps eps // A ---------> B ------> C // [havoc x] [x:=0] WFA wfa; Key A = getKey("A"); Key B = getKey("B"); Key C = getKey("C"); wfa.addState(A, havoc->zero()); wfa.addState(B, havoc->zero()); wfa.addState(C, havoc->zero()); wfa.setInitialState(A); wfa.addTrans(A, WALI_EPSILON, B, havoc); wfa.addTrans(B, WALI_EPSILON, C, to_zero); // A should be reachable with weight one // B should be reachable with weight [havoc x] // C should be reachable with weight ([havoc x] * [x:=0]) = [x:=0] WFA::AccessibleStateMap accessible = checkedEpsilonClose(wfa, A); EXPECT_CONSISTENT_EPSILON_CLOSURES(wfa); EXPECT_EQ(3u, accessible.size()); EXPECT_NE(accessible.find(A), accessible.end()); EXPECT_NE(accessible.find(B), accessible.end()); EXPECT_NE(accessible.find(C), accessible.end()); #if 0 wfa.print(std::cout); std::cout << "C weight: "; accessible[C]->print(std::cout); #endif EXPECT_TRUE(to_zero->one()->equal(accessible[A])); EXPECT_TRUE(havoc->equal(accessible[B])); EXPECT_TRUE(to_zero->equal(accessible[C])); } TEST(wali$wfa$$removeEpsilons, epsilonCycleTerminates) { // eps // A <------> B Key A = getKey("A"); Key B = getKey("B"); sem_elem_t one = Reach(true).one(); WFA wfa; wfa.addState(A, one); wfa.addState(B, one); wfa.setInitialState(A); wfa.addTrans(A, WALI_EPSILON, B, one); wfa.addTrans(B, WALI_EPSILON, A, one); WFA no_eps = wfa.removeEpsilons(); } TEST(wali$wfa$$epsilonClose, unreachableNodes) { // // -> A (B) Key A = getKey("A"); Key B = getKey("B"); sem_elem_t one = Reach(true).one(); WFA wfa; wfa.addState(A, one); wfa.addState(B, one); wfa.setInitialState(A); wfa.addFinalState(B); EXPECT_CONSISTENT_EPSILON_CLOSURES(wfa); WFA::AccessibleStateMap eclose_A = checkedEpsilonClose(wfa, A); WFA::AccessibleStateMap eclose_B = checkedEpsilonClose(wfa, B); EXPECT_EQ(1u, eclose_A.size()); EXPECT_EQ(1u, eclose_B.size()); EXPECT_CONTAINS(eclose_A, A); EXPECT_CONTAINS(eclose_B, B); } TEST(wali$wfa$$epsilonClose, zeroWeightsAreOmitted) { // zero // -> A ---> (B) Key A = getKey("A"); Key B = getKey("B"); sem_elem_t zero = Reach(true).zero(); WFA wfa; wfa.addState(A, zero); wfa.addState(B, zero); wfa.addTrans(A, A, B, zero); wfa.setInitialState(A); wfa.addFinalState(B); EXPECT_CONSISTENT_EPSILON_CLOSURES(wfa); WFA::AccessibleStateMap eclose_A = checkedEpsilonClose(wfa, A); EXPECT_EQ(1u, eclose_A.size()); EXPECT_CONTAINS(eclose_A, A); } TEST(wali$wfa$$epsilonClose, epsilonTransitions) { // A * * * * // -> A ---> 1 ---> 2 ---> ... ---> 100 -----> B Key A = getKey("A"); Key B = getKey("B"); const size_t N = 100; Key keys[N]; for (size_t i = 0; i < N; ++i) keys[i] = getKey(i); sem_elem_t zero = Reach(true).zero(); sem_elem_t one = Reach(true).one(); WFA wfa; wfa.addState(A, zero); wfa.addState(B, zero); for (size_t i = 0; i < N; ++i) wfa.addState(keys[i], zero); wfa.addTrans(A, A, keys[0], one); for (size_t i = 0; i < N-1; ++i) wfa.addTrans(keys[i], WALI_EPSILON, keys[i+1], one); wfa.addTrans(keys[N-1], WALI_EPSILON, B, one); wfa.setInitialState(A); wfa.addFinalState(B); wfa = wfa.removeEpsilons(); wfa.prune(); EXPECT_EQ(2u, wfa.getStates().size()); EXPECT_EQ(1u, wfa.getFinalStates().size()); } } }
#pragma once #include "BaseService/BaseService.h" class GroupCorrelations; class CorrelationsService : public BaseService { Q_OBJECT public: explicit CorrelationsService(QObject *parent = nullptr); public slots: void getDefaultGroupsCorrelations(int testId, int scaleId) const; signals: void defaultGroupsCorrelationsGot(const QList<GroupCorrelations> &groupsCorrelations); private slots: void defaultGroupsCorrelationsJsonGot(const QJsonArray &groupsCorrelationsJson); };
// Created on: 2016-07-07 // Copyright (c) 2016 OPEN CASCADE SAS // Created by: Oleg AGASHIN // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepMesh_TorusRangeSplitter_HeaderFile #define _BRepMesh_TorusRangeSplitter_HeaderFile #include <BRepMesh_UVParamRangeSplitter.hxx> #include <IMeshTools_Parameters.hxx> //! Auxiliary class extending UV range splitter in order to generate //! internal nodes for NURBS surface. class BRepMesh_TorusRangeSplitter : public BRepMesh_UVParamRangeSplitter { public: //! Constructor. BRepMesh_TorusRangeSplitter() { } //! Destructor. virtual ~BRepMesh_TorusRangeSplitter() { } //! Returns list of nodes generated using surface data and specified parameters. Standard_EXPORT virtual Handle(IMeshData::ListOfPnt2d) GenerateSurfaceNodes( const IMeshTools_Parameters& theParameters) const Standard_OVERRIDE; //! Registers border point. Standard_EXPORT virtual void AddPoint(const gp_Pnt2d& thePoint) Standard_OVERRIDE; private: Handle(IMeshData::SequenceOfReal) fillParams( const IMeshData::IMapOfReal& theParams, const std::pair<Standard_Real, Standard_Real>& theRange, const Standard_Integer theStepsNb, const Standard_Real theScale, const Handle(NCollection_IncAllocator)& theAllocator) const; Standard_Real FUN_CalcAverageDUV(TColStd_Array1OfReal& P, const Standard_Integer PLen) const; }; #endif
#pragma once #include "main.h" class setCompression { public: typedef void(*callbackFunc)(const bool result, void *data); private: const struct workdata { Persistent<Object> self; Persistent<Function> func; }; const struct workdata2 { callbackFunc callback; void *data; HANDLE hnd; }; public: static bool basic(const wchar_t *path, const bool compress) { bool result = false; HANDLE hnd = CreateFileW(path, FILE_GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (hnd != INVALID_HANDLE_VALUE) { USHORT c = compress ? COMPRESSION_FORMAT_DEFAULT : COMPRESSION_FORMAT_NONE; DWORD d; if (DeviceIoControl(hnd, FSCTL_SET_COMPRESSION, &c, sizeof(USHORT), NULL, 0, &d, NULL)) { result = true; } CloseHandle(hnd); } return result; } static bool basicWithCallback(const wchar_t *path, const bool compress, callbackFunc callback, void *data) { bool result = false; workdata2 *work = new workdata2; work->callback = callback; work->data = data; work->hnd = CreateFileW(path, FILE_GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (work->hnd == INVALID_HANDLE_VALUE) { delete work; } else { uv_loop_t *loop = uv_default_loop(); if (CreateIoCompletionPort(work->hnd, loop->iocp, (ULONG_PTR)work->hnd, 0)) { uv_async_t *hnd = new uv_async_t; uv_async_init(uv_default_loop(), hnd, afterWork); hnd->data = work; USHORT c = compress ? COMPRESSION_FORMAT_DEFAULT : COMPRESSION_FORMAT_NONE; DeviceIoControl(work->hnd, FSCTL_SET_COMPRESSION, &c, sizeof(USHORT), NULL, 0, NULL, &hnd->async_req.THEASYNCOVERLAP); if (GetLastError() == ERROR_IO_PENDING) { result = true; } else { CloseHandle(work->hnd); uv_close((uv_handle_t*)hnd, NULL); delete hnd; delete work; } } } return result; } static Local<Function> functionRegister(bool isAsyncVersion) { ISOLATE_NEW; SCOPE_ESCAPABLE; RETURNTYPE<String> tmp; RETURNTYPE<Function> t = NEWFUNCTION(isAsyncVersion ? jsAsync : jsSync); //set errmessages RETURNTYPE<Object> errors = Object::New(ISOLATE); tmp = NEWSTRING(SYB_ERR_WRONG_ARGUMENTS); SETWITHATTR(errors, tmp, tmp, SYB_ATTR_CONST); tmp = NEWSTRING(SYB_ERR_NOT_A_CONSTRUCTOR); SETWITHATTR(errors, tmp, tmp, SYB_ATTR_CONST); SETWITHATTR(t, NEWSTRING(SYB_ERRORS), errors, SYB_ATTR_CONST); RETURN_SCOPE(t); } private: static ASYNCCB(afterWork) { workdata2 *work = (workdata2*)hnd->data; CloseHandle(work->hnd); work->callback(hnd->async_req.THEASYNCOVERLAP.Internal == ERROR_SUCCESS, work->data); uv_close((uv_handle_t*)hnd, NULL); delete hnd; delete work; } static JSFUNC(jsSync) { ISOLATE_NEW_ARGS; SCOPE; RETURNTYPE<Value> result; if (args.IsConstructCall()) { result = THROWEXCEPTION(SYB_ERR_NOT_A_CONSTRUCTOR); } else { if (args.Length() > 0 && (args[0]->IsString() || args[0]->IsStringObject())) { String::Value spath(args[0]); result = basic((wchar_t*)*spath, args[1]->ToBoolean()->IsTrue()) ? True(ISOLATE) : False(ISOLATE); } else { result = THROWEXCEPTION(SYB_ERR_WRONG_ARGUMENTS); } } RETURN(result); } static JSFUNC(jsAsync) { ISOLATE_NEW_ARGS; SCOPE; RETURNTYPE<Value> result; if (args.IsConstructCall()) { result = THROWEXCEPTION(SYB_ERR_NOT_A_CONSTRUCTOR); } else { if (args.Length() > 0 && (args[0]->IsString() || args[0]->IsStringObject())) { workdata *data = NULL; bool b; if (args.Length() > 1) { if (args[1]->IsFunction()) { data = new workdata; PERSISTENT_NEW(data->self, args.This(), Object); PERSISTENT_NEW(data->func, RETURNTYPE<Function>::Cast(args[1]), Function); b = args[2]->ToBoolean()->IsTrue(); } else { b = args[1]->ToBoolean()->IsTrue(); } } else { b = false; } String::Value p(args[0]); if (basicWithCallback((wchar_t*)*p, b, asyncCallback, data)) { result = True(ISOLATE); } else { if (data) { PERSISTENT_RELEASE(data->self); PERSISTENT_RELEASE(data->func); delete data; } result = False(ISOLATE); } } else { result = THROWEXCEPTION(SYB_ERR_WRONG_ARGUMENTS); } } RETURN(result); } static void asyncCallback(const bool succeeded, void *data) { if (data) { ISOLATE_NEW; SCOPE; workdata *work = (workdata*)data; RETURNTYPE<Value> r = succeeded ? True(ISOLATE) : False(ISOLATE); PERSISTENT_CONV(work->func, Function)->Call(PERSISTENT_CONV(work->self, Object), 1, &r); PERSISTENT_RELEASE(work->self); PERSISTENT_RELEASE(work->func); delete work; } } };
#include <vector> #include <string> #include <iostream> #include <map> #include <set> #include <fstream> #include <sstream> using namespace std; template<class T> class MyHeap { vector<pair<int, T> > array; map<T, int> positions; int parent_id(int i) { return (i - 1) / 2; } int get_min_child(int i) { int child1 = i * 2 + 1; int child2 = i * 2 + 2; if (child1 >= array.size()) return -1; if (child2 >= array.size()) return child1; if (array[child1].first < array[child2].first) return child1; return child2; } void swap(int i, int j) { positions[array[i].second] = j; positions[array[j].second] = i; pair<int, T> tmp; tmp = array[i]; array[i] = array[j]; array[j] = tmp; } int heapify(int i) { int to_swap = get_min_child(i); if (to_swap != -1 && array[to_swap].first < array[i].first) { swap(to_swap, i); return to_swap; } return -1; } public: MyHeap() { } MyHeap(const vector<pair<int, T> > from_array) : array(from_array) { } int size() const { return array.size(); } void insert(pair<int, T> element) { array.push_back(element); positions[element.second] = array.size() - 1; int parent = parent_id(array.size() - 1); while (heapify(parent) != -1) { parent = parent_id(parent); } } void remove(T element) { int pos = positions[element]; positions.erase(element); if (array.size() == 1) { array = vector<pair<int, T> > (); positions = map<T,int> (); return; } if (pos == array.size() - 1) { array.pop_back(); return; } array[pos] = array.back(); array.pop_back(); while((pos = heapify(pos)) != -1) ; } bool in_heap(T element) { return (positions.count(element) > 0); } pair<int, T> get_min() { pair<int, T> result = array[0]; remove(result.second); return result; } }; void dijkstra_simple(map<int, map<int,int> >& ad_m, map<int, int>& min_length, int s) { set<int> X; min_length[s] = 0; X.insert(s); while(X.size() != ad_m.size()) { cout<<X.size()<<"\n"; int nxt; int mn = 1000000000; for(set<int>::iterator si=X.begin();si!=X.end();si++) { for (map<int,int>::iterator mi = ad_m[*si].begin(); mi != ad_m[*si].end();mi++) { pair<int,int> candidate = (*mi); if(min_length[candidate.first] > (min_length[*si] + candidate.second)) { min_length[candidate.first] = min_length[*si] + candidate.second; } if (min_length[candidate.first] < mn && X.count(candidate.first) == 0) { mn = min_length[candidate.first]; nxt = candidate.first; } } } X.insert(nxt); } } void dijkstra(map<int, map<int,int> >& ad_m, map<int, int>& min_length, int s) { set<int> X; min_length[s] = 0; MyHeap<int> m_heap; m_heap.insert(make_pair(0,s)); while(X.size() != ad_m.size()) // && m_heap.size() > 0) { if (m_heap.size() == 0) { for (set<int>::iterator si=X.begin();si!=X.end();si++) { cout<<(*si)<<" "; } cout<<"\n"; return; } pair<int,int> nxt = m_heap.get_min(); X.insert(nxt.second); for (map<int,int>::iterator mi = ad_m[nxt.second].begin(); mi != ad_m[nxt.second].end();mi++) { pair<int,int> candidate = (*mi); if(min_length[candidate.first] > (min_length[nxt.second] + candidate.second)) { min_length[candidate.first] = min_length[nxt.second] + candidate.second; if (m_heap.in_heap(candidate.first)) m_heap.remove(candidate.first); m_heap.insert(make_pair(min_length[candidate.first], candidate.first)); } } } } int main(int argc, char** argv) { MyHeap<int> m_heap; map<int, map<int,int> > ad_m; map<int,int> min_length; ifstream f; f.open(argv[1]); string s; while(getline(f,s)) { int vertex_a, vertex_b, length; stringstream st(s); st>>vertex_a; min_length[vertex_a] = 2000000000; string k; while (st>>k) { vertex_b = stoi(k.substr(0, k.find(','))); length = stoi(k.substr(k.find(',') + 1, k.size() - k.find(','))); ad_m[vertex_a][vertex_b] = length; ad_m[vertex_b][vertex_a] = length; } } dijkstra_simple(ad_m, min_length, 1); cout<<min_length[7]<<"," <<min_length[37]<<"," <<min_length[59]<<"," <<min_length[82]<<"," <<min_length[99]<<"," <<min_length[115]<<"," <<min_length[133]<<"," <<min_length[165]<<"," <<min_length[188]<<"," <<min_length[197] ; cout<<"\n"; return 0; }
#include<iostream> #include<cstdio> #include<queue> #include<stack> #include<cstring> #define MAX_SIZE 20001 #define ull unsigned long long int using namespace std; struct object { ull number; int remainder; int d; }; void display(object temp) { stack<bool> s; while(temp.d) { s.push(temp.number&1); temp.number >>=1; temp.d--; } while(!s.empty()) { printf("%d",(s.top()==true)); s.pop(); } printf("\n"); } void answer(int n) { bool flag=false; bool rems[MAX_SIZE]; queue<object> q; object temp; temp.number=1; temp.remainder=1%n; temp.d=1; q.push(temp); memset(rems,0,sizeof(rems)); while(!q.empty() && !flag) { temp=q.front(); q.pop(); if(temp.remainder==0) flag=true; else { temp.number<<=1; temp.remainder*=10; temp.remainder%=n; temp.d++; if(!rems[temp.remainder]) { q.push(temp); rems[temp.remainder]=true; } temp.number|=1; temp.remainder+=1; temp.remainder%=n; if(!rems[temp.remainder]) { q.push(temp); rems[temp.remainder]=true; } } } display(temp); } int main() { int k,n; scanf("%d",&k); while(k--) { scanf("%d",&n); answer(n); } return 0; }
#include <Arduino.h> #include <ESPReactWifiManager.h> #include <ESPAsyncWebServer.h> namespace { AsyncWebServer *server = nullptr; ESPReactWifiManager *wifiManager = nullptr; } // namespace void setup() { delay(1000); Serial.begin(115200); Serial.println(F("\nHappy debugging!")); Serial.flush(); if (!SPIFFS.begin()) { Serial.println(F("An Error has occurred while mounting SPIFFS")); return; } #if defined(ESP8266) WiFi.setSleepMode(WIFI_NONE_SLEEP); #endif server = new AsyncWebServer(80); server->serveStatic(PSTR("/static/js/"), SPIFFS, PSTR("/")) .setCacheControl(PSTR("max-age=86400")); server->serveStatic(PSTR("/static/css/"), SPIFFS, PSTR("/")) .setCacheControl(PSTR("max-age=86400")); server->serveStatic(PSTR("/"), SPIFFS, PSTR("/")) .setCacheControl(PSTR("max-age=86400")) .setDefaultFile(PSTR("wifi.html")); wifiManager = new ESPReactWifiManager(); wifiManager->onFinished([](bool isAPMode) { server->begin(); }); wifiManager->onNotFound([](AsyncWebServerRequest* request) { request->send(SPIFFS, F("wifi.html")); }); wifiManager->setupHandlers(server); wifiManager->autoConnect(F("REACT")); } void loop() { wifiManager->loop(); }
#include<iostream> using namespace std; int main() { int input[5],i,j,count1,count2,temp,sol,flag; while(1) { count1=0;count2=0; for(i=0;i<5;i++) cin>>input[i]; if(input[0]==0) break; for(i=0;i<3;i++) { for(j=i+1;j<3;j++) if(input[i]>input[j]) { temp=input[i]; input[i]=input[j]; input[j]=temp; } } if(input[3]>input[4]) { temp=input[3]; input[3]=input[4]; input[4]=temp; } for(i=0;i<3;i++) { if(input[i]<input[3]) count1++; if(input[i]<input[4]) count2++; } if(count1+count2>=4||count1==3||count2==3) { if(count1+count2==6) sol=0; else{ if(input[3]<input[1]) sol=input[2]; else sol=input[1]; } } else sol=52; for(i=sol+1;i<=52;i++) { for(j=0,flag=0;j<5;j++) { if(input[j]==i) { flag=1; break; } } if(flag!=1) break; } if(i>52) cout<<-1<<endl; else cout<<i<<endl; } return 0; }
#include "predictor.h" #include <stdint.h> #include <math.h> ///////////////////////////////////////////////////////////// // 2bitsat ///////////////////////////////////////////////////////////// #define BIMODAL_PREDICTION_TABLE_SIZE 4096 uint8_t bimodal_saturating_counter[BIMODAL_PREDICTION_TABLE_SIZE]; int GetTableIndex_2bitsat(UINT32 PC){ return PC%BIMODAL_PREDICTION_TABLE_SIZE; } void InitPredictor_2bitsat() { int i; for (i=0; i<BIMODAL_PREDICTION_TABLE_SIZE; i++){ bimodal_saturating_counter[i] = 0b01; } } bool GetPrediction_2bitsat(UINT32 PC) { int index = GetTableIndex_2bitsat(PC); if (bimodal_saturating_counter[index] > 1) return TAKEN; else return NOT_TAKEN; } void UpdatePredictor_2bitsat(UINT32 PC, bool resolveDir, bool predDir, UINT32 branchTarget) { int index = GetTableIndex_2bitsat(PC); if(resolveDir && bimodal_saturating_counter[index] < 0b11) bimodal_saturating_counter[index]++; else if(!resolveDir && bimodal_saturating_counter[index] > 0b00) bimodal_saturating_counter[index]--; } ///////////////////////////////////////////////////////////// // 2level ///////////////////////////////////////////////////////////// #define BHT_SIZE 512 #define PHT_SIZE 64 #define PHT_COUNT 8 uint8_t branch_history_table[BHT_SIZE]; uint8_t pattern_history_tables[PHT_COUNT][PHT_SIZE]; void InitPredictor_2level() { int i, j; for (i=0; i<PHT_COUNT; i++){ for (j=0; j<PHT_SIZE; j++){ pattern_history_tables[i][j]=0b01; } } for (i=0; i<BHT_SIZE; i++){ branch_history_table[i]=0; } } bool GetPrediction_2level(UINT32 PC) { int phtIndex, bhtIndex, phtEntryIndex; phtIndex = PC & 0b0111; bhtIndex = (PC & 0b0111111111000)>>3; phtEntryIndex = branch_history_table[bhtIndex]; if(pattern_history_tables[phtIndex][phtEntryIndex]>1) return TAKEN; else return NOT_TAKEN; } void UpdatePredictor_2level(UINT32 PC, bool resolveDir, bool predDir, UINT32 branchTarget) { int phtIndex, bhtIndex, phtEntryIndex; phtIndex = PC & 0b0111; bhtIndex = (PC & 0b0111111111000)>>3; phtEntryIndex = branch_history_table[bhtIndex]; if(resolveDir && pattern_history_tables[phtIndex][phtEntryIndex] < 0b11) pattern_history_tables[phtIndex][phtEntryIndex] ++; else if(!resolveDir && pattern_history_tables[phtIndex][phtEntryIndex] > 0b00) pattern_history_tables[phtIndex][phtEntryIndex] --; branch_history_table[bhtIndex] = ((branch_history_table[bhtIndex]<<1)&0b0111111)+resolveDir; } ///////////////////////////////////////////////////////////// // openend ///////////////////////////////////////////////////////////// /* M distinct predictor tables Ti 0 <= i < M BHR is global = good for tight branch correlative index by hash function which input = { branch PC and global BHR} To make prediction Ci = counter in each prediction table Ti Prediction (S) = M/2 + sum of C(i) where 0 <= i < M if S > 0 = taken and vice versa */ /* based on research paper 4 to 12 tables are good in terms of performance and cost trade off based on more information, more accurate, 12 tables are choosen "experiments showed that using 4-bit or 5-bit counters with 4 to 12 tables is cost-effective */ #define Num_Table 12 /* Based on research paper, 4 bits and 5 bits counter does not have absolute performance advantage over each other, 4 bits is overwhemling on some benchmarks and 5 bits one on other benchmarks, so there is limit constraints on total cache size, so choose 4 bits counter 4 bits counter = signed number => -8 to 7 value range */ #define MAX_Count 15 #define MIN_Count -16 /* PC portion to calcualte hash based on the current system PC = UNIT32, we choose 4K page size code are load page by page, and most significant 20 bits are not change very much, which means least significant 12 bits are not fixed and dynamically change during run time, so choose 12 bits to make hash function */ #define PC_part_index 12 /* Based on research paper L1 and L11 magic L number should be this*/ #define L1 3 #define L11 223 signed int threshold; int max_counter_value; int min_counter_value; double alpha_power; double alpha; //double init_Geometric; /* " For computing the hash function to index Table Ti, being the number of entries on Ti, we regularly pick 3n bits in the vector of bits composed with the least significant bits of the branch address and the L(i) bits of history." Also, based on research paper, page table should be 2048 entries each slot of prediction table is a signed counter which is 2^5 bits value is from - 16 to 15 */ int32_t PHT[Num_Table][2048]; #define pht_entries 11 //There are 12 tables UINT32 L[Num_Table]; //prediction length for each table /* efficiently exploits very long global histories in the 100-200 bits range. refer global_BHR bits = 4 UINT64 = 256 bits */ //256 bits of BHR, based on research paper UINT64 global_BHR[4]; // 256 bit BHR int Index_Geometric_hash_PHT(UINT32 PC, UINT64 *BHR , UINT32 history_length){ UINT64 index; UINT64 xor_get_input; UINT64 history; /* * Based on research paper, there is a one level and 3 entries for XOR gate input * To get index of each PHT, a signle stage of three-entry xor gates * will be used to compute the index bit */ UINT32 num_xor_entry = 3; UINT32 BHR_bountry; UINT32 PC_bountry; UINT32 BHR_index; UINT32 PC_length; UINT32 i; UINT32 shift_bits; bool BHR_bountry_set = false; /* * Based on researh paper, the input for XOR should be * 3n where n = log(number of entry of a table) * there are 2048 entries in one table log(2048) = 11 * so input bits should be 3 * 11 = 33 bits */ UINT64 BHR_index_chosen[num_xor_entry * pht_entries]; /* * The composition of inputs = * part of PC * part of history bits = BHR * Based on research paper, there are 33 bits to the xor gate, * But there are 256 bits BHR and 12 bits PC in total * L = number of bists should be used in making the entry of the xor gate * There are 12 tables, and each unique L for each table, * In other words, each table take different size of history bits to hash an * index of prediction table to get a counter */ UINT64 xor_input_bits = num_xor_entry * pht_entries; /* * The solution to get 33 bits from more than 33 bits * For example, we choose PC = 12 bits to make xor gate inputs * and on the other hand, should select 128 bits from BHR history bits * there are total 140 bits for 33 bits entry. To make sure every time that * same PC and same table, for like same 12 bits PC and same table with the same L * same indexes should be produced from BHR, so the solution to achieve this, is use a formular to * calculate the index out for each pair of 12 bits PC and L of BHR, so everytime same set * of indexes of BHR will be got and used */ /* * choose indexes of BHR * simply add (12 of bits and L) / 33 bits to achieve the object discussed above, to get same indexes of BHR * everytime, if the indexes excceed the L, then should stop, rest of 33 bits should select from PC. As mentioned * eariler, 33 bits composed of BHR and 12 bits of PC */ UINT64 total_input_bits = PC_part_index + history_length; //get interval double bhr_index_selector = (double)total_input_bits/(double)33; for (i = 0; i < (xor_input_bits & 0x1FFFF); i++){ // get selected index of BHR BHR_index_chosen[i] = (UINT64)i * bhr_index_selector; if( (!BHR_bountry_set) && ((BHR_index_chosen[i] & 0x1FFFF) > history_length)){ BHR_bountry = i; BHR_bountry_set = true; } } PC_length = 32 - BHR_bountry; PC_bountry = BHR_bountry; /* * Simply go around again to get BHR_bountry bits of BHR and put it into intermidiant * target index could be in one BHR[i], and also could be in different BHR[i] * because 256 bits BHR, we use UINT64 BHR[4] to mimic 256 bits */ bool in_same_BHR; bool is_set_0 = false; bool is_set_1 = false; bool is_set_2 = false; BHR_index = 0; //bit 0 of entry already get, so get from the 1th bit for (i = 0; i < BHR_bountry; i++){ // bit 0 of entry input = no need to shift if(i == 0){ history = global_BHR[0]; xor_get_input = (history & 1); } else{ /* * check if two index they are in the same BHR[i] * if still in the same register, just shift another interval * if in the next BHR, just BHR_index ++ move to next BHR[i] * till two index are not in the same register */ if(BHR_index_chosen[i] >= 64 && BHR_index_chosen[i - 1] <= 63){ in_same_BHR = false; if(!is_set_0){ BHR_index++; is_set_0 = true; } } else if(BHR_index_chosen[i] >= 128 && BHR_index_chosen[i - 1] <= 127){ in_same_BHR = false; if(!is_set_1){ BHR_index++; is_set_1 = true; } } else if(BHR_index_chosen[i] >= 192 && BHR_index_chosen[i - 1] <= 191){ in_same_BHR = false; if(!is_set_2){ BHR_index++; is_set_2 = true; } } else in_same_BHR = true; //get how many bits to shift BHR and put it into intermidiant if(in_same_BHR) //this one better, no shift difference shift_bits = BHR_index_chosen[i] - BHR_index_chosen[i - 1]; //shift_bits = bhr_index_selector; this average becomes 5.783 else{ history = global_BHR[BHR_index]; shift_bits = BHR_index_chosen[i] & 0xFFFFFFFF; //shift_bits = bhr_index_selector; } /* * shift left 1 bit to get 1 bit free space for */ xor_get_input = (xor_get_input << 1); history = history >> shift_bits; xor_get_input = xor_get_input + (history & 1); } } /* * Here is to get reset of 33 bits from 12 PC bits, 0 to 32 = 33 bits * for example, L = 128, BHR_bountry = 30, so still need 2 bits * from PC to make up to 33 bits of xor gate entry */ //for ( i = BHR_bountry; i < (xor_input_bits & 0x1FFFF); i++){ for(i = 0; i < PC_length; i++, PC_bountry++){ shift_bits = (BHR_index_chosen[PC_bountry] & 0x1FFFF)- history_length; xor_get_input = (xor_get_input << 1); //To enable and increase the weight of PC address in calcuating the xor_get_input += ((PC >> shift_bits) ^ 0b1); } /* * 33 bits of xor input has been selected * to xor each 11 bits part */ UINT64 temp1; UINT64 temp2; UINT64 temp3; temp1 = xor_get_input & 0b011111111111; temp2 = (xor_get_input >> 11) & 0b011111111111; temp3 = (xor_get_input >> 22) & 0b011111111111; index = temp1 ^ temp2 ^ temp3; return (int)index; } void InitPredictor_openend() { int i, j; for( i = 0; i < Num_Table; i++){ for(j = 0; j < 2048; j ++) PHT[i][j] = 0; //counter = 0; } for (i = 0; i < 5; i++){ global_BHR[i] = 0x0000000000000000; } L[0] = 0; //only PC L[1] = L1; /* based on research best geometric L(1)=3, L(10)=223, REF-0.02 misp/KI best overall {0, 2, 4, 9, 12, 18, 31, 54, 114, 145, 266} REF-0.04 misp/KI history length formula: alpha = (L(M - 1)/L(1)) ^ (1/(M - 2)) where M = number of page tables */ threshold = Num_Table; //init_Geometric = L1; alpha_power = ((double)1)/((double) Num_Table - 2); alpha = pow(L11/L1, alpha_power); for( i = 2; i < Num_Table; i++ ){ L[i] = (int) ((L1 * pow(alpha, (double) (i - 1)))); } } bool GetPrediction_openend(UINT32 PC) { int sum = Num_Table/2; int i; int pht_index[Num_Table]; /* * based on research paper, prediction decision is made based on sum value * sum = M/2 + sum of C(i) where i = [0...M] */ for(i = 0; i < Num_Table; i++){ //get index pht_index[i] = Index_Geometric_hash_PHT(PC, global_BHR, L[i]); //sum sum += PHT[i][pht_index[i]]; } return ( sum >= 0 ? TAKEN : NOT_TAKEN); //return TAKEN; } void UpdatePredictor_openend(UINT32 PC, bool resolveDir, bool predDir, UINT32 branchTarget) { int i; int sum = Num_Table/2; int pht_index[Num_Table]; for (i = 0; i < Num_Table; i++){ pht_index[i] = Index_Geometric_hash_PHT(PC, global_BHR, L[i]); sum += PHT[i][pht_index[i]]; } if((predDir != resolveDir) || abs(sum) < threshold){ for (i = 0; i < Num_Table; i++){ if(resolveDir){ if(PHT[i][pht_index[i]] < MAX_Count) PHT[i][pht_index[i]]++; else PHT[i][pht_index[i]] = MAX_Count; } else{ if(PHT[i][pht_index[i]] > MIN_Count) PHT[i][pht_index[i]]--; else PHT[i][pht_index[i]] = MIN_Count; } } } //update BHR value = 256 bits for (i = 5; i > 0; i--) global_BHR[i] = (global_BHR[i] << 1) | ((global_BHR[i-1] >> 63) & 0b1); global_BHR[0] = global_BHR[0] << 1; if(resolveDir) global_BHR[0] = global_BHR[0] | 0b1; }
// Created on: 1992-04-06 // Created by: Christophe MARION // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _HLRAlgo_EdgesBlock_HeaderFile #define _HLRAlgo_EdgesBlock_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TColStd_Array1OfInteger.hxx> #include <TColStd_Array1OfBoolean.hxx> #include <Standard_Integer.hxx> #include <Standard_Transient.hxx> #include <TopAbs_Orientation.hxx> class HLRAlgo_EdgesBlock; DEFINE_STANDARD_HANDLE(HLRAlgo_EdgesBlock, Standard_Transient) //! An EdgesBlock is a set of Edges. It is used by the //! DataStructure to structure the Edges. //! //! An EdgesBlock contains : //! //! * An Array of index of Edges. //! //! * An Array of flagsf ( Orientation //! OutLine //! Internal //! Double //! IsoLine) class HLRAlgo_EdgesBlock : public Standard_Transient { public: struct MinMaxIndices { Standard_Integer Min[8], Max[8]; MinMaxIndices& Minimize(const MinMaxIndices& theMinMaxIndices) { for (Standard_Integer aI = 0; aI < 8; ++aI) { if (Min[aI] > theMinMaxIndices.Min[aI]) { Min[aI] = theMinMaxIndices.Min[aI]; } if (Max[aI] > theMinMaxIndices.Max[aI]) { Max[aI] = theMinMaxIndices.Max[aI]; } } return *this; } MinMaxIndices& Maximize(const MinMaxIndices& theMinMaxIndices) { for (Standard_Integer aI = 0; aI < 8; ++aI) { if (Min[aI] < theMinMaxIndices.Min[aI]) { Min[aI] = theMinMaxIndices.Min[aI]; } if (Max[aI] < theMinMaxIndices.Max[aI]) { Max[aI] = theMinMaxIndices.Max[aI]; } } return *this; } }; //! Create a Block of Edges for a wire. Standard_EXPORT HLRAlgo_EdgesBlock(const Standard_Integer NbEdges); Standard_Integer NbEdges() const { return myEdges.Upper(); } void Edge (const Standard_Integer I, const Standard_Integer EI) { myEdges(I) = EI; } Standard_Integer Edge (const Standard_Integer I) const { return myEdges(I); } void Orientation (const Standard_Integer I, const TopAbs_Orientation Or) { myFlags(I) &= ~EMaskOrient; myFlags(I) |= ((Standard_Integer)Or & (Standard_Integer)EMaskOrient); } TopAbs_Orientation Orientation (const Standard_Integer I) const { return ((TopAbs_Orientation)(myFlags(I) & EMaskOrient)); } Standard_Boolean OutLine (const Standard_Integer I) const { return (myFlags(I) & EMaskOutLine) != 0; } void OutLine (const Standard_Integer I, const Standard_Boolean B) { if (B) myFlags(I) |= EMaskOutLine; else myFlags(I) &= ~EMaskOutLine; } Standard_Boolean Internal (const Standard_Integer I) const { return (myFlags(I) & EMaskInternal) != 0; } void Internal (const Standard_Integer I, const Standard_Boolean B) { if (B) myFlags(I) |= EMaskInternal; else myFlags(I) &= ~EMaskInternal; } Standard_Boolean Double (const Standard_Integer I) const { return (myFlags(I) & EMaskDouble) != 0; } void Double (const Standard_Integer I, const Standard_Boolean B) { if (B) myFlags(I) |= EMaskDouble; else myFlags(I) &= ~EMaskDouble; } Standard_Boolean IsoLine (const Standard_Integer I) const { return (myFlags(I) & EMaskIsoLine) != 0; } void IsoLine (const Standard_Integer I, const Standard_Boolean B) { if (B) myFlags(I) |= EMaskIsoLine; else myFlags(I) &= ~EMaskIsoLine; } void UpdateMinMax(const MinMaxIndices& TotMinMax) { myMinMax = TotMinMax; } MinMaxIndices& MinMax() { return myMinMax; } DEFINE_STANDARD_RTTIEXT(HLRAlgo_EdgesBlock,Standard_Transient) protected: enum EMskFlags { EMaskOrient = 15, EMaskOutLine = 16, EMaskInternal = 32, EMaskDouble = 64, EMaskIsoLine = 128 }; private: TColStd_Array1OfInteger myEdges; TColStd_Array1OfInteger myFlags; MinMaxIndices myMinMax; }; #endif // _HLRAlgo_EdgesBlock_HeaderFile
#include "../inc/SEOpenGLRenderObject.h" #include "../inc/SEDebugTools.h" #include <iostream> USEDUMPFLAG; void SEOpenGLRenderObject::applyTransformation(const SERenderServiceInternals<GLfloat> &rs) const { DUMPONCE("===SEOpenGLRenderObject::applyTransformation()==="); //glMatrixMode(GL_MODELVIEW); //DUMPONCE("glMatrixMode(GL_MODELVIEW)"); glPushMatrix(); DUMPONCE("glPushMatrix()"); glMultMatrixf(getModelMatrix().transposed().m); DUMPONCE("glMultMatrixf({"<<std::endl<<getModelMatrix()<<" })"); } void SEOpenGLRenderObject::clearTransformation(const SERenderServiceInternals<GLfloat> &rs) const { DUMPONCE("===SEOpenGLRenderObject::clearTransformation()==="); glPopMatrix(); DUMPONCE("glPopMatrix()"); }
#include "../include/Table.h" //Constructor Table::Table(int capacity):capacity(capacity), open(false), customersList(), orderList(){ //customer and order list are initliazed by default constructor as empty containers } // End Constructor //Copy Constructor Table::Table(const Table &t):capacity(),open(), customersList(), orderList(){ copy(t); } // End Copy Constructor //Destructor Table:: ~Table(){ clear(); } // End Destructor //Move Constructor Table::Table(Table &&t):capacity(), open(), customersList(), orderList(){ move(t); } // End Move Constructor //Copy Assignment Operator Table& Table::operator=(const Table &t) { if(this!=&t){ clear(); copy(t); } return *this; } //End Copy Assignment Operator //Move Assignment Operator Table& Table::operator=(Table &&t) { if (this != &t) { clear(); move(t); } return *this; } //End Move Assignment Operator //Copy - Allocates using copy constructors void Table::copy(const Table &t) { capacity = t.capacity; open = t.open; orderList = t.orderList; for (unsigned int i = 0; i < t.customersList.size(); i++) { customersList.push_back(t.customersList[i]->clone()); } } //End Copy //Clear - Deallocates fields void Table::clear(){ for (unsigned int i = 0; i < customersList.size(); ++i) { delete customersList[i]; customersList[i] = nullptr; } customersList.clear(); orderList.clear(); } //End Clear //Move - Reallocates fields void Table::move(Table &t){ customersList = std::move(t.customersList); orderList = std::move(t.orderList); capacity = t.capacity; open = t.open; } int Table::getCapacity() const { return capacity; } void Table::addCustomer(Customer *customer) { if(this->open) customersList.push_back(customer); } void Table::removeCustomer(int id) { for (unsigned int i = 0; i < customersList.size(); ++i) { if (customersList[i]->getId() == id) { customersList.erase(customersList.begin() + i); } } } Customer* Table::getCustomer(int id) { Customer* output = nullptr; for(unsigned int i = 0; i < customersList.size(); i++) { if (customersList[i]->getId() == id) { output = customersList[i]; } } return output; } std::vector<Customer*>& Table::getCustomers() { return customersList; } std::vector<OrderPair>& Table:: getOrders(){ return orderList; } void Table::order(const std::vector<Dish> &menu) { std::vector<int> tmp; // Order id's for(unsigned int i = 0; i < customersList.size(); i++){ //takes orders from all customers at table if(customersList[i] != nullptr){ tmp = customersList[i]->order(menu); //customer order command for(unsigned int j = 0; j < tmp.size(); j++){ // adds customer order to orderlist orderList.push_back(std::make_pair(customersList[i]->getId(),menu[tmp[j]])); } } } } void Table::openTable() { open = true; } void Table::closeTable(){ open = false; for (unsigned int i = 0; i < customersList.size(); ++i) { delete customersList[i]; customersList[i] = nullptr; } customersList.clear(); orderList.clear(); } int Table::getBill(){ int bill = 0; for(unsigned int i=0; i<orderList.size(); i++){ bill = bill + orderList[i].second.getPrice(); } return bill; } bool Table::isOpen() { return open; } bool Table::isEmpty() { return customersList.empty(); } std::vector<Dish> Table::movecBill(int customer_id){ //Source Table std::vector<Dish> output; std::vector<OrderPair> orderchange; for(unsigned int i = 0; i<orderList.size();i++){ if(orderList[i].first == customer_id){ output.push_back(orderList[i].second); } else{ orderchange.push_back(orderList[i]); } } orderList = std::move(orderchange); return output; } void Table::movecBill(int customer_id, std::vector<Dish> dishes){ //Destination Table for(unsigned int i = 0; i < dishes.size();i++){ OrderPair toAdd = std::make_pair(customer_id,dishes[i]); orderList.push_back(toAdd); } }
#include "loginscreen.h" #include "ui_loginscreen.h" #include <QDebug> LoginScreen::LoginScreen(QWidget *parent) : QDialog(parent), ui(new Ui::LoginScreen) { ui->setupUi(this); } LoginScreen::~LoginScreen() { delete ui; } void LoginScreen::on_pushButton_login_clicked() { QString login = ui->lineEdit_login->text(); QString password = ui->lineEdit_password->text(); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "conn"); db.setHostName("localhost"); db.setDatabaseName("ProjetoIntegrador"); db.setUserName("root"); db.setPassword("M4a10121"); bool ok = db.open(); if(!ok) { QMessageBox::warning(this, "connection", "can not open connection!"); } else { QSqlQuery q(db); q.prepare("SELECT login, password FROM users"); if(q.exec()) { while(q.next()) { if(q.value(0).toString() == login && q.value(1).toString() == password) { m = new mainMenu(); m->setAttribute(Qt::WA_DeleteOnClose); connect(m, &mainMenu::closeMenu, this, &LoginScreen::closeMenu); connect(this, &LoginScreen::logged_player, m, &mainMenu::logged_player); m->show(); emit logged_player(login);//gives the mainMenu class the username of the player that is logged disconnect(this, &LoginScreen::logged_player, m, &mainMenu::logged_player); db.close(); hide(); return; } } QMessageBox::warning(this, "error", "authentication failed!"); return; } } } void LoginScreen::on_pushButton_clicked() { c = new AccountCreation(this); c->setAttribute(Qt::WA_DeleteOnClose); connect(c, &AccountCreation::closeAccountCreation, this, &LoginScreen::closeAccountCreation); hide(); c->show(); } void LoginScreen::closeMenu() { show(); m->close(); } void LoginScreen::closeAccountCreation() { show(); c->close(); }
// 정적으로 많은 수의 배열을 잡을 때 동적으로 잡아주기! #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> using namespace std; int N, M; int nArray[500020]; int mArray[500020]; int mCount[500020] = { 0 }; int nCount[20000010] = { 0 }; void findBinarySearch(int i); int main() { cin >> N; //scanf("%d", &N); for (int i = 0; i < N; i++) { cin >> nArray[i]; if (nArray[i] >= 0) { nCount[nArray[i]]++; } else { nCount[(nArray[i]*-1)+10000000]++; } //scanf("%d", &nArray[i]); } cin >> M; //scanf("%d", &M); for (int i = 0; i < M; i++) { cin >> mArray[i]; //scanf("%d", &mArray[i]); } sort(nArray, nArray + N); for (int i = 0; i < M; i++) { findBinarySearch(i); } for (int i = 0; i < M; i++) { if (mArray[i] >= 0) { cout << nCount[mArray[i]]<< " "; } else { cout << nCount[(mArray[i] * -1) + 10000000]<< " "; } //printf("%d ",mCount[i]); } } void findBinarySearch(int i) { int start = 0; int end = N - 1; while (1) { if ((end - start) < 0) { break; } int temp = (end + start) / 2; if (nArray[temp] == mArray[i]) { break; } else if (nArray[temp] > mArray[i]) { end = temp - 1; } else { start = temp + 1; } } }
#include <iostream> #include <cstdio> using namespace std; struct Node { char ch; int priority; struct Node *child[26]; bool isWord; int childPriority; struct Node *next; }; void addToTrie(Node *root, string str, int priority) { int l = str.length(); struct Node *parent; for(int i=0; i<l; ++i) { int idx = str[i]-97; parent = root; if(root->child[idx] == NULL) { struct Node *tmp = (struct Node *)calloc(1, sizeof(Node)); tmp->ch = str[i]; root->child[idx] = tmp; } root = root->child[idx]; root->priority = max(root->priority, priority); if(parent->childPriority < priority) { parent->childPriority = priority; parent->next = root; } } root->isWord = true; } int queryRes(struct Node *root, string str) { int l = str.length(); for(int i=0; i<l; ++i) { int idx = str[i]-97; if(root->child[idx] == NULL) return -1; root = root->child[idx]; } if(root->isWord) return root->priority; return root->childPriority; } int main() { int n,q; cin >> n >> q; struct Node *root = (struct Node *)calloc(1, sizeof(struct Node)); string str; int priority; while(n--) { cin>>str; cin>>priority; addToTrie(root, str, priority); } while(q--) { cin >> str; cout << queryRes(root, str) << endl; } return 0; }
#pragma once #include "creature.h" class RandomWalker : public Creature { public: RandomWalker(void); ~RandomWalker(void); void step(); private: int counter; };
#include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> #endif #define LED_PIN 6 #define LED_COUNT 8 Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800); void setup() { // put your setup code here, to run once: strip.begin(); strip.show(); strip.setBrightness(25); randomSeed(analogRead(0)); } void loop() { // put your main code here, to run repeatedly: randomColor(50); } void randomColor(int speed){ // have the first pixel go from 0 to 25 brightness of a // random color, do 2 quick blinks before moving to the next // pixel. Once this gets to the last pixel, slowley 0 to 25 // brightness of all the pixels with their prevously assigned // random colors. each color will need 3 numbers from 0 to 255 // inclsive. int randoPixel = random(0, 8); int randoRed = random(0, 256); int randoGreen = random(0, 256); int randoBlue = random(0, 256); for (int i = 0; i <= LED_COUNT; i++){ strip.setPixelColor(i, 0, 0, 0); } int maxBrightness = 25; for (int i = 0; i <= maxBrightness; i++){ strip.setBrightness(i); strip.setPixelColor(randoPixel, randoRed, randoGreen, randoBlue); strip.show(); delay(speed); } for (int i = maxBrightness; i >= 0; i--){ strip.setBrightness(i); strip.setPixelColor(randoPixel, randoRed, randoGreen, randoBlue); strip.show(); delay(speed); } delay(10); }
#include <iostream> #include <algorithm> using namespace std; int main(){ int a{}, b{}; int len1{}, len2{}; while(cin >> a >> b && !(a == -1 && b == -1)){ len1 = a - b; len1 = (len1 < 0) ? len1 + 100 : len1; len2 = b - a; len2 = (len2 < 0) ? len2 + 100 : len2; cout << min(len1, len2) << endl; } return 0; }
#ifndef SERVER_CHATMANAGER_H #define SERVER_CHATMANAGER_H #include "BaseManager.h" #include <boost/property_tree/ptree.hpp> #include "src/server/lib/Connection/BaseConnection.h" class ChatManager: public BaseManager { public: ~ChatManager() override = default; boost::property_tree::ptree sendMessage(boost::property_tree::ptree &params); boost::property_tree::ptree deleteChat(boost::property_tree::ptree &params); boost::property_tree::ptree createChat(boost::property_tree::ptree &params); boost::property_tree::ptree getChatMessages(boost::property_tree::ptree &params); boost::property_tree::ptree getChatLastMessage(boost::property_tree::ptree &params); }; #endif //SERVER_CHATMANAGER_H
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { int l, r, lmod, rmod, ldiv, rdiv; cin >> l >> r; lmod = l % 2019; rmod = r % 2019; ldiv = l / 2019; rdiv = r / 2019; int ans = 2019; if (lmod < rmod && ldiv == rdiv){ for (int i = lmod; i < rmod + 1; i++) { for (int j = i + 1; j < rmod + 1; j++) { ans = min(ans, (i * j) % 2019); } } } else { ans = 0; } cout << ans << endl; }
#include <stdlib.h> #include <string.h> #include <map> #include "GameCmd.h" #include "PlayerManager.h" #include "Logger.h" #include "Configure.h" #include "HallHandler.h" #include "CoinConf.h" #include "NamePool.h" #include "Util.h" #include "Protocol.h" using namespace std; static PlayerManager* instance = NULL; PlayerManager* PlayerManager::getInstance() { if(instance==NULL) { instance = new PlayerManager(); } return instance; } PlayerManager::PlayerManager() { addbetrobot = false; int startUid = RobotUtil::getRobotStartUid(E_BULLFIGHT_GAME_ID, Configure::getInstance()->m_nLevel, Configure::getInstance()->m_nRobotIndex); LOGGER(E_LOG_INFO) << "Robot Start uid=" << startUid; for (int i = 0; i < MAX_ROBOT_NUMBER; ++i) { m_idpool[i].uid = startUid + i; m_idpool[i].hasused = false; } this->StartTimer(1000*60); CoinConf::getInstance()->getCoinCfg(&cfg); ResetBetArray(); } int PlayerManager::init() { return 0; } int PlayerManager::addPlayer(int uid, Player* player) { playerMap[uid] = player; return 0; } int PlayerManager::getPlayerSize() { return playerMap.size(); } void PlayerManager::calculateAreaBetLimit(int bankeruid) { Player* banker = getPlayer(bankeruid); if (banker != NULL) { static const int FACTOR = 40; int64_t areaLimit = banker->money / FACTOR; for (int i = 1; i < BETNUM; i++) { int rate = Util::rand_range(30, 50); areaTotalBetLimit[i] = areaLimit * rate / 100; } } } void PlayerManager::updateAreaBetLimit(int64_t bankermoney, int bettype, int rate) { static const int FACTOR = 40; int64_t areaLimit = bankermoney / FACTOR; if (rate == 0) { rate = Util::rand_range(30, 50); } areaTotalBetLimit[bettype] = areaLimit * rate / 100; } void PlayerManager::ResetBetArray() { memset(areaTotalBetLimit, 0, sizeof(areaTotalBetLimit)); memset(areaTotalBetArray, 0, sizeof(areaTotalBetArray)); } bool PlayerManager::CheckAreaBetLimit(int bettype, int64_t betcoin) { assert(bettype < BETNUM); if (bettype >= BETNUM) { return false; } int64_t limit = areaTotalBetLimit[bettype]; int64_t curr_total = areaTotalBetArray[bettype]; return curr_total + betcoin <= limit; } int PlayerManager::SavePlayerBetRecord(int uid, int bettype, int64_t betmoney, int pc) { int rate = 0; BetArea a; a.betmoney = betmoney; a.bettype = bettype; a.continuePlayCount = pc; auto rec = playerBetRecord.find(uid); if (rec == playerBetRecord.end()) { if (pc == 0 || betmoney == 0) { return 0; } std::deque<BetArea> ba; ba.push_back(a); playerBetRecord[uid] = ba; } else { auto& ba = rec->second; if (pc == 0 || betmoney == 0) { ba.clear(); return 0; } ba.push_back(a); if (ba.size() > 5) //最多保存5个 { ba.pop_front(); } //条件1 int rate1 = 0; if (pc == 1 && betmoney > 50000) { rate1 = 50; } if (pc == 2 && betmoney > 50000) { rate1 = 60; } if (pc >= 3 && betmoney > 50000) { rate1 = 70; } //条件2 int rate2 = 0; if (ba.size() > 1 && ba[0].betmoney > 20000) { std::vector<int64_t> progression; for (size_t i = 1; i < ba.size(); i++) { progression.push_back(ba[i].betmoney - ba[i - 1].betmoney); } if (progression.size() == 1) { if (progression[0] > 10000) { rate2 = 50; } } else { bool increase = true; for (size_t i = 1; i < progression.size(); i++) { if (progression[i] <= progression[i - 1]) { increase = false; break; } } if (increase && progression[0] > 10000) { if (progression.size() == 3) { rate2 = 60; } if (progression.size() >= 4) { rate2 = 70; } } } } if (rate2 > rate1) { rate = rate2; } else { rate = rate1; } } return rate; } void PlayerManager::ClearBetRecord() { playerBetRecord.clear(); } void PlayerManager::delPlayer(int uid,bool isOnclose) { Player* player = getPlayer(uid); if(player) { if(isOnclose) player->handler = NULL; LOGGER(E_LOG_INFO)<<"Robot Exit uid["<<player->id<<"] playersize["<<playerMap.size()<<"]"; delRobotUid(player->id); if(player->handler) delete player->handler; NamePool::getInstance()->FreeName(player->name); delete player; playerMap.erase(uid); } } Player* PlayerManager::getPlayer(int uid) { map<int , Player*>::iterator it = playerMap.find(uid); if(it == playerMap.end()) return NULL; else return it->second; } int PlayerManager::getRobotUid() { for (int i = 0; i < MAX_ROBOT_NUMBER; ++i) { if (!m_idpool[i].hasused) { m_idpool[i].hasused = true; return m_idpool[i].uid; } } return -1; } int PlayerManager::delRobotUid(int robotuid) { for (int i = 0; i < MAX_ROBOT_NUMBER; ++i) { if (m_idpool[i].uid == robotuid) { m_idpool[i].hasused = false; return 0; } } return 0; } int PlayerManager::ProcessOnTimerOut() { this->StartTimer(1000 * 60); LOGGER(E_LOG_INFO)<<"Check EveryActive Player, current Count player count=["<<playerMap.size()<<"]"; CoinConf::getInstance()->getCoinCfg(&cfg); return 0; }
// // main.cpp // firstxodeproject.cpp // // Created by Wallace Obey on 2/6/16. // Copyright © 2016 Wallace Obey. All rights reserved. // #include <iostream> #include <cstdlib> #include <cstring> using namespace std; void reverseString(char word[], int length); // Prototype reverse function int main(){ char userString[4]; int length = strlen(userString); // int length is equal to the length on the string (4) cout <<" Enter a word that has four letters " << "\n"; cin >> userString; // user enters a word reverseString(userString, 4); //runs reverse string function return 0; } void reverseString(char word[], int length) { char *headP = &word[0]; // head pointer is pointing to first letter char *tailP = &word[length-1]; // tail pointer points to last letter. -1 because of null character char userString[4]; cout << word << endl; // displays the word char temp; // creats temporary variable while(headP < tailP){ //switch pointers until word is completley flipped temp = *tailP; *tailP = *headP; *headP = temp; headP++; // increments head pointer tailP--; // decrements tail pointer } cout << word << endl; // displayes reversed string }
pair<int,int> ex_gcd(int a, int b){ if(a%b==0) return make_pair(0,1); pair<int, int> prev = ex_gcd(b, a%b); return make_pair(prev.second, prev.first + prev.second * (a/b) ) ; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/forms/formvaluelist.h" #include "modules/forms/formsenum.h" // FORMS_ATTR_OPTION_SELECTED #include "modules/logdoc/htm_elm.h" // HTML_Element #include "modules/forms/piforms.h" // SelectionObject #include "modules/layout/box/box.h" // SelectionObject #include "modules/layout/content/content.h" // SelectContent /* virtual */ FormValue* FormValueList::Clone(HTML_Element *he) { FormValueList* clone = OP_NEW(FormValueList, ()); if (clone) { clone->m_listbox_scroll_pos = m_listbox_scroll_pos; #ifdef CACHE_SELECTED_FIELD clone->m_selected_index = -1; clone->m_selected_option = NULL; #endif // CACHE_SELECTED_FIELD OP_ASSERT(!clone->IsValueExternally()); } return clone; } /** * Helper class, iterating over only the HE_OPTIONS (and HE_OPTGROUPS) that are included in * a select's option list. */ class OptionIterator { HTML_Element* m_stop; HTML_Element* m_current; BOOL m_include_optgroups; public: OptionIterator(HTML_Element* select, BOOL include_optgroups = FALSE) : m_current(select), m_include_optgroups(include_optgroups) { OP_ASSERT(select); OP_ASSERT(select->IsMatchingType(HE_SELECT, NS_HTML)); m_stop = static_cast<HTML_Element*>(select->NextSibling()); } HTML_Element* GetNext() { OP_ASSERT(m_current); OP_ASSERT(m_current->IsMatchingType(HE_SELECT, NS_HTML) || m_current->IsMatchingType(HE_OPTION, NS_HTML) || m_current->IsMatchingType(HE_OPTGROUP, NS_HTML)); if (m_current->IsMatchingType(HE_SELECT, NS_HTML)) { // First call. if (!m_current->FirstChild()) { m_current = NULL; return NULL; } m_current = m_current->FirstChild(); if (m_current->IsMatchingType(HE_OPTION, NS_HTML) || m_include_optgroups && m_current->IsMatchingType(HE_OPTGROUP, NS_HTML)) { return m_current; } } do { if (m_current->IsMatchingType(HE_OPTGROUP, NS_HTML)) { m_current = static_cast<HTML_Element*>(m_current->Next()); } else { m_current = static_cast<HTML_Element*>(m_current->NextSibling()); } } while (m_current != m_stop && !m_current->IsMatchingType(HE_OPTION, NS_HTML) && !(m_include_optgroups && m_current->IsMatchingType(HE_OPTGROUP, NS_HTML))); if (m_current == m_stop) { m_current = NULL; } return m_current; } void JumpTo(HTML_Element* option) { OP_ASSERT(option); OP_ASSERT(option->IsMatchingType(HE_OPTION, NS_HTML)); m_current = option; } }; void FormValueList::SyncWithFormObject(HTML_Element* he) { OP_ASSERT(he->Type() == HE_SELECT); // Not HE_KEYGEN FormObject* form_object = he->GetFormObject(); OP_ASSERT(form_object); // Who triggered this (ONCHANGE) if there was no FormObject??? SelectionObject* sel = static_cast<SelectionObject*>(form_object); int sel_count = sel->GetElementCount(); OP_ASSERT(sel_count >= 0); unsigned int count = static_cast<unsigned int>(sel_count); #ifdef CACHE_SELECTED_FIELD BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(he, is_multiple_select, is_dropdown); #endif // CACHE_SELECTED_FIELD OptionIterator iterator(he); unsigned int current_index = 0; int last_selected = -1; #ifdef CACHE_SELECTED_FIELD int first_selected = -1; HTML_Element* first_selected_option = NULL; HTML_Element* last_selected_option = NULL; #endif // CACHE_SELECTED_FIELD while (HTML_Element* opt_he = iterator.GetNext()) { // If there are more HE_OPTION:s than elements in the SelectionObject, we set the // rest to be not selected #ifdef CACHE_SELECTED_FIELD if (current_index >= count) { SetOptionSelected(opt_he, FALSE); } else { BOOL selected = sel->IsSelected(current_index); if (selected && first_selected < 0) { first_selected = current_index; first_selected_option = opt_he; } if (selected) { last_selected = current_index; last_selected_option = opt_he; } SetOptionSelected(opt_he, selected); } #else BOOL option_selected = current_index < count && sel->IsSelected(current_index); if (option_selected) { last_selected = current_index; } SetOptionSelected(opt_he, option_selected); #endif // CACHE_SELECTED_FIELD current_index++; } #ifdef CACHE_SELECTED_FIELD if (is_multiple_select) { m_selected_index = first_selected; m_selected_option = first_selected_option; } else { m_selected_index = last_selected; m_selected_option = last_selected_option; } #endif // CACHE_SELECTED_FIELD unsigned char &is_not_selected = GetIsExplicitNotSelected(); if (last_selected >= 0 && is_not_selected) { is_not_selected = FALSE; } // If this fires the FormObject didn't match the HTML tree. // Maybe something changed the tree and we failed to update the widget? OP_ASSERT(count == current_index); } BOOL FormValueList::IsSelected(HTML_Element* he, unsigned int looked_at_index) const { OP_ASSERT(he->GetFormValue() == const_cast<FormValueList*>(this)); BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(he, is_multiple_select, is_dropdown); #ifdef CACHE_SELECTED_FIELD // If for cached selection _or_ there is another one for dropdowns, go with it. Otherwise, fall through to scanning. if (m_selected_index == looked_at_index || (is_dropdown && m_selected_index >= 0)) { return (m_selected_index == looked_at_index); } #endif // CACHE_SELECTED_FIELD OptionIterator iterator(he); unsigned int current_index = 0; while (HTML_Element* option_he = iterator.GetNext()) { if (current_index == looked_at_index) { if (IsThisOptionSelected(option_he)) { return TRUE; } // Not selected, but can option at matching index be defaulted as the selected option? // Definitely not iff: // - a multi-selection. // - index > 0 for a dropdown // - we know that we aren't selected. if (!is_dropdown || looked_at_index > 0 || GetIsExplicitNotSelected()) { return FALSE; } } if (looked_at_index == 0) { // This is selected -> The first option cannot be automatically selected if (IsThisOptionSelected(option_he)) { return FALSE; } } current_index++; } if (current_index > looked_at_index) { OP_ASSERT(is_dropdown); OP_ASSERT(looked_at_index == 0); // We looked for a later selection but didn't find one -> The first must be selected automatically return TRUE; } // The index was too large return FALSE; // OpStatus::ERR? } #ifdef WAND_SUPPORT BOOL FormValueList::IsListChangedFromOriginal(HTML_Element* he) const { OptionIterator iterator(he); while (HTML_Element* he_opt = iterator.GetNext()) { BOOL selected_in_html = he_opt->GetSelected(); BOOL selected_for_user = IsThisOptionSelected(he_opt); if (selected_in_html != selected_for_user) { return TRUE; } } return FALSE; } #endif // WAND_SUPPORT static SelectContent* GetSelectContent(HTML_Element* select) { Box* sel_box = select->GetLayoutBox(); Content* content = sel_box ? sel_box->GetContent() : NULL; SelectContent* sel_content = content ? content->GetSelectContent() : NULL; if (!sel_content) { // Not a real select in the layout - generated content? Since we // need the "real" SelectContent we have to find the element it's stored at. // As soon as we skip past the layout engine when updating the widget all this // can be removed. HTML_Element* child = select->FirstChild(); while (child && !sel_content) { if (child->GetInserted() == HE_INSERTED_BY_LAYOUT && child->Type() == select->Type()) { sel_content = GetSelectContent(child); } child = child->Suc(); } } return sel_content; } /* private */ void FormValueList::EmptyWidget(HTML_Element* he) { OP_ASSERT(IsValueExternally()); SelectContent* sel_content = GetSelectContent(he); if (!sel_content) { // Not a real select in the layout return; } SelectionObject* sel_obj = static_cast<SelectionObject*>(he->GetFormObject()); sel_content->RemoveOptions(); int options_count = sel_obj->GetFullElementCount(); OP_ASSERT(options_count >= 0); if (options_count > 0) { // If we end up here, we probably have thrown away the old SelectContent // and need to remove the elements from SelectionObject here instead sel_obj->RemoveAll(); } OP_ASSERT(sel_obj->GetElementCount() == 0); OP_ASSERT(sel_obj->GetFullElementCount() == 0); } void FormValueList::HandleOptionListChanged(FramesDocument* frames_doc, HTML_Element* select_he, HTML_Element* option_he, BOOL added) { if (IsValueExternally()) // else it will be fixed when we are externalized { BOOL need_full_rebuild = FALSE; if (option_he->Type() == HE_OPTION) { // These are not handled by the layout engine: // - inserting first into an optgroup or // - inserting right before an optgroup. // (ignoring text nodes in both cases.) if (added) { HTML_Element *pred = option_he->PredActual(); while (pred && pred->IsText()) { pred = pred->PredActual(); } if (option_he->ParentActual() && option_he->ParentActual()->IsMatchingType(HE_OPTGROUP, NS_HTML)) { HTML_Element *iter = NULL; if (pred) { iter = option_he->ParentActual()->SucActual(); while (iter && iter->IsText()) { iter = iter->SucActual(); } } if (!pred || iter && iter->IsMatchingType(HE_OPTGROUP, NS_HTML)) { need_full_rebuild = TRUE; } } else if (HTML_Element *iter = option_he->SucActual()) { while (iter && iter->IsText()) { iter = iter->SucActual(); } if (iter && iter->IsMatchingType(HE_OPTGROUP, NS_HTML)) { need_full_rebuild = TRUE; } } } } else { OP_ASSERT(option_he->Type() == HE_OPTGROUP); if (added) { need_full_rebuild = TRUE; } else { // This is somehow handled by the layout engine yet } } if (need_full_rebuild) { OP_ASSERT(select_he->GetFormObject()); // Otherwise we're not external // Rebuild the widget from the beginning. Yes, this sucks. select_he->RemoveLayoutBox(frames_doc, TRUE); select_he->MarkExtraDirty(frames_doc); } } HTML_Element *selected_option = NULL; unsigned int selected_index = 0; BOOL has_selection = FALSE; #ifdef CACHE_SELECTED_FIELD has_selection = m_selected_index >= 0; selected_index = m_selected_index; selected_option = m_selected_option; #endif // CACHE_SELECTED_FIELD has_selection = has_selection || OpStatus::IsSuccess(GetIndexAndElementOfFirstSelected(select_he, selected_option, selected_index, TRUE)); /* Adjust the selection as add/remove had an impact on the selected index * (e.g. if selected element was removed a default one should be selected, * or if selected option was added to a single selection <select> - make sure it's the only one selected) */ if (!has_selection || IsThisOptionSelected(option_he)) { if (!select_he->GetBoolAttr(ATTR_MULTIPLE)) { SetInitialSelection(select_he, FALSE); } } // If we added/removed an element before the current selection, adjust selected index. else if (has_selection) { int index = static_cast<int>(selected_index); HTML_Element *iter = selected_option; // Avoid doing a full linear scan by approximating: if near the start, see if before. if (index <= 6) { while (iter && index-- >= 0) { if (option_he == iter) { // Before; adjust selected index (and cached info, if any.) OpStatus::Ignore(SetInitialSelection(select_he, FALSE)); return; } iter = iter->Pred(); } // Known not to occur before current selection; update unnecessary. } else { // Look beyond current selection..a bit; if found, selection and index is still valid. Otherwise, assume it occurred before. index = 6; while (iter && index-- >= 0) { if (option_he == iter) { return; } iter = iter->Suc(); } OpStatus::Ignore(SetInitialSelection(select_he, FALSE)); } } } void FormValueList::LockUpdate(HTML_Element* helm, BOOL is_externalizing, BOOL lock) { m_update_locked = lock; if (!m_update_locked) { if (m_update_attempt_when_locked) UpdateWidget(helm, is_externalizing); m_update_attempt_when_locked = FALSE; } } /* private */ BOOL FormValueList::UpdateWidget(HTML_Element* he, BOOL is_externalizing) { if (m_update_locked) { m_update_attempt_when_locked = TRUE; return FALSE; } OP_ASSERT(he->Type() == HE_SELECT); SelectionObject *sel = (SelectionObject*)he->GetFormObject(); OP_ASSERT(sel); // Otherwise we're not external SelectContent* sel_content = GetSelectContent(he); if (!sel_content) { // Not a real select return FALSE; } BOOL was_impossible; // First try an simple fast sync BOOL changes_done = SynchronizeWidgetWithTree(he, sel, sel_content, is_externalizing, was_impossible); if (was_impossible) { m_rebuild_needed = TRUE; sel->ScheduleFormValueRebuild(); } return changes_done; } void FormValueList::Rebuild(HTML_Element* he, BOOL is_externalizing) { if (!m_rebuild_needed || !IsValueExternally()) return; m_rebuild_needed = FALSE; OP_ASSERT(he->Type() == HE_SELECT); SelectionObject *sel = static_cast<SelectionObject*>(he->GetFormObject()); SelectContent* sel_content = GetSelectContent(he); if (!sel_content) { // Not a real select return; } sel->LockWidgetUpdate(TRUE); // Rebuild the widget from the beginning. Yes, this sucks. EmptyWidget(he); #ifdef _DEBUG OP_ASSERT(sel->GetElementCount() == 0); OP_ASSERT(sel->GetFullElementCount() == 0); #endif // _DEBUG BOOL was_impossible; SynchronizeWidgetWithTree(he, sel, sel_content, is_externalizing, was_impossible); OP_ASSERT(!was_impossible || !"Still out of sync. Caused by a bug or OOM"); sel->LockWidgetUpdate(FALSE); sel->UpdateWidget(); if (!is_externalizing) { // Since we had to redo the whole widget, we must also ensure that we layout every option // This must not be done if we're inside the layout engine already (thus the check for // is_externalizing). See bug 273923. HTML_Element* stop_marker = static_cast<HTML_Element*>(he->NextSibling()); HTML_Element* opt_he = static_cast<HTML_Element*>(he->Next()); while (opt_he != stop_marker) { opt_he->MarkExtraDirty(sel->GetDocument()); opt_he = opt_he->Next(); } } } /* private */ BOOL FormValueList::SynchronizeWidgetWithTree(HTML_Element* he, SelectionObject* sel, SelectContent* sel_content, BOOL is_externalizing, BOOL& out_was_impossible) { OP_ASSERT(IsValueExternally()); out_was_impossible = FALSE; // Do we know a better way than looping over the options // and update the widget one by one? unsigned int widget_option_count; unsigned int widget_element_count; // Includes optgroup starts and ends { int count = sel->GetElementCount(); OP_ASSERT(count >= 0); widget_option_count = static_cast<unsigned int>(count); widget_element_count = sel->GetFullElementCount(); } OP_ASSERT(he->Type() == HE_SELECT); BOOL need_full_rebuild = FALSE; BOOL changed_widget_structure = FALSE; unsigned int current_option_index = 0; unsigned int current_element_index = 0; // includes optgroup starts and ends unsigned int selected_count = 0; int first_enabled_option = -1; OptionIterator iterator(he, TRUE); // TRUE = Include HE_OPTGROUP OpVector<HTML_Element> opt_groups; while (HTML_Element* opt_he = iterator.GetNext()) { // Close any optgroups we have left while (opt_groups.GetCount() > 0) { HTML_Element* innermost_opt_group = opt_groups.Get(opt_groups.GetCount() - 1); if (innermost_opt_group->IsAncestorOf(opt_he)) { // We are still inside the optgroup break; } BOOL need_to_insert_optgroup_stop = current_element_index >= widget_element_count || !sel->ElementAtRealIndexIsOptGroupStop(current_element_index); if (need_to_insert_optgroup_stop) { if (current_element_index < widget_element_count) { // Can only insert groups at the end of the widget need_full_rebuild = TRUE; break; } changed_widget_structure = TRUE; #if 0 sel->EndGroup(); #else // Need to talk through layout right now or it will get confused sel_content->EndOptionGroup(opt_he); #endif // 0 widget_element_count++; } current_element_index++; opt_groups.Remove(opt_groups.GetCount() - 1); } if (opt_he->Type() == HE_OPTGROUP) { // Entering a optgroup if (OpStatus::IsSuccess(opt_groups.Add(opt_he))) { BOOL need_to_insert_optgroup_start = current_element_index >= widget_element_count || !sel->ElementAtRealIndexIsOptGroupStart(current_element_index); if (need_to_insert_optgroup_start) { if (current_element_index < widget_element_count) { // Can only insert groups at the end of the widget need_full_rebuild = TRUE; break; } changed_widget_structure = TRUE; #if 0 sel->BeginGroup(opt_he); #else // Need to talk through layout right now or it will get confused sel_content->BeginOptionGroup(opt_he); #endif // 0 widget_element_count++; } } // else (OOM) we will miss the optgroup. Not too serious effect of the oom. current_element_index++; } else { OP_ASSERT(opt_he->IsMatchingType(HE_OPTION, NS_HTML)); BOOL selected = IsThisOptionSelected(opt_he); if (selected) { selected_count++; } if (current_option_index < widget_option_count) { if (sel->IsSelected(current_option_index) != selected) { sel->SetElement(current_option_index, selected); } } else { // This option is not added to the listbox yet. Normally // done by the layout engine, but then we do it here instead. // Hopefully the actual string will be set by the layout engine when the // options is processed there. It should be since it's always been that // way. changed_widget_structure = TRUE; // Need to add through the layout box since it has own // datastructures and would get confused if we bypassed it. // (see bug 217347) unsigned index; if (OpStatus::IsError(sel_content->AddOption(opt_he, index))) { // OOM or other error (exhausted capacity to hold more options); // empty and rebuild. need_full_rebuild = TRUE; break; } widget_option_count++; widget_element_count++; if (static_cast<unsigned>(sel->GetElementCount()) != widget_option_count) { // the new option wasn't inserted, probably because // it had already been used at a different position earlier or // that the widget was locked (should the lock be // removed now with FormValueList?) // So now we have to do a full rebuild. need_full_rebuild = TRUE; break; } } if (first_enabled_option == -1 && !opt_he->GetDisabled()) { first_enabled_option = current_option_index; } // Verify option text? A change to the text should cause a reflow which should solve // all unsyncness current_option_index++; current_element_index++; } } if (need_full_rebuild) { out_was_impossible = TRUE; return TRUE; } // Remove options in the widget that are not in the tree while (current_option_index < widget_option_count) { sel->RemoveElement(--widget_option_count); } // If it's a dropdown and nothing else was selected, // then the first enabled value is // automatically selected if (GetIsExplicitNotSelected()) { // Setting the option "-1" will make the widget understand that it // is completely unselected as well. Otherwise it will during // history walks reset itself to "first option". sel->SetElement(-1, TRUE); } else if (selected_count == 0 && widget_option_count > 0 && first_enabled_option != -1) { BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(he, is_multiple_select, is_dropdown); if (is_dropdown) { if (he->GetEndTagFound()) { // Must have a real selection SelectValueInternal(he, first_enabled_option, TRUE, is_externalizing); } sel->SetElement(first_enabled_option, TRUE); } } sel->ScrollIfNeeded(); return changed_widget_structure; } BOOL FormValueList::IsSelectedElement(HTML_Element* he, HTML_Element* option_elm) const { OP_ASSERT(he->GetFormValue() == const_cast<FormValueList*>(this)); OP_ASSERT(he->IsAncestorOf(option_elm)); #ifdef CACHE_SELECTED_FIELD if (option_elm == m_selected_option) return TRUE; #endif // CACHE_SELECTED_FIELD BOOL selected = IsThisOptionSelected(option_elm); BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(he, is_multiple_select, is_dropdown); // If it's a dropdown and nothing else is selected, we select the first so // we must see if we're selected in that way. if (!selected && is_dropdown && !option_elm->GetDisabled()) { #ifdef CACHE_SELECTED_FIELD // element not selected, but another is known to be. if (m_selected_index >= 0) return FALSE; #endif // CACHE_SELECTED_FIELD // Look if we're first HTML_Element* earlier_he = static_cast<HTML_Element*>(option_elm->Prev()); while (earlier_he != he) // We must pass the select on our way backwards { if (earlier_he->IsMatchingType(HE_OPTION, NS_HTML)) { HTML_Element* parent = earlier_he->Parent(); while (parent != he && parent->IsMatchingType(HE_OPTGROUP, NS_HTML)) { parent = parent->Parent(); } if (parent == he) { // We weren't the first option -> Not selected return FALSE; } } earlier_he = static_cast<HTML_Element*>(earlier_he->Prev()); } // We were the first OPTION. See if any other is selected. OptionIterator iterator(he); iterator.JumpTo(option_elm); while (HTML_Element* later_he = iterator.GetNext()) { if (IsThisOptionSelected(later_he)) { // Later selected -> We're not selected return FALSE; } } // Found no later selected, and we're the first option in a dropdown // so we must be automatically selected selected = TRUE; } return selected; } /* virtual */ OP_STATUS FormValueList::ResetToDefault(HTML_Element* he) { OP_ASSERT(he->GetFormValue() == this); ResetChangedFromOriginal(); return SetInitialSelection(he, TRUE); } OP_STATUS FormValueList::SetInitialSelection(HTML_Element* he, BOOL use_selected_attribute) { OP_ASSERT(he->GetFormValue() == this); // OP_ASSERT(he->GetEndTagFound()); // This is called right before the flag is set BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(he, is_multiple_select, is_dropdown); BOOL must_have_single_selection = is_dropdown; // If we have to fallback on something ourself, we will use options in this order: // 1. first_enabled_option HTML_Element* first_enabled_option = NULL; unsigned int selection_count = 0; #ifdef CACHE_SELECTED_FIELD int option_count = 0; int first_selected_index = -1; #endif OptionIterator iterator(he); HTML_Element* last_selected_option = NULL; // Used to handle multiple ATTR_SELECTED while (HTML_Element* he_opt = iterator.GetNext()) { BOOL option_disabled = he_opt->GetDisabled(); // We don't care about inherited disabling here. if (!first_enabled_option && !option_disabled) { first_enabled_option = he_opt; #ifdef CACHE_SELECTED_FIELD first_selected_index = option_count; #endif // CACHE_SELECTED_FIELD } BOOL select_option; if (use_selected_attribute) { // Only look at the selected attribute select_option = he_opt->GetSelected(); } else { select_option = IsThisOptionSelected(he_opt); } if (select_option) { selection_count++; GetIsExplicitNotSelected() = FALSE; } SetOptionSelected(he_opt, select_option); if (select_option && !is_multiple_select) { if (last_selected_option) { // Only the last of the elements marked with // ATTR_SELECTED should be select SetOptionSelected(last_selected_option, FALSE); } last_selected_option = he_opt; #ifdef CACHE_SELECTED_FIELD m_selected_index = option_count; m_selected_option = he_opt; } option_count++; #else } #endif // CACHE_SELECTED_FIELD } // Fallback to a calculated selection if (selection_count == 0 && must_have_single_selection) { if (first_enabled_option) { GetIsExplicitNotSelected() = FALSE; SetOptionSelected(first_enabled_option, TRUE); } #ifdef CACHE_SELECTED_FIELD m_selected_index = first_selected_index; m_selected_option = first_enabled_option; } else if (selection_count == 0) { // If the sole selection in a multi-select was removed, drop its cached selection. m_selected_index = -1; m_selected_option = NULL; } #else } #endif // CACHE_SELECTED_FIELD if (IsValueExternally()) { // The widget needs to update too BOOL changed_structure = UpdateWidget(he, FALSE); if (changed_structure) { // Need to layout the options (color, text...) he->MarkDirty(he->GetFormObject()->GetDocument()); } } return OpStatus::OK; } OP_STATUS FormValueList::SelectValueInternal(HTML_Element* he, unsigned int index, BOOL select, BOOL is_externalizing) { OP_ASSERT(he->GetFormValue() == this); // Can we improve? A linear scan to count them followed by the same below. if (index >= GetOptionCount(he)) { OP_ASSERT(FALSE); // XXX Count the options in advance! return OpStatus::ERR; } #ifdef CACHE_SELECTED_FIELD HTML_Element* selected_element = NULL; #endif // CACHE_SELECTED_FIELD OptionIterator iterator(he); BOOL is_single_selection = !he->GetMultiple(); unsigned int option_number = 0; while (HTML_Element* he_opt = iterator.GetNext()) { if (select && is_single_selection || index == option_number) { BOOL select_option = (index == option_number) && select; SetOptionSelected(he_opt, select_option); #ifdef CACHE_SELECTED_FIELD if (index == option_number) selected_element = he_opt; #endif // CACHE_SELECTED_FIELD } option_number++; } #ifdef CACHE_SELECTED_FIELD // Can we improve caching? Default to first-enabled on the fly or get at the selection set for multi-select. if (!select) { m_selected_index = -1; m_selected_option = NULL; } else { m_selected_index = index; m_selected_option = selected_element; } #endif // CACHE_SELECTED_FIELD GetIsExplicitNotSelected() = FALSE; if (IsValueExternally() && !is_externalizing) { // The widget needs to update too UpdateWidget(he, FALSE); } return OpStatus::OK; } unsigned int FormValueList::GetOptionCount(HTML_Element* he) { OP_ASSERT(he->GetFormValue() == this); OP_ASSERT(he->Type() == HE_SELECT); return GetOptionIndexOrCount(he, NULL); // NULL -> Get Count } unsigned int FormValueList::GetOptionIndexOrCount(HTML_Element* he, HTML_Element* option_he) { // option_he == NULL -> Count unsigned int option_count = 0; OptionIterator iterator(he); while (HTML_Element* he_opt = iterator.GetNext()) { if (he_opt == option_he) { break; } option_count++; } return option_count; } /* static */ OP_STATUS FormValueList::ConstructFormValueList(HTML_Element* he, FormValue*& out_value) { OP_ASSERT(he->Type() == HE_SELECT); FormValueList* list_value = OP_NEW(FormValueList, ()); if (!list_value) { return OpStatus::ERR_NO_MEMORY; } // No children exists yet so this value's internals are built lazily. out_value = list_value; return OpStatus::OK; } OP_STATUS FormValueList::GetOptionValues(HTML_Element* he, OpVector<OpString>& selected_values, BOOL include_not_selected) { OP_ASSERT(he->GetFormValue() == this); OP_ASSERT(he->Type() == HE_SELECT); OptionIterator iterator(he); BOOL only_selected = !include_not_selected; BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(he, is_multiple_select, is_dropdown); BOOL must_have_one_selected = is_dropdown && !GetIsExplicitNotSelected(); HTML_Element* first_option = NULL; while (HTML_Element* he_opt = iterator.GetNext()) { if (must_have_one_selected && !first_option) { first_option = he_opt; } if (include_not_selected || (IsThisOptionSelected(he_opt) && !he_opt->GetDisabled())) { RETURN_IF_ERROR(AddOptionValueOrClear(selected_values, he_opt, he)); } } if (only_selected && must_have_one_selected && selected_values.GetCount() == 0 && first_option) { RETURN_IF_ERROR(AddOptionValueOrClear(selected_values, first_option, he)); } return OpStatus::OK; } /* static */ void FormValueList::IsMultipleOrDropdown(HTML_Element* he, BOOL& is_multiple, BOOL& is_dropdown) { OP_ASSERT(he->Type() == HE_SELECT); is_multiple = he->GetBoolAttr(ATTR_MULTIPLE); is_dropdown = !is_multiple && he->GetNumAttr(ATTR_SIZE) <= 1; } /* private static */ OP_STATUS FormValueList::AddOptionValueOrClear(OpVector<OpString>& selected_values, HTML_Element* he_opt, HTML_Element* he_sel) { TempBuffer buffer; const uni_char* opt_val = GetValueOfOption(he_opt, &buffer); if (!opt_val) { return OpStatus::ERR_NO_MEMORY; } // String will be owned by caller OpString* selected_value = OP_NEW(OpString, ()); if (!selected_value || OpStatus::IsError(selected_value->Set(opt_val))) { OP_DELETE(selected_value); selected_values.DeleteAll(); return OpStatus::ERR_NO_MEMORY; } selected_values.Add(selected_value); return OpStatus::OK; } BOOL FormValueList::HasSelectedValue(HTML_Element* he) { OP_ASSERT(he->GetFormValue() == this); unsigned int dummy_index; #ifdef CACHE_SELECTED_FIELD if (m_selected_index >= 0) { return TRUE; } #endif // CACHE_SELECTED_FIELD return GetIndexOfFirstSelected(he, dummy_index) == OpStatus::OK; } #ifdef _WML_SUPPORT_ HTML_Element* FormValueList::GetFirstSelectedOption(HTML_Element* he) { OP_ASSERT(he->GetFormValue() == this); HTML_Element* he_opt; unsigned int dummy_index; if (OpStatus::IsSuccess(GetIndexAndElementOfFirstSelected(he, he_opt, dummy_index, FALSE))) { OP_ASSERT(he_opt); return he_opt; } return NULL; } #endif // _WML_SUPPORT_ /* private */ OP_STATUS FormValueList::GetIndexAndElementOfFirstSelected(HTML_Element* sel_he, HTML_Element*& out_option, unsigned int& out_index, BOOL use_first_selected) { OP_ASSERT(sel_he->GetFormValue() == this); out_option = sel_he->FirstChild(); out_index = 0; HTML_Element* first_enabled_option = NULL; unsigned first_enabled_option_index = 0; HTML_Element* last_selected = NULL; unsigned int last_selected_index = 0; BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(sel_he, is_multiple_select, is_dropdown); OptionIterator iterator(sel_he); while (HTML_Element* it_option = iterator.GetNext()) { if (IsThisOptionSelected(it_option)) { if (use_first_selected || is_multiple_select) { // First selected return OpStatus::OK; } // This is selected, but if there are more than one selected, then // the last one is the one really selected. last_selected = it_option; last_selected_index = out_index; } if (!first_enabled_option && !it_option->GetDisabled()) { first_enabled_option = it_option; first_enabled_option_index = out_index; } out_index++; } if (last_selected) { out_option = last_selected; out_index = last_selected_index; return OpStatus::OK; } if (!GetIsExplicitNotSelected() && is_dropdown && first_enabled_option) { // If it's a dropdown and nothing else is selected // but it is non empty, we select the first out_index = first_enabled_option_index; out_option = first_enabled_option; return OpStatus::OK; } return OpStatus::ERR; // Nothing selected } /* static */ BOOL FormValueList::IsOptionSelected(HTML_Element* option) { BOOL has_option_selected_attr = option->HasSpecialAttr(FORMS_ATTR_OPTION_SELECTED, SpecialNs::NS_FORMS); return has_option_selected_attr ? option->GetSpecialBoolAttr(FORMS_ATTR_OPTION_SELECTED, SpecialNs::NS_FORMS) : option->GetBoolAttr(ATTR_SELECTED); } BOOL FormValueList::IsThisOptionSelected(HTML_Element* option) const { #ifdef CACHE_SELECTED_FIELD if (m_selected_option == option) { return TRUE; } else #endif // CACHE_SELECTED_FIELD { return IsOptionSelected(option); } } /* static */ const uni_char* FormValueList::GetValueOfOption(HTML_Element* he_opt, TempBuffer* buffer) { OP_ASSERT(he_opt && he_opt->IsMatchingType(HE_OPTION, NS_HTML)); OP_ASSERT(buffer && buffer->Length() == 0); const uni_char* opt_val = he_opt->GetValue(); if (!opt_val) { if (OpStatus::IsSuccess(he_opt->GetOptionText(buffer))) { opt_val = buffer->GetStorage(); OP_ASSERT(opt_val); } } return opt_val; } OP_STATUS FormValueList::UnselectAll(HTML_Element* he) { OP_ASSERT(he->GetFormValue() == this); OP_ASSERT(he->Type() == HE_SELECT); OptionIterator iterator(he); while (HTML_Element* he_opt = iterator.GetNext()) { SetOptionSelected(he_opt, FALSE); } GetIsExplicitNotSelected() = TRUE; #ifdef CACHE_SELECTED_FIELD m_selected_index = -1; m_selected_option = NULL; #endif // CACHE_SELECTED_FIELD if (IsValueExternally()) { // The widget needs to update too UpdateWidget(he, FALSE); } return OpStatus::OK; } OP_STATUS FormValueList::UpdateSelectedValue(HTML_Element* he, HTML_Element* he_opt) { BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(he, is_multiple_select, is_dropdown); if (is_multiple_select) { SetOptionSelected(he_opt, TRUE); return SetInitialSelection(he, FALSE); } else { unsigned index; HTML_Element* he_opt_selected; OP_STATUS status = GetIndexAndElementOfFirstSelected(he, he_opt_selected, index); if (OpStatus::IsMemoryError(status)) { return status; } else if (OpStatus::IsError(status)) { SetOptionSelected(he_opt, TRUE); return SetInitialSelection(he, FALSE); } else if (he_opt != he_opt_selected) { SetOptionSelected(he_opt_selected, FALSE); SetOptionSelected(he_opt, TRUE); } return OpStatus::OK; } } /* static */ void FormValueList::SetOptionSelected(HTML_Element* he_opt, BOOL selected) { // We save memory by not setting the attribute unless it's // already there or if it must be set to TRUE // Update: It was not possible to save that memory because if we don't mark things // explicitly we may when unsetting things default back to checked values instead // of getting nothing selected at all. // if (IsOptionSelected(he_opt) != selected) // { void* attr_val = reinterpret_cast<void*>(static_cast<INTPTR>(selected)); he_opt->SetSpecialAttr(FORMS_ATTR_OPTION_SELECTED, ITEM_TYPE_BOOL, attr_val, FALSE, SpecialNs::NS_FORMS); // } } #if defined(WAND_SUPPORT) || defined(_WML_SUPPORT_) OP_STATUS FormValueList::GetSelectedIndexes(HTML_Element* he, OpINT32Vector& selected_indexes) { OP_ASSERT(he->GetFormValue() == this); OP_ASSERT(he->Type() == HE_SELECT); BOOL is_multiple_select, is_dropdown; IsMultipleOrDropdown(he, is_multiple_select, is_dropdown); if (is_multiple_select) { HTML_Element* dummy; unsigned int selected_index; if (OpStatus::IsSuccess(GetIndexAndElementOfFirstSelected(he, dummy, selected_index, FALSE))) { return selected_indexes.Add(static_cast<INT32>(selected_index)); } return OpStatus::OK; } OptionIterator iterator(he); int option_index = 0; while (HTML_Element* he_opt = iterator.GetNext()) { if (IsOptionSelected(he_opt)) { selected_indexes.Add(option_index); } option_index++; } if (!GetIsExplicitNotSelected() && is_dropdown && selected_indexes.GetCount() == 0 && option_index > 0) { // First value is automatically selected selected_indexes.Add(0); } return OpStatus::OK; } #endif // defined(WAND_SUPPORT) || defined(_WML_SUPPORT_) /* virtual */ BOOL FormValueList::Externalize(FormObject* form_object_to_seed) { if (!FormValue::Externalize(form_object_to_seed)) { return FALSE; // It was wrong to call Externalize } OP_ASSERT(m_listbox_scroll_pos >= 0); SelectionObject* sel = static_cast<SelectionObject*>(form_object_to_seed); sel->SetWidgetScrollPosition(m_listbox_scroll_pos); if (m_rebuild_needed) Rebuild(form_object_to_seed->GetHTML_Element(), TRUE); else UpdateWidget(form_object_to_seed->GetHTML_Element(), TRUE); return TRUE; } /* virtual */ void FormValueList::Unexternalize(FormObject* form_object_to_replace) { if (IsValueExternally()) { m_listbox_scroll_pos = static_cast<SelectionObject*>(form_object_to_replace)->GetWidgetScrollPosition(); OP_ASSERT(m_listbox_scroll_pos >= 0); FormValue::Unexternalize(form_object_to_replace); } }
#include "cpptest.h" CPPTEST_CONTEXT("core.threads.test.cpptest.TA_Thread_CppTest/core.thread.test.cpptest/ThreadPool/ThreadPoolManager.cpp"); CPPTEST_TEST_SUITE_INCLUDED_TO("core.threads.test.cpptest.TA_Thread_CppTest/core.thread.test.cpptest/ThreadPool/ThreadPoolManager.cpp"); class TestSuite_run_4d52f4e9 : public CppTest_TestSuite { public: CPPTEST_TEST_SUITE(TestSuite_run_4d52f4e9); CPPTEST_TEST(test_run_1); CPPTEST_TEST_SUITE_END(); void setUp(); void tearDown(); void test_run_1(); }; CPPTEST_TEST_SUITE_REGISTRATION(TestSuite_run_4d52f4e9); void TestSuite_run_4d52f4e9::setUp() { FUNCTION_ENTRY( "setUp" ); FUNCTION_EXIT; } void TestSuite_run_4d52f4e9::tearDown() { FUNCTION_ENTRY( "tearDown" ); FUNCTION_EXIT; } /* CPPTEST_TEST_CASE_BEGIN test_run_1 */ /* CPPTEST_TEST_CASE_CONTEXT virtual void TA_Base_Core::ThreadPoolManager::run(void) */ void TestSuite_run_4d52f4e9::test_run_1() { FUNCTION_ENTRY( "test_run_1" ); ///* Pre-condition initialization */ ///* Initializing argument 0 (this) */ // /* Initializing constructor argument 1 (numThreads) */ // unsigned long _numThreads_0 = 130; // /* Initializing constructor argument 2 (upperLimit) */ // unsigned long _upperLimit_0 = 130; //::TA_Base_Core::ThreadPoolManager _cpptest_TestObject (_numThreads_0, _upperLimit_0); ///* Tested function call */ //_cpptest_TestObject.run(); ///* Post-condition check */ //CPPTEST_POST_CONDITION_UINTEGER("unsigned long _cpptest_TestObject.m_originalSize", ( _cpptest_TestObject.m_originalSize )); //CPPTEST_POST_CONDITION_UINTEGER("unsigned long _cpptest_TestObject.m_upperLimit", ( _cpptest_TestObject.m_upperLimit )); FUNCTION_EXIT; } /* CPPTEST_TEST_CASE_END test_run_1 */
#include<stdio.h> #include<conio.h> #include<stdlib.h> using namespace std; struct node { int data; struct node *next; }; void push(struct node **root,int a) { struct node *n = (struct node *)malloc(sizeof(struct node)); n->data = a; n->next = (*root); (*root) = n; } void printlist(struct node *root) { while(root!=NULL) { printf("%d\t",root->data); root = root->next; } } struct node *reverse(struct node *root,int m) { int count=0; struct node *prev = NULL; struct node *cur = root; struct node *next; while(cur!=NULL && count<m) { next = cur->next; cur->next = prev; prev = cur; cur= next; count++; } if(next!=NULL) root->next = reverse(next,m); return prev; } int main() { struct node *root = NULL; struct node *head; push(&root,3); push(&root,5); push(&root,6); push(&root,7); push(&root,9); push(&root,2); printlist(root); head = reverse(root,4); printf("\n"); printlist(head); getch(); }
#pragma once #include "stdafx.h" #include <QDialog> #include "ItemDAO.h" class NewTable : public QDialog { Q_OBJECT public: NewTable(QWidget* parent); ~NewTable(); public slots: void validatePressed(); signals: void transfertNewTable(QString name, QString password); private: QLabel* errorMessage; QLineEdit* containName; QLineEdit* containPassword; void ini(QGridLayout* layout); };
#include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int tc; cin >> tc; while (tc--) { int n, m, minCount = 0; int cSpeed = 0; cin >> n >> m; int dist = m - n; while (dist) { int maxDist = 0; int ts = cSpeed + 1; if(ts%2 == 0){ maxDist = (ts+1)*(ts/2); }else{ maxDist = (ts+1)*(ts/2) + (ts+1)/2; } if (dist >= maxDist) { dist -= ++cSpeed; minCount++; } else { maxDist -= (cSpeed+1); if(dist >= maxDist){ dist -= cSpeed; minCount++; }else{ dist -= --cSpeed; minCount++; } } } cout << minCount << '\n'; } return 0; }
#include <assert.h> #include <stdlib.h> #include <stdio.h> #if defined(DM_PLATFORM_IOS) || defined(DM_PLATFORM_OSX) || defined(DM_PLATFORM_ANDROID) #include <unistd.h> #endif #define EXTENSION_NAME Vibrate #define LIB_NAME "Vibrate" #define MODULE_NAME "vibrate" // Defold SDK #define DLIB_LOG_DOMAIN LIB_NAME #include <dmsdk/sdk.h> #if defined(DM_PLATFORM_IOS) || defined(DM_PLATFORM_ANDROID) #include "vibrate_private.h" static int Trigger(lua_State* L) { DM_LUA_STACK_CHECK(L, 0); int status = VibratePlatform_Trigger(); if( !status ) { luaL_error(L, "Failed to vibrate"); } return 0; } static const luaL_reg Module_methods[] = { {"trigger", Trigger}, {0, 0} }; static void LuaInit(lua_State* L) { int top = lua_gettop(L); luaL_register(L, MODULE_NAME, Module_methods); lua_pop(L, 1); assert(top == lua_gettop(L)); } dmExtension::Result AppInitializeVibrate(dmExtension::AppParams* params) { return dmExtension::RESULT_OK; } dmExtension::Result InitializeVibrate(dmExtension::Params* params) { LuaInit(params->m_L); return dmExtension::RESULT_OK; } dmExtension::Result AppFinalizeVibrate(dmExtension::AppParams* params) { return dmExtension::RESULT_OK; } dmExtension::Result FinalizeVibrate(dmExtension::Params* params) { return dmExtension::RESULT_OK; } #else // unsupported platforms static dmExtension::Result AppInitializeVibrate(dmExtension::AppParams* params) { dmLogInfo("Registered %s (null) Extension\n", MODULE_NAME); return dmExtension::RESULT_OK; } static dmExtension::Result InitializeVibrate(dmExtension::Params* params) { return dmExtension::RESULT_OK; } static dmExtension::Result AppFinalizeVibrate(dmExtension::AppParams* params) { return dmExtension::RESULT_OK; } static dmExtension::Result FinalizeVibrate(dmExtension::Params* params) { return dmExtension::RESULT_OK; } #endif // platforms DM_DECLARE_EXTENSION(EXTENSION_NAME, LIB_NAME, AppInitializeVibrate, AppFinalizeVibrate, InitializeVibrate, 0, 0, FinalizeVibrate)
#include "worldsinglethread.h" worldsinglethread::worldsinglethread(btScalar averageFPS,btScalar lowestFPS):WorldBase(averageFPS, lowestFPS) { } void worldsinglethread::init(btVector3 & gravity) { broadphase = new btDbvtBroadphase(); collisionConfiguration = new btDefaultCollisionConfiguration(); dispatcher = new btCollisionDispatcher(collisionConfiguration); solver = new btSequentialImpulseConstraintSolver; world = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration); world->setGravity(gravity); Object::setWorld(world); } worldsinglethread::~worldsinglethread() { }
// // ICMPPacket.cpp // // $Id: //poco/1.4/Net/src/ICMPPacket.cpp#2 $ // // Library: Net // Package: ICMP // Module: ICMPPacket // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "_Net/ICMPPacket.h" #include "_Net/ICMPv4PacketImpl.h" #include "_Net/NetException.h" #include "_/Timestamp.h" #include "_/Timespan.h" #include "_/NumberFormatter.h" #include <sstream> using _::InvalidArgumentException; using _::NotImplementedException; using _::Timestamp; using _::Timespan; using _::NumberFormatter; using _::UInt8; using _::UInt16; using _::Int32; namespace _Net { ICMPPacket::ICMPPacket(IPAddress::Family family, int dataSize):_pImpl(0) { if (family == IPAddress::IPv4) _pImpl = new ICMPv4PacketImpl(dataSize); #if defined(___HAVE_IPv6) else if (family == IPAddress::IPv6) throw NotImplementedException("ICMPv6 packets not implemented."); #endif else throw InvalidArgumentException("Invalid or unsupported address family passed to ICMPPacket"); } ICMPPacket::~ICMPPacket() { delete _pImpl; } void ICMPPacket::setDataSize(int dataSize) { _pImpl->setDataSize(dataSize); } int ICMPPacket::getDataSize() const { return _pImpl->getDataSize(); } int ICMPPacket::packetSize() const { return _pImpl->packetSize(); } int ICMPPacket::maxPacketSize() const { return _pImpl->maxPacketSize(); } const _::UInt8* ICMPPacket::packet() { return _pImpl->packet(); } struct timeval ICMPPacket::time(_::UInt8* buffer, int length) const { return _pImpl->time(buffer, length); } bool ICMPPacket::validReplyID(_::UInt8* buffer, int length) const { return _pImpl->validReplyID(buffer, length); } std::string ICMPPacket::errorDescription(_::UInt8* buffer, int length) { return _pImpl->errorDescription(buffer, length); } std::string ICMPPacket::typeDescription(int typeId) { return _pImpl->typeDescription(typeId); } } //< namespace _Net
#pragma once #include "integrator.h" #include "pp_disk.h" #include "red_type.h" class rungekutta4 : public integrator { public: static var_t a[]; static var_t b[]; static var_t bh[]; static ttt_t c[]; rungekutta4(pp_disk *ppd, ttt_t dt, bool adaptive, var_t tolerance, computing_device_t comp_dev); ~rungekutta4(); ttt_t step(); private: void cpu_sum_vector(int n, const var_t* a, const var_t* b, var_t b_factor, var_t* result); void cpu_calc_y_np1(int n, const var_t *y_n, const var_t *f1, const var_t *f2, const var_t *f3, const var_t *f4, var_t b0, var_t b1, var_t *y_np1); void cpu_calc_error(int n, const var_t *f4, const var_t* f5, var_t *result); void calc_ytemp_for_fr(uint32_t n_var, int r); void calc_y_np1(uint32_t n_var); void calc_error(uint32_t n_var); };
/* * Copyright (c) 2015-2017 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_SELECTION_SORT_H_ #define CPPSORT_DETAIL_SELECTION_SORT_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <cpp-sort/utility/iter_move.h> #include "min_element.h" namespace cppsort { namespace detail { template<typename ForwardIterator, typename Compare, typename Projection> auto selection_sort(ForwardIterator first, ForwardIterator last, Compare compare, Projection projection) -> void { for (ForwardIterator it = first ; it != last ; ++it) { using utility::iter_swap; iter_swap(it, unchecked_min_element(it, last, compare, projection)); } } }} #endif // CPPSORT_DETAIL_SELECTION_SORT_H_
// Created on: 1998-07-16 // Created by: CAL // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _V3d_RectangularGrid_HeaderFile #define _V3d_RectangularGrid_HeaderFile #include <Standard.hxx> #include <gp_Ax3.hxx> #include <V3d_ViewerPointer.hxx> #include <Standard_Boolean.hxx> #include <Standard_Real.hxx> #include <Aspect_RectangularGrid.hxx> class Graphic3d_Structure; class Graphic3d_Group; class V3d_RectangularGrid : public Aspect_RectangularGrid { DEFINE_STANDARD_RTTIEXT(V3d_RectangularGrid, Aspect_RectangularGrid) public: Standard_EXPORT V3d_RectangularGrid(const V3d_ViewerPointer& aViewer, const Quantity_Color& aColor, const Quantity_Color& aTenthColor); Standard_EXPORT virtual ~V3d_RectangularGrid(); Standard_EXPORT virtual void SetColors (const Quantity_Color& aColor, const Quantity_Color& aTenthColor) Standard_OVERRIDE; Standard_EXPORT virtual void Display() Standard_OVERRIDE; Standard_EXPORT virtual void Erase() const Standard_OVERRIDE; Standard_EXPORT virtual Standard_Boolean IsDisplayed() const Standard_OVERRIDE; Standard_EXPORT void GraphicValues (Standard_Real& XSize, Standard_Real& YSize, Standard_Real& OffSet) const; Standard_EXPORT void SetGraphicValues (const Standard_Real XSize, const Standard_Real YSize, const Standard_Real OffSet); //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; protected: Standard_EXPORT virtual void UpdateDisplay() Standard_OVERRIDE; private: Standard_EXPORT void DefineLines(); Standard_EXPORT void DefinePoints(); private: //! Custom Graphic3d_Structure implementation. class RectangularGridStructure; private: Handle(Graphic3d_Structure) myStructure; Handle(Graphic3d_Group) myGroup; gp_Ax3 myCurViewPlane; V3d_ViewerPointer myViewer; Standard_Boolean myCurAreDefined; Standard_Boolean myToComputePrs; Aspect_GridDrawMode myCurDrawMode; Standard_Real myCurXo; Standard_Real myCurYo; Standard_Real myCurAngle; Standard_Real myCurXStep; Standard_Real myCurYStep; Standard_Real myXSize; Standard_Real myYSize; Standard_Real myOffSet; }; DEFINE_STANDARD_HANDLE(V3d_RectangularGrid, Aspect_RectangularGrid) #endif // _V3d_RectangularGrid_HeaderFile
#include "stdafx.h" #include "CLRIQMeasure.h" #include "windows.h" #include "stdio.h" void OutputDebugPrintf(const char* strOutputString, ...) { char strBuffer[4096] = { 0 }; va_list vlArgs; va_start(vlArgs, strOutputString); _vsnprintf(strBuffer, sizeof(strBuffer) - 1, strOutputString, vlArgs); //vsprintf(strBuffer,strOutputString,vlArgs); va_end(vlArgs); OutputDebugStringA(strBuffer); } CLRIQMeasure::CLRIQMeasure() { } int CLRIQMeasure::add(int a, int b) { int c; c = a + b; //char msgbuf[1024]; //sprintf(msgbuf, "kajsdkfj"); //OutputDebugStringA(msgbuf); OutputDebugPrintf("%d,%d", a, b); return c; } int CLRIQMeasure::showstr(char* ssid) { OutputDebugPrintf("%d,%s",strlen(ssid),ssid); return 0; } int CLRIQMeasure::feedstr(char* buf) { char videoName[] = "{\"ID\":2,\"Name\":\"ÍõÒ»\",\"Age\":230,\"Sex\":\"ÄÐ\"}"; strcpy(buf, videoName); return 0; }
#include<bits/stdc++.h> using namespace std; main() { char s1[200]; while(cin>>s1) { int i, co=0; int len = strlen(s1); for(i=1; i<len; i++) { if(s1[i]<'a') co++; } if(co==(len-1)) { for(i=0; i<len; i++) { if(s1[i]<'a') s1[i]=s1[i]+32; else s1[i]=s1[i]-32; } } cout<<s1<<endl; co=0; } return 0; }
#include <iostream> #include <mpi.h> #include <unistd.h> #include <stdlib.h> #define MCW MPI_COMM_WORLD using namespace std; void printBoard(int arr[], const int ROW_SIZE) { cout << " Grid:\n"; for(int i = 0; i < ROW_SIZE; ++i) { for(int j = 0; j < ROW_SIZE; ++j) { if(arr[ROW_SIZE * i + j]) cout << " 0"; else cout << " -"; } cout << endl; } cout << endl; } int calcNeighbors(int arr[], const int ROW_SIZE, int i, int j) { int neighbors = 0; //north 3 if(i != 0) { // Upper left if(j != 0) neighbors += arr[ROW_SIZE * (i-1) + (j-1)]; // Upper neighbors += arr[ROW_SIZE * (i-1) + j]; // Upper right if(j+1 < ROW_SIZE) neighbors += arr[ROW_SIZE * (i-1) + (j+1)]; } // Middle 2 // Left if(j != 0) neighbors += arr[ROW_SIZE * (i) + (j-1)]; // Right if(j+1 < ROW_SIZE) neighbors += arr[ROW_SIZE * (i) + (j+1)]; // South 3 if(i+1 < ROW_SIZE) { // Upper left if(j != 0) neighbors += arr[ROW_SIZE * (i+1) + (j-1)]; // Upper neighbors += arr[ROW_SIZE * (i+1) + j]; // Upper right if(j+1 < ROW_SIZE) neighbors += arr[ROW_SIZE * (i+1) + (j+1)]; } return neighbors; } int main(int argc, char **argv) { const int ROW_SIZE = 8; int arr[ROW_SIZE * ROW_SIZE] = {0,0,0,0,0,0,0,0, 0,1,0,0,0,0,0,0, 0,0,1,1,0,0,0,0, 0,1,1,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0}; int tmpArr[ROW_SIZE * ROW_SIZE]; for(int i = 0; i < ROW_SIZE; ++i) { for(int j = 0; j < ROW_SIZE; ++j) { tmpArr[ROW_SIZE * i + j] = arr[ROW_SIZE * i + j]; } } printBoard(arr, ROW_SIZE); for(int cnt = 0; cnt < 10; cnt++){ for(int i = 0; i < ROW_SIZE; ++i) { for(int j = 0; j < ROW_SIZE; ++j) { int neighbors = calcNeighbors(arr, ROW_SIZE, i, j); if(neighbors == 0 || neighbors == 1) tmpArr[ROW_SIZE * i + j] = 0; else if(neighbors == 3) tmpArr[ROW_SIZE * i + j] = 1; else if(neighbors > 3) tmpArr[ROW_SIZE * i + j] = 0; } } for(int i = 0; i < ROW_SIZE; ++i) { for(int j = 0; j < ROW_SIZE; ++j) { arr[ROW_SIZE * i + j] = tmpArr[ROW_SIZE * i + j]; } } printBoard(arr, ROW_SIZE); } return 0; }
#ifndef _BERLEKAMP_MASSEY_ #define _BERLEKAMP_MASSEY_ #include <vector> namespace BM { const int mod = 1e9+7; long long add(long long a, long long b) { return ((a+b)%mod+mod)%mod; } long long powmod(long long a, long long b) { long long ret = 1; while(b) { if(b&1ll) ret*=a, ret%=mod; a*=a; a%=mod; b>>=1; } return ret; } long long inv(long long a) { return powmod(a, mod-2); } std::vector<long long> linearRecurrence(std::vector<long long> a) { int n = a.size(); std::vector<long long> l = {0}; std::vector<long long> mark = {0}; std::vector<std::vector<long long> > co = {{1}}; for(int i=1; i<n; i++) { long long eval = 0; for(int j=0; j<(int)l.size(); j++) { eval+=(l[j]*a[i-j-1]%mod+mod)%mod; eval%=mod; } if(eval==a[i]) continue; //There is a discrepancy long long d = add(eval, -a[i]); int mn = n+2; int ind = -1; for(int j=0; j<(int)mark.size(); j++) { if(i-1-mark[j]+(int)co[j].size()<mn) { mn = i-1-mark[j]+(int)co[j].size(); ind = j; } } mark.push_back(i); std::vector<long long> tmp = {1}; for(int x:l) tmp.push_back((mod-x)%mod); co.push_back(tmp); std::vector<long long> newl(i-1-mark[ind], 0); for(int x:co[ind]) newl.push_back(x); long long newval = 0; for(int j=0; j<(int)newl.size(); j++) newval = add(newval, (newl[j]*a[i-1-j]%mod+mod)%mod); for(long long &x:newl) x = x*inv(newval)%mod*d%mod; l.resize(std::max(l.size(), newl.size())); for(int j=0; j<(int)l.size(); j++) { if(j<(int)newl.size()) l[j] = add(l[j], -newl[j]); } } return l; } } #endif
#include "opencv2/core/core.hpp" #include "opencv2/calib3d/calib3d.hpp" #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "opencv2/contrib/contrib.hpp" #include <stdio.h> #include <string.h> #include <iostream> using namespace cv; using namespace std; void expand(int value) { const char * const ones[20] = {"zero", "one", "two", "three","four","five","six","seven", "eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen", "eighteen","nineteen"}; const char * const tens[10] = {"", "ten", "twenty", "thirty","forty","fifty","sixty","seventy", "eighty","ninety"}; if(value<0) { cout<<"minus "; expand(-value); } else if(value>=1000) { expand(value/1000); cout<<" thousand"; if(value % 1000) { if(value % 1000 < 100) { cout << " and"; } cout << " " ; expand(value % 1000); } } else if(value >= 100) { expand(value / 100); cout<<" hundred"; if(value % 100) { cout << " and "; expand (value % 100); } } else if(value >= 20) { cout << tens[value / 10]; if(value % 10) { cout << " "; expand(value % 10); } } else { cout<<ones[value]; } cout<<" "; return; } void conversion( float d) { int a=d,l=2; expand(a); d-=a; if(d!=0) cout<<" point "; while(l--) { d*=10; int c=d; expand(c); d-=c; } cout << " centimeters" ; } int main(int argc, char* argv[]) { int flag=0; VideoCapture stream1(0); VideoCapture stream2(1); Mat img1, img2, g1, g2; Mat disp, disparity; char* method = argv[1]; while(true){ float min=100000.00; stream1.read(img1); stream2.read(img2); cvtColor(img1, g1, CV_BGR2GRAY); cvtColor(img2, g2, CV_BGR2GRAY); if (!(strcmp(method, "BM"))) { StereoBM sbm; sbm.state->SADWindowSize = 21; sbm.state->numberOfDisparities = 80; sbm.state->preFilterSize = 5; sbm.state->preFilterCap = 61; sbm.state->minDisparity = -39; sbm.state->textureThreshold = 507; sbm.state->uniquenessRatio = 0; sbm.state->speckleWindowSize = 0; sbm.state->speckleRange = 8; sbm.state->disp12MaxDiff = 1; sbm(g1, g2, disp); } normalize(disp, disparity, 0, 255, CV_MINMAX, CV_8U); Mat Q; Q=(Mat_<double>(4,4)<< 1., 0., 0., -2.5064871978759766e+02, 0., 1., 0., -2.3899789428710938e+02, 0., 0., 0., 6.7491086722346256e+02, 0., 0., -1.3560081060673629e-01, 0.); Q.convertTo(Q, CV_32F); if (Q.cols != 4 || Q.rows != 4) { std::cerr << "ERROR: Q is not 4x4)" << std::endl; return 1; } //cv::Mat disparity = cv::imread("disp8", cv::IMREAD_GRAYSCALE); if (disparity.empty()) { std::cerr << "ERROR: Could not read disparity" << std::endl; return 1; } disparity.convertTo(disparity, CV_32F, 1.0 / 16.0); cv::Mat image3D; cv::reprojectImageTo3D(disparity, image3D, Q, false, CV_32F); for (int i = 0; i < image3D.rows; i++) { const cv::Vec3f* image3D_ptr = image3D.ptr<cv::Vec3f>(i); for (int j = 0; j < image3D.cols; j++) { //cout<< image3D_ptr[j][0] << " " << image3D_ptr[j][1] << " " << image3D_ptr[j][2] << endl; if(min > image3D_ptr[j][2] ) min = image3D_ptr[j][2] ; } } cout << min; flag++; if(flag==1000) { freopen ("myfile.txt","w",stdout); cout << "Closest object is detected at a distance of "; conversion (min) ; fclose (stdout); system("say -f myfile.txt"); flag=0; } namedWindow("left",WINDOW_NORMAL); resizeWindow("left",600,600); namedWindow("right",WINDOW_NORMAL); resizeWindow("right",600,600); namedWindow("disp",WINDOW_NORMAL); resizeWindow("disp",600,600); imshow("left", img1); imshow("right", img2); imshow("disp", disparity); if (waitKey(5) >= 0) break; } return(0); }
#pragma once #include "KEGIESDoc.h" class View2 : public CView { protected: // serialization View2(); DECLARE_DYNCREATE(View2) public: bool m_displayMode[10]; CKEGIESDoc* GetDocument() const; // function public: //Initialize void InitGL(); //Drawing void DrawView(); void SetupView(); void UpdateView(); void drawAxis(bool atOrigin, CCamera* cam); // variable public: HDC m_hDC; HGLRC m_hRC; GLuint base; //flag bool LEFT_DOWN; bool RIGHT_DOWN; //window int m_WindowHeight; int m_WindowWidth; //mouse position vec3d m_MousePos; vec3d m_PreMousePos; vec3d m_DMousePos; //camera manipulation CCamera m_Cam1; // public: virtual void OnDraw(CDC* pDC); // virtual BOOL PreCreateWindow(CREATESTRUCT& cs); // public: virtual ~View2(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: DECLARE_MESSAGE_MAP() public: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); virtual void OnInitialUpdate(); afx_msg void OnSize(UINT nType, int cx, int cy); //Key board afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); //Timer afx_msg void OnTimer(UINT_PTR nIDEvent); //Mouse function afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt); }; #ifndef _DEBUG // KEGIESView inline CKEGIESDoc* View2::GetDocument() const { return reinterpret_cast<CKEGIESDoc*>(m_pDocument); } #endif
#pragma once #include "List2w.h" using namespace std; template< typename T > struct MyQueue { List2W<T> list; }; template< typename T > MyQueue<T> CreateEmptyQueue() { MyQueue<T> st; st.list = CreateEmptyList2W<T>(); return st; } template< typename T > void Push(MyQueue<T> &st, T k) { AddLast(st.list, k); } template< typename T > T Pop(MyQueue<T> &st) { T temp = GetFirst(st.list); DeleteFirst(st.list); return temp; } template< typename T > bool isEmpty(MyQueue<T> st) { return isEmpty(st.list); }
#include <sfwdraw.h> #include "Defines.h" #include "AssetLib.h" #include "GameState.h" #include "GameLevel.h" bool Level::loaded = false; // We set up a static instance of GameState so that we may access the gamestate after it's initialized. Game *& Level::game() { static Game *gs; return gs; } // Set our texture name and level bounds. If this is our first session then load the texture. Level::Level() { textureName = "Map"; if (!loaded) loadTexture(textureName, "../textures/BasicMap.png", 1, 1); negativeBounds = Vector2(-450, -440); positiveBounds = Vector2(450, 465); } // Draw the level background and tint it blue to simulate darkness. void Level::Draw() { RENDER(getTexture(textureName), -game()->camOffset.x, -game()->camOffset.y, 960, 960, 0, true, 0,0x005aaeff); } // Get our levels bounds Vector2 Level::getNegativeBounds() { return negativeBounds; } Vector2 Level::getPositiveBounds() { return positiveBounds; }
#include "ChasingEnemy.h" #include "../CSC8503Common//StateTransition.h" #include "../CSC8503Common/StateMachine.h" #include "../CSC8503Common//State.h" #include "../GameTech/TutorialGame.h" #include "../CSC8503Common/NavigationPath.h" #include "../CSC8503Common/GameWorld.h" using namespace NCL; using namespace CSC8503; ChasingEnemy::ChasingEnemy(GameWorld* w, string n) { world = w; name = n; counter = 0.0f; //cards //float behaviourTimer; //float distanceToTarget; BehaviourAction* findPlayer = new BehaviourAction("Find Player", [&](float dt, BehaviourState state)->BehaviourState { if (state == Initialise) { std::cout << "Looking for player!\n"; counter = 0.0f; //behaviourTimer = rand() % 100; state = Ongoing; } else if (state == Ongoing) { counter += dt; for (int i = 0; i < 4; i++) { int randX = rand() % 64 + 1; int randZ = rand() % 64 + 1; int randY = rand() % 2 - 1; Vector3 edge = this->GetTransform().GetPosition() + (Vector3(1 / randX, 0, 1 / randZ) + Vector3(2.1f, randY, 2.1f)); //Vector3 edge = this->GetTransform().GetPosition() + (cards[i] * 2.1f); Ray r = Ray(edge, cards[i]); //std::cout << this->GetTransform().GetPosition(); RayCollision closestCollision; world->Raycast(r, closestCollision, true); Debug::DrawLine(this->GetTransform().GetPosition(), closestCollision.collidedAt, Vector4(1, 1, 1, 1), 10.0f); //Debug::DrawLine(this->GetTransform().GetPosition(), edge, Vector4(1, 1, 1, 1), 10.0f); //Debug::DrawLine(closestCollision.collidedAt, this->GetTransform().GetPosition(), Vector4(1, 1, 1, 1), 10.0f); GameObject* castedObject = (GameObject*)closestCollision.node; if (castedObject) { if (castedObject->GetName() == "player") { std::cout << "Located."; playerPosPoint = &(castedObject->GetTransform().GetPosition()); playerPos = castedObject->GetTransform().GetPosition(); player = castedObject; return Success; } //if (castedObject->GetName() == "coin") { // return Failure; //} } } if (counter > 10.0f) { std::cout << "Can't find them :(\n"; return Failure; } //if (behaviourTimer <= 0.0f) { // std::cout << "Found a key!\n"; // return Success; //} } return state; } ); BehaviourAction* goToPlayer = new BehaviourAction("Chase Player", [&](float dt, BehaviourState state)->BehaviourState { if (state == Initialise) { std::cout << "Going to chase them!\n"; state = Ongoing; } else if (state == Ongoing) { //distanceToTarget -= dt; direction = (player->GetTransform().GetPosition() - this->GetTransform().GetPosition()).Normalised(); this->GetPhysicsObject()->AddForce((direction * 45)); if ((playerPos - this->GetTransform().GetPosition()).Length() > 50) { std::cout << "Lost Player!\n"; return Failure; } } return state; //will be 'ongoing' until success } ); BehaviourAction* lookForCoin = new BehaviourAction("Looking for Coin", [&](float dt, BehaviourState state)->BehaviourState { if (state == Initialise) { std::cout << "Looking for coin!\n"; counter = 0.0f; //behaviourTimer = rand() % 100; state = Ongoing; } else if (state == Ongoing) { counter += dt; for (int i = 0; i < 4; i++) { int randX = rand() % 64 + 1; int randZ = rand() % 64 + 1; int randY = rand() % 2 - 1; Vector3 edge = this->GetTransform().GetPosition() + (Vector3(1 / randX, 0, 1 / randZ) + Vector3(2.1f, randY, 2.1f)); Ray r = Ray(edge, cards[i]); //std::cout << r.GetDirection(); RayCollision closestCollision; world->Raycast(r, closestCollision, true); //Debug::DrawLine(closestCollision.collidedAt, r.GetDirection(), Vector4(1, 1, 1, 1), 10.0f); GameObject* castedObject = (GameObject*)closestCollision.node; if (castedObject) { if (castedObject->GetName() == "coin") { std::cout << "Money.\n"; destination = castedObject->GetTransform().GetPosition(); return Success; } if (castedObject->GetName() == "player" && closestCollision.rayDistance < 50) { return Failure; } } } if (counter > 10.0f) { std::cout << "Can't find money :(\n"; return Failure; } //if (behaviourTimer <= 0.0f) { // std::cout << "Found a key!\n"; // return Success; //} } return state; } ); BehaviourAction* getCoin = new BehaviourAction("Get Coin", [&](float dt, BehaviourState state)->BehaviourState { if (state == Initialise) { std::cout << "Going to get rich!\n"; state = Ongoing; } else if (state == Ongoing) { //distanceToTarget -= dt; direction = (destination - this->GetTransform().GetPosition()).Normalised(); this->GetPhysicsObject()->AddForce((direction * 45)); if ((destination - this->GetTransform().GetPosition()).Length() < 2) { std::cout << "Got the cash.\n"; return Success; } } return state; //will be 'ongoing' until success } ); BehaviourSequence* sequence = new BehaviourSequence("Player Selector"); sequence->AddChild(findPlayer); sequence->AddChild(goToPlayer); //sequence->AddChild(openDoor); BehaviourSequence* selection = new BehaviourSequence("Coin Sequence"); selection->AddChild(lookForCoin); selection->AddChild(getCoin); root = new BehaviourSelector("Root Sequence"); root->AddChild(sequence); root->AddChild(selection); } ChasingEnemy::~ChasingEnemy() { delete stateMachine; } void ChasingEnemy::Update(float dt) { //stateMachine->Update(dt); if (first) { root->Reset(); first = false; } BehaviourState state = Ongoing; if (state == Ongoing) { state = root->Execute(dt); } if (state == Success || state == Failure) { root->Reset(); } } void ChasingEnemy::MoveLeft(float dt) { GetPhysicsObject()->AddForce({ -10, 0, 0 }); counter += dt; } void ChasingEnemy::MoveRight(float dt) { GetPhysicsObject()->AddForce({ 10, 0, 0 }); counter -= dt; }
#include <cstdio> int main(){ int n; int ans = 1; scanf("%d", &n); for (int i = 0; i < n; ++i) ans *= 2; printf("2^%d = %d\n", n, ans); return 0; }
#include <graphicsim.h> using namespace std; int main(){ // Always call initCanvas() after main function // initCanvas() initialises all data structures and opens a window // Key Checker Program - Title of the window. You can change that. initCanvas("Key Checker Program"); char *keyname; // Pointer to string XEvent event; // This is event structure // You can ignore XPoint XPoint p = {10, 10}; // XPoint is simple structure // Print messege on screen drawText(p, "Press key to get its code", COLOR("blue")); p.y += 15; drawText(p, "Click to exit", COLOR("blue")); // Event loop while(1){ // nextEvent() - It pauses your program till someone presses a key or mouse button nextEvent(&event); // --> You came here because some key was pressed or mouse click occured // Now check what has happend? // If event.type has code ButtonPress // Then mouse click has occured. Just exit program by breaking loop if(event.type == ButtonPress) break; // If event.type has code KeyPress // Then keyboard key has been pressed. if(event.type == KeyPress){ // Now lets try to determine what is KeyCode // keyname points to relevent string. switch(KeyCode(event)){ case KeyCode_ESC: keyname = (char*) "KeyCode_ESC"; break; case KeyCode_F1: keyname = (char*) "KeyCode_F1"; break; case KeyCode_F2: keyname = (char*) "KeyCode_F2"; break; case KeyCode_F3: keyname = (char*) "KeyCode_F3"; break; case KeyCode_F4: keyname = (char*) "KeyCode_F4"; break; case KeyCode_F5: keyname = (char*) "KeyCode_F5"; break; case KeyCode_F6: keyname = (char*) "KeyCode_F6"; break; case KeyCode_F7: keyname = (char*) "KeyCode_F7"; break; case KeyCode_F8: keyname = (char*) "KeyCode_F8"; break; case KeyCode_F9: keyname = (char*) "KeyCode_F9"; break; case KeyCode_F10: keyname = (char*) "KeyCode_F10"; break; case KeyCode_F11: keyname = (char*) "KeyCode_F11"; break; case KeyCode_F12: keyname = (char*) "KeyCode_F12"; break; case KeyCode_ACUTE: keyname = (char*) "KeyCode_ACUTE"; break; case KeyCode_0: keyname = (char*) "KeyCode_0"; break; case KeyCode_1: keyname = (char*) "KeyCode_1"; break; case KeyCode_2: keyname = (char*) "KeyCode_2"; break; case KeyCode_3: keyname = (char*) "KeyCode_3"; break; case KeyCode_4: keyname = (char*) "KeyCode_4"; break; case KeyCode_5: keyname = (char*) "KeyCode_5"; break; case KeyCode_6: keyname = (char*) "KeyCode_6"; break; case KeyCode_7: keyname = (char*) "KeyCode_7"; break; case KeyCode_8: keyname = (char*) "KeyCode_8"; break; case KeyCode_9: keyname = (char*) "KeyCode_9"; break; case KeyCode_A: keyname = (char*) "KeyCode_A"; break; case KeyCode_B: keyname = (char*) "KeyCode_B"; break; case KeyCode_C: keyname = (char*) "KeyCode_C"; break; case KeyCode_D: keyname = (char*) "KeyCode_D"; break; case KeyCode_E: keyname = (char*) "KeyCode_E"; break; case KeyCode_F: keyname = (char*) "KeyCode_F"; break; case KeyCode_G: keyname = (char*) "KeyCode_G"; break; case KeyCode_H: keyname = (char*) "KeyCode_H"; break; case KeyCode_I: keyname = (char*) "KeyCode_I"; break; case KeyCode_J: keyname = (char*) "KeyCode_J"; break; case KeyCode_K: keyname = (char*) "KeyCode_K"; break; case KeyCode_L: keyname = (char*) "KeyCode_L"; break; case KeyCode_M: keyname = (char*) "KeyCode_M"; break; case KeyCode_N: keyname = (char*) "KeyCode_N"; break; case KeyCode_O: keyname = (char*) "KeyCode_O"; break; case KeyCode_P: keyname = (char*) "KeyCode_P"; break; case KeyCode_Q: keyname = (char*) "KeyCode_Q"; break; case KeyCode_R: keyname = (char*) "KeyCode_R"; break; case KeyCode_S: keyname = (char*) "KeyCode_S"; break; case KeyCode_T: keyname = (char*) "KeyCode_T"; break; case KeyCode_U: keyname = (char*) "KeyCode_U"; break; case KeyCode_V: keyname = (char*) "KeyCode_V"; break; case KeyCode_W: keyname = (char*) "KeyCode_W"; break; case KeyCode_X: keyname = (char*) "KeyCode_X"; break; case KeyCode_Y: keyname = (char*) "KeyCode_Y"; break; case KeyCode_Z: keyname = (char*) "KeyCode_Z"; break; case KeyCode_SUBTRACT: keyname = (char*) "KeyCode_SUBTRACT"; break; case KeyCode_EQUAL: keyname = (char*) "KeyCode_EQUAL"; break; case KeyCode_BACKSPACE: keyname = (char*) "KeyCode_BACKSPACE"; break; case KeyCode_TAB: keyname = (char*) "KeyCode_TAB"; break; case KeyCode_CAPS_LOCK: keyname = (char*) "KeyCode_CAPS_LOCK"; break; case KeyCode_LSHIFT: keyname = (char*) "KeyCode_LSHIFT"; break; case KeyCode_RSHIFT: keyname = (char*) "KeyCode_RSHIFT"; break; case KeyCode_LALT: keyname = (char*) "KeyCode_LALT"; break; case KeyCode_RALT: keyname = (char*) "KeyCode_RALT"; break; case KeyCode_LCTRL: keyname = (char*) "KeyCode_LCTRL"; break; case KeyCode_RCTRL: keyname = (char*) "KeyCode_RCTRL"; break; case KeyCode_SPACEBAR: keyname = (char*) "KeyCode_SPACEBAR"; break; case KeyCode_ENTER: keyname = (char*) "KeyCode_ENTER"; break; case KeyCode_LBRACKET: keyname = (char*) "KeyCode_LBRACKET"; break; case KeyCode_RBRACKET: keyname = (char*) "KeyCode_RBRACKET"; break; case KeyCode_BACKSLASH: keyname = (char*) "KeyCode_BACKSLASH"; break; case KeyCode_SEMICOLON: keyname = (char*) "KeyCode_SEMICOLON"; break; case KeyCode_QUOTE: keyname = (char*) "KeyCode_QUOTE"; break; case KeyCode_COMMA: keyname = (char*) "KeyCode_COMMA"; break; case KeyCode_FULLSTOP: keyname = (char*) "KeyCode_FULLSTOP"; break; case KeyCode_FORWARDSLASH: keyname = (char*) "KeyCode_FORWARDSLASH"; break; case KeyCode_HOME: keyname = (char*) "KeyCode_HOME"; break; case KeyCode_PAGEUP: keyname = (char*) "KeyCode_PAGEUP"; break; case KeyCode_PAGEDOWN: keyname = (char*) "KeyCode_PAGEDOWN"; break; case KeyCode_END: keyname = (char*) "KeyCode_END"; break; case KeyCode_ARROWUP: keyname = (char*) "KeyCode_ARROWUP"; break; case KeyCode_ARROWDOWN: keyname = (char*) "KeyCode_ARROWDOWN"; break; case KeyCode_ARROWLEFT: keyname = (char*) "KeyCode_ARROWLEFT"; break; case KeyCode_ARROWRIGHT: keyname = (char*) "KeyCode_ARROWRIGHT"; break; case KeyCode_SCROLL: keyname = (char*) "KeyCode_SCROLL"; break; case KeyCode_PAUSE: keyname = (char*) "KeyCode_PAUSE"; break; case KeyCode_INSERT: keyname = (char*) "KeyCode_INSERT"; break; case KeyCode_DELETE: keyname = (char*) "KeyCode_DELETE"; break; case KeyCode_NUMLOCK: keyname = (char*) "KeyCode_NUMLOCK"; break; case KeyCode_NUMPADDIVIDE: keyname = (char*) "KeyCode_NUMPADDIVIDE"; break; case KeyCode_NUMPADMULTIPLY: keyname = (char*) "KeyCode_NUMPADMULTIPLY"; break; case KeyCode_NUMPADSUBTRACT: keyname = (char*) "KeyCode_NUMPADSUBTRACT"; break; case KeyCode_NUMPADPLUS: keyname = (char*) "KeyCode_NUMPADPLUS"; break; case KeyCode_NUMPADENTER: keyname = (char*) "KeyCode_NUMPADENTER"; break; case KeyCode_NUMPAD0: keyname = (char*) "KeyCode_NUMPAD0"; break; case KeyCode_NUMPAD1: keyname = (char*) "KeyCode_NUMPAD1"; break; case KeyCode_NUMPAD2: keyname = (char*) "KeyCode_NUMPAD2"; break; case KeyCode_NUMPAD3: keyname = (char*) "KeyCode_NUMPAD3"; break; case KeyCode_NUMPAD4: keyname = (char*) "KeyCode_NUMPAD4"; break; case KeyCode_NUMPAD5: keyname = (char*) "KeyCode_NUMPAD5"; break; case KeyCode_NUMPAD6: keyname = (char*) "KeyCode_NUMPAD6"; break; case KeyCode_NUMPAD7: keyname = (char*) "KeyCode_NUMPAD7"; break; case KeyCode_NUMPAD8: keyname = (char*) "KeyCode_NUMPAD8"; break; case KeyCode_NUMPAD9: keyname = (char*) "KeyCode_NUMPAD9"; break; case KeyCode_NUMPADFULLSTOP: keyname = (char*) "KeyCode_NUMPADFULLSTOP"; break; // For Unknown key codes, print on cout stream default: keyname = (char*)"KeyCode_UNKNOWN"; cout<<KeyCode(event)<<endl; break; } // Now keyname has valid code string // This is screen manipulation logic - IGNORE p.y += 15; // Ignore if(p.y > 600){ // Ignore p.y = 20; // Ignore p.x += 130; // Ignore } // Ignore // Now draw that string on screen // p is point having X co-ordinate p.x // and Y co-ordinate p.y drawText(p, keyname, COLOR("red")); } } // Always close window with this call closeCanvas(); return 0; }
/*! * \file memoryvariable.cpp * \author Simon Coakley * \date 2012 * \copyright Copyright (c) 2012 University of Sheffield * \brief Implementation of memory variable */ #include "./memoryvariable.h" MemoryVariable::MemoryVariable(QString n, QString d, ADT t, int s) { myName = n; myDesc = d; myType = t; mySize = s; myValue = 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: "stroustrup" -*- * * Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef XMLFRAGMENT_H #define XMLFRAGMENT_H #ifdef XMLUTILS_XMLFRAGMENT_SUPPORT #include "modules/xmlutils/xmltypes.h" class XMLFragmentData; class XMLExpandedName; class XMLCompleteName; class XMLNamespaceDeclaration; class XMLFragmentSerializerBackend; class XMLTreeAccessor; class ByteBuffer; class OpFileDescriptor; /** Convenience class intended for easily implemented parsers and generators of known simple XML dialects; principal use being the Opera 'scope' module and its support code in other modules. The parser is not optimized for minimal memory footprint, since it parses the entire fragment into an internal structure. Primarily, the parser has two important states: - the current element - the position The current element is simply a pointer to an element in the fragment. All attribute access functions access attributes on this element. The current element might be null, if the parser is on the top level of the fragment. In this case, the following functions should not be used: GetElementName(), GetNamespaceDeclaration(), MakeSubFragment(), GetAttribute(), GetAttributeFallback(), GetNextAttribute(), GetId() and GetAllText(). The function HasCurrentElement() can be used to check if there is a current element. The position can be thought of as a cursor positioned between two characters in the source text. It is always positioned inside the current element, when there is a current element. Additionally, it is never positioned inside character data, always "between tokens." Plain text and CDATA sections are considered the same, and all consecutive occurences of plain text and/or CDATA sections are merged. Whitespace is handled as described in the description of the SetDefaultWhitespaceHandling() function. All comments and processing instructions are completely ignored, unless API_XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT is imported, in which case they can be accessed as well. This extended content handling is mainly so that an XMLFragment can be used to parse and later reserialize as described in "Canonical XML 1.0". To enable storage (and thus access) of comments and processing instructions, the function SetStoreCommentsAndPIs() must be called before parsing. <h3>Parsing XML source code</h3> To parse XML source code into an XMLFragment is very simple: <pre> const uni_char *sourcecode = UNI_L("..."); XMLFragment fragment; RETURN_IF_ERROR(fragment.Parse(sourcecode)); </pre> If parsing fails, Parse returns OpStatus::ERR. After parsing, the fragment is ready for "reading". <h3>Reading content</h3> An XMLFragment is basically meant to be read sequentially from beginning to end. "Random access" is not really supported. Code for reading the contents of an XMLFragment containing a document that follows the content model <pre> <!ELEMENT root (item*)> <!ELEMENT item (subitem | text)*> <!ELEMENT subitem (data*)> <!ELEMENT text (#PCDATA)> <!ELEMENT data (#PCDATA)> </pre> could look something like this: <pre> TempBuffer buffer; if (fragment.EnterElement(UNI_L("root"))) { while (fragment.EnterElement(UNI_L("item"))) { if (fragment.EnterAnyElement()) { if (fragment.GetElementName() == UNI_L("subitem")) while (fragment.EnterElement(UNI_L("data"))) { RETURN_IF_ERROR(fragment.GetAllText(buffer)); HandleData(buffer); fragment.LeaveElement(); } else if (fragment.GetElementName() == UNI_L("text")) { RETURN_IF_ERROR(fragment.GetAllText(buffer)); HandleText(buffer); } fragment.LeaveElement(); } fragment.LeaveElement(); } } </pre> This type of code is not particularly robust in its handling of unexpected elements (content model violations, that is.) Using only EnterAnyElement() and GetElementName() enables reading of more untrusted documents, but is of course less convienent. Reading moves through the document by skipping past text and start tags in EnterElement() and EnterAnyElement(), skipping past text in GetAllText() and skipping past the "current" end tag (and any content preceding the end tag) in LeaveElement(). It is possible to move backwards either to the start of the entire fragment, using RestartFragment(), and the start of the current element, using RestartCurrentElement(). <h3>Accessing attributes</h3> Attributes are accessed on the current element, that is, the element a call to LeaveElement() would leave. After a (successful) call to EnterElement(), the entered element's attributes are accessed. After a call to LeaveElement(), attributes are accessed on the parent of the element just left. <b>Read named attribute</b> To read a specific attribute by name, use GetAttribute() like <pre> if (fragment.EnterElement(UNI_L("element"))) { if (const uni_char *attr1 = fragment.GetAttribute(UNI_L("attr1"))) HandleAttribute(...); if (const uni_char *attr2 = fragment.GetAttribute(UNI_L("attr2"))) HandleAttribute(...); } </pre> GetAttributeFallback() can be used to provide an explicit default value in case the attribute wasn't specified in the document. <b>Iterate through all attributes</b> To iterate through all the attribute's on an element, do something like <pre> if (fragment.EnterElement(UNI_L("element"))) { XMLCompleteName name; const uni_char *value; while (fragment.GetNextAttribute(name, value)) HandleAttribute(...); } </pre> The iteration can be restarted using RestartCurrentElement(). <h3>Generating content</h3> Content can be inserted into an XMLFragment as well. To build a document such as the one read in the section about reading, do something like <pre> XMLFragment fragment; RETURN_IF_ERROR(fragment.OpenElement(UNI_L("root"))); RETURN_IF_ERROR(fragment.OpenElement(UNI_L("item"))); RETURN_IF_ERROR(fragment.AddText(UNI_L("text"), UNI_L("this is some text"))); RETURN_IF_ERROR(fragment.OpenElement(UNI_L("subitem"))); RETURN_IF_ERROR(fragment.AddText(UNI_L("data"), UNI_L("this is some data"))); RETURN_IF_ERROR(fragment.AddText(UNI_L("data"), UNI_L("this is some more data"))); RETURN_IF_ERROR(fragment.CloseElement()); // close 'subitem' RETURN_IF_ERROR(fragment.CloseElement()); // close 'item' RETURN_IF_ERROR(fragment.CloseElement()); // close 'root' </pre> which would generate the document (minus the formatting, typically) <pre> <root> <item> <text>this is some text</text> <subitem> <data>this is some data</data> <data>this is some more data</data> </subitem> </item> </root> </pre> It is not strictly necessary to close all opened elements, closing the element only affects where new content is inserted, not whether the XML fragment is well-formed. RestartFragment() can be used when generation is finished to prepare the XMLFragment for reading. Reading and generating can be combined freely. To add another 'text' element at the end of the 'item' element in the fragment generated above, one can use the code <pre> fragment.RestartFragment(); fragment.EnterElement(UNI_L("root")); fragment.EnterElement(UNI_L("item")); while (fragment.EnterAnyElement()) fragment.LeaveElement(); RETURN_IF_ERROR(fragment.AddText(UNI_L("text"), UNI_L("additional text"))); </pre> The AddText() calls in the code above open an element named as their first argument, add a text node containing the second argument in it and close it again, that is, the same as the code <pre> RETURN_IF_ERROR(fragment.OpenElement(UNI_L("text"))); RETURN_IF_ERROR(fragment.AddText("this is some text")); fragment.CloseElement(); </pre> <h3>Retrieving XML source code</h3> At any time while reading or generating content, the whole XMLFragment can be retrieved as XML source code, either as a single unicode string or such a string encoded into binary data using any export encoding the encodings module supports, using the functions GetXML() and GetEncodedXML(). When converting to XML source code, characters in character data and attribute values that are not valid unescaped in XML, or that are not possible to represent in the selected encoding, are escaped using hexadecimal character references. Note that certain characters are not ever valid in character data or attribute values, even as character references. If such characters are present, the serialization will fail and GetXML()/GetEncodedXML() return OpStatus::ERR. See the section "Binary data" for a workaround. If element or attribute names in the fragment has namespace URI:s, appropriate namespace declarations ('xmlns' and 'xmlns:prefix' attributes) will be added if needed, and the prefix of those names may be changed if that is necessary. <h3>Whitespace handling</h3> Whitespace handling is slightly complex. Basically, there are two modes: <dl> <dt>default / XMLWHITESPACEHANDLING_DEFAULT</dt> <dd> According to XML: use the application's default behaviour. </dd> <dd> In XMLFragment: normalize whitespace characters so that only space (#x20) characters occur, and so that they never occur next to each other or in the beginning or end of an attribute or character data block. </dd> <dt>preserve / XMLWHITESPACEHANDLING_PRESERVE</dt> <dd> According to XML: preserve whitespace. </dd> <dd> In XMLFragment: do not modify whitespace in character data, and insert the necessary information and use character references in generated XML source code to keep it preserved outside of the XMLFragment. </dd> </dl> How the choice between these modes is made varies: <b>During parsing</b> During parsing, the XMLFragment's default whitespace handling mode, as set by SetDefaultWhitespaceHandling() or 'default' if not set, is initially used on all character data encountered in the document. Attribute values, however, are not normalized other than what the XML parser does following the XML specification (which, on the other hand, is quite a lot of normalization already.) The parsed document can change whitespace handling mode inside elements if it contains 'xml:space' attributes. Such attributes should have the values 'preserve' or 'default', and set the whitespace handling mode inside the elements accordingly. <b>During generation</b> For content generated using the functions AddText() and SetAttribute(), the XMLFragment's default whitespace handling is <em>not</em> used. Instead, those functions each have an argument named 'wshandling' that decides which mode to use for that content. This argument defaults to XMLWHITESPACEHANDLING_DEFAULT, that is, whitespace in the content is normalized by default. When generated content is retrieved as XML source code, extra 'xml:space' attributes will be added on elements, signalling how character data inside them is should to be handled. Essentially, if AddText() was used with the argument XMLWHITESPACEHANDLING_PRESERVE to add character data immediately inside an element, that element will have the attribute specification 'xml:space="preserve"' in its start tag in the generated XML source code, unless one of its ancestors already had such an attribute. Since 'xml:space' attributes do not apply to attribute values, non-space whitespace characters in attribute values are always escaped in the generated XML source code (since they typically only occur there if they occured escaped in the parsed XML source code or were added by a call to SetAttribute that preserved whitespace.) <h3>Binary data</h3> Since some characters simply cannot be represented in character data or attribute values in XML, unknown binary data should not be added as text in an XMLFragment. Such data must be encoded in some way external to XML. XMLFragment provides functionality for storing binary data encoded using base64 encoding. The functions AddBinaryData() and GetBinaryData() are used the same way as AddText() and GetAllText(), but access base64 encoded binary data instead of character data. Note that XMLFragment doesn't handle base64 encoded character data any different from ordinary character data: character data added with AddText() can be retrieved using GetBinaryData(), assuming it is valid base64 data, and binary data added with AddBinaryData() can be retrieved as unencoded character data using GetAllText(). */ class XMLFragment { private: friend class XMLFragmentSerializerBackend; friend class XMLFragmentTreeAccessor; XMLFragmentData *data; XMLWhitespaceHandling default_wshandling; #ifdef XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT BOOL store_comments_and_pis; #endif // XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT #ifdef XML_ERRORS const char *error_description; XMLRange error_location; #endif // XML_ERRORS OP_STATUS Construct(); public: XMLFragment(); /**< Constructor. The object is invalid for use until Parse() has been called successfully. */ virtual ~XMLFragment(); /**< Destructor. */ void SetDefaultWhitespaceHandling(XMLWhitespaceHandling wshandling) { default_wshandling = wshandling; } /**< Sets default whitespace handling used during parsing. This is overridden by any xml:space attributes in source text. The default default is XMLWHITESPACEHANDLING_DEFAULT (no pun intended) which means that all whitespace only character data is completely skipped (the parser behaves in all regards as if it wasn't in the source text at all,) that leading and trailing whitespace characters are stripped and that all sequences of one or more consecutive whitespace characters are normalized into a single space character. Whitespace is defined as all characters data matched by the 'S' production in XML 1.0/1.1: S ::= (#x20 | #x9 | #xD | #xA)+ Linebreaks are also normalized as specified by the used XML version, meaning for instance that in XML 1.1, the sequence (#xD #x85) comes out of the XML parser as a single #xA, which then is normalized into a single #x20. As usual XML 1.0 is the default if no XML declaration is present at the beginning of the document. This function must be called before the call to Parse() to have any effect. @param wshandling New default whitespace handling. */ #ifdef XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT void SetStoreCommentsAndPIs(BOOL value = TRUE) { store_comments_and_pis = value; } /**< If 'value' is TRUE, comments and processing instructions are stored in the fragment by the Parse() functions. By default, they are not. The functions GetComment() and GetProcessingInstruction() can be used to access comments and processing instructions. The functions EnterElement(), EnterAnyElement() and GetText() will all skip comments and processing instructions as if they weren't there. */ #endif // XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT OP_STATUS Parse(const uni_char *text, unsigned text_length = ~0u); /**< Parses the text. If the text is a well-formed XML fragment, OpStatus::OK is returned and the object is ready to be used. If the text is not a well-formed XML fragment OpStatus::ERR is returned, and none of the other functions may be called. The fragment may start with an XML declaration specifying XML version, encoding (which is ignored) and standalone, and a document type declaration. External entities are never loaded while internal entities are expanded as usual. Calling this function always resets the object to an initial state for parsing the new text. That is, all current state is lost. @param text Source text. Need not be null terminated if its length is specified. @param text_length Length of 'text' or ~0u to calculate length using uni_strlen. @return OpStatus::OK on success, OpStatus::ERR on parse errors or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS Parse(ByteBuffer *buffer, const char *charset = NULL); /**< Parses the contents of the buffer as if it had been joined into a single string, converted to unicode using either the supplied charset, the charset specified in the XML declaration, if one is present at the beginning of the data, or 'UTF-8', and then used in a call to Parse(const uni_char *, unsigned). @param buffer Buffer containing data to parse. @param charset Optional charset to use when decoding the data. @return Anything returned by Parse(const uni_char *, unsigned), and OpStatus::ERR if 'charset' is not a supported encoding. */ OP_STATUS Parse(OpFileDescriptor *fd, const char *charset = NULL); /**< Reads all data from the file descriptor and parses it. The file descriptor should be open for reading. If reading from the file fails, the error returned by OpFileDescriptor::Read will be returned by this function. Otherwise, this function works exactly like Parse(ByteBuffer *, const char *). @param fd A file descriptor open for reading. @param charset Optional charset to use when decoding the data. @return OpStatus::OK on success, or anything returned by OpFileDescriptor::Read, or anything returned by Parse(const ByteBuffer *, const char *). */ OP_STATUS Parse(URL url); /**< Creates a URL_DataDescriptor from the URL (by calling URL::GetDescriptor with the arguments mh=NULL, follow_ref=TRUE, override_content_type=URL_XML_CONTENT and otherwise the defaults,) reads all data from and parses it. The URL should be loaded or otherwise possible to read all data from. If no data is available to read from the URL or if not all data is available to read, this function will behave as if Parse(const uni_char *, unsigned) was called with an empty string or truncated string respectively. @param url URL to read and parse data from. @return OpStatus::OK on success, or anything thrown by URL_DataDescriptor::RetrieveDataL(), or anything returned by Parse(const uni_char *, unsigned), or OpStatus::ERR_NO_MEMORY if URL::GetDescriptor() returns NULL (which it might do if the URL is not ready for use as it should be, in addition to on OOM.) */ OP_STATUS Parse(HTML_Element *element); /**< Creates an XMLFragment containing the same information as the tree of elements whose root is 'element'. The element does not have to be an actual root element (that is, it can have both ancestors and siblings) but the resulting XMLFragment will look like if it was an actual root element. @param element An element. @return OpStatus::OK on success or OpStatus::ERR_NO_MEMORY on OOM. */ #ifdef XML_ERRORS /* Parse error access. Enabled by FEATURE_XML_ERRORS. */ const char *GetErrorDescription() { return error_description; } /**< Returns a string describing the parse error, or NULL if the there was some other kind of problem. Should only be used after one of the Parse() functions has returned OpStatus::ERR. @return Error message. The string is not owned by the caller and should not be freed. */ XMLRange GetErrorLocation() { return error_location; } /**< Returns the location of the parse error. Should only be used after one of the Parse() functions has returned OpStatus::ERR. A range with an invalid start point is returned if no error location is known. @return An error location. */ #endif // XML_ERRORS void RestartFragment(); /**< Restarts the fragment, which means moving position to before the very first content and setting no current element. */ BOOL HasMoreContent(); /**< Returns TRUE if there is any more content and FALSE if the end of the fragment or the current element (if an element has been entered) has been reached. @return TRUE or FALSE. */ BOOL HasMoreElements(); /**< Like HasMoreContent() but counts only elements. @return TRUE or FALSE. */ BOOL HasCurrentElement(); /**< Returns TRUE if there is a current element, or FALSE if the position is on the top-level of the fragment. @return TRUE or FALSE. */ /** Content types. */ enum ContentType { CONTENT_ELEMENT, CONTENT_TEXT, #ifdef XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT CONTENT_COMMENT, CONTENT_PROCESSING_INSTRUCTION, #endif // XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT CONTENT_END_OF_ELEMENT, CONTENT_END_OF_FRAGMENT }; ContentType GetNextContentType(); /**< Returns the type of content directly after the position. If type is CONTENT_ELEMENT a successful call to EnterElement will not have skipped any content. If type is CONTENT_TEXT a call to GetText() would succeed. If type is CONTENT_END_OF_FRAGMENT there is no more content. @return The type of content directly after the position. */ BOOL SkipContent(); /**< Moves to the next position in the current element. @return TRUE if we moved to the next content, else FALSE. */ BOOL EnterElement(const XMLExpandedName &name); /**< Enters an element named 'name' and returns TRUE, if the next element is named 'name', otherwise does nothing and returns FALSE. Only elements in the current element, if there is a current element, or top-level elements, if there is no current element, are considered. If 'name' has no prefix, any element with the right local part and namespace URI is entered, regardless of its prefix. If 'name' has a prefix, only elements with exactly the right complete name are considered. If an element is entered, the position is moved to after the element's start tag. Empty element tags are handled as a start tag directly followed by an end tag; that is, a call to LeaveElement() is also required to move the position to after the tag. If there is non-element content between the position and the start tag, it is skipped. If an element is not entered, the position is not moved, not even to skip content that would have been skipped if an element had been entered. @param name The element name's. @return TRUE or FALSE. */ BOOL EnterAnyElement(); /**< Like EnterElement, except it enters the next element, if there is one, regardless of its name. @return TRUE or FALSE. */ void RestartCurrentElement(); /**< Restarts the current element, which means moving position to where it was right after EnterElement, and restarting the attribute iteration performed by GetNextAttribute(). */ const XMLCompleteName &GetElementName(); /**< Returns the name of the current element (last one entered and not left.) The strings returned by the object are valid during the whole life time of the XMLFragment object, but no longer. */ XMLNamespaceDeclaration *GetNamespaceDeclaration(); /**< Returns a chain of namespace declarations representing all namespaces in scope at the current element. Its reference count is not increased by this function, and need not be increased at all unless it's used after the XMLFragment object has been destroyed. If no namespaces are in scope at the current element, NULL is returned. @return A namespace declaration chain or NULL. */ OP_STATUS MakeSubFragment(XMLFragment *&fragment); /**< Creates an XMLFragment object that is limited to the remaining content of the current element. The state of this XMLFragment is not affected by this function or by use of the created XMLFragment. The created XMLFragment will initially have no current element. Modifications made to the created XMLFragment will not affect the this XMLFragment. @param fragment Set to the created object. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ const uni_char *GetAttribute(const XMLExpandedName &name); /**< Returns the value of the attribute named 'name' on the current element. If the attribute was not specified but had a declared default value, the default value is returned. If the attribute was not specified and had no declared default value, NULL is returned. If the name has a namespace URI but no prefix, attributes with a prefix declared to that URI *or* attributes with no prefix on an element with that namespace URI are considered. If the name has no namespace URI, only namespaces with no prefix are considered, regardless of the element's namespace URI. If the name has both a namespace URI and a prefix, only attributes with names exactly matching the provided namespace URI and prefix are considered. @param name The attribute name. @return The attribute's value or NULL. */ const uni_char *GetAttributeFallback(const XMLExpandedName &name, const uni_char *fallback); /**< Like GetAttribute(), but returns 'fallback' instead of NULL. @param name The attribute name. @param fallback Fallback value or NULL. @return The attribute's value or 'fallback'. */ const uni_char *GetId(); /**< Returns the value of the first attribute declared to be of the type ID. The attributes 'xml:id' is always declared to be of type ID, as is a prefixless attribute named 'id' on an element with XHTML, SVG, WML or XSLT namespace. Using 'xml:id' or declaring the attribute to be of type ID in the internal document type subset is highly recommended when authoring fragments to be parsed. Relying on the attribute's implicit type in some namespace is bad. If no appropriate attribute was found, NULL is returned. A declared default value is never returned, even if it for some reason might seem like it might be. @return An id or NULL. */ BOOL GetNextAttribute(XMLCompleteName &name, const uni_char *&value); /**< Returns the next attribute (or the first, if it hasn't been used on the current element yet.) Attributes are returned in the order they were specified in the tag, with non-specified attributes with declared default values last. This function can be used at any time, mixed with any other function calls except EnterFunction() and LeaveFunction(), that change current element and thus change what element's attributes are iterated over. If there were no more attributes, FALSE is returned and the arguments are left unmodified. @param name Set to the next attribute's name. @param value Set to the next attribute's value. @return TRUE if there was a next attribute and FALSE if there wasn't. */ OP_STATUS GetAllText(TempBuffer &buffer); /**< Appends the concatenation of all character data in the current element to 'buffer', including that which is in descendant elements of the current element. The position is not moved. For whitespace handling, see SetDefaultWhitespaceHandling(). @param buffer Buffer to which character data is appended. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS GetAllText(TempBuffer &buffer, const XMLExpandedName &name); /**< Like GetAllText(TempBuffer &) but automatically enters an element named 'name' before and leaves it after, as if EnterElement and LeaveElement had been called. If entering the element fails (because the next element is not named 'name' or because there is no next element) no text is appended. If you need to know, enter the element manually. The position is moved to after the element, if an element is entered, otherwise the position is not changed. For whitespace handling, see SetDefaultWhitespaceHandling(). @param buffer Buffer to which character data is appended. @param name Name of element to enter. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ void LeaveElement(); /**< Leaves the current element. This moves the position to directly after the element's end tag. */ const uni_char *GetText(); /**< Returns the concatenation of all character data up to the next start tag, end tag or empty element tag or the empty string if there is no such character data. The position is moved past the returned text. For whitespace handling, see SetDefaultWhitespaceHandling(). @return Character data or the empty string. */ #ifdef XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT const uni_char *GetComment(); /**< Returns the text inside the comment immediately following the current position, or NULL if there is no comment immediately following the current position. (If GetNextContentType() returns CONTENT_COMMENT, the function will return non-NULL, otherwise it will return NULL.) The position is moved past the comment if a comment was found, otherwise it is not moved. No whitespace normalization other than basic linebreak normalization is performed on text inside comments. @return Comment text or NULL. */ BOOL GetProcessingInstruction(const uni_char *&target, const uni_char *&data); /**< Returns the target and data of the processing instruction immediately following the current position, and TRUE, if a processing instruction is immediately following the current position, otherwise returns FALSE. If the processing instruction contained no data (only whitespace followed the target) 'data' will be set to an empty string. The position is moved past the returned processing instruction if a processing instruction was found, otherwise it is not moved. No whitespace normalization other than basic linebreak normalization is performed on data of a processing instruction, but note that any whitespace between the target and the first non-whitespace character following the target is not part of the data, and thus will not appear at the beginning of the string in 'data'. @param target Set to a non-NULL string if a processing instruction was found, otherwise not modified. @param data Set to a non-NULL string if a processing instruction was found, otherwise not modified. @return TRUE if a processing instruction was found, otherwise FALSE. */ #endif // XMLUTILS_XMLFRAGMENT_EXTENDED_CONTENT OP_STATUS OpenElement(const XMLCompleteName &name); /**< Creates a new element as a child of the current element, inserted at the current position and enters it. The name must be a valid QName. If it contains a prefix and its namespace URI is NULL, the prefix is stripped. If it contains a prefix and that prefix is not declared, an appropriate namespace declaration attribute is automatically added. If it contains no prefix and its namespace URI is not NULL and the default namespace is not that URI, an appropriate default namespace declaration is automatically added. After a successful call, the current element is the newly created element and the position is after its start tag. To leave the element, use CloseElement. Note however that calling CloseElement is not required in order for the element to have an end tag, the end tag is inserted immediately by this function. @param name The element's name. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS SetAttribute(const XMLCompleteName &name, const uni_char *value, XMLWhitespaceHandling wshandling = XMLWHITESPACEHANDLING_DEFAULT); /**< Sets an attribute on the current element. If an attribute with the same expanded name already exists, it is removed first. If the name has a namespace URI but no prefix, and the current element's namespace URI is not the same as the name's, an appropriate namespace declaration attribute is added first. If it is not possible to declare the name's prefix like that, the name's prefix is changed to some other available prefix, and an appropriate namespace declaration attribute declared that prefix is added first. Note: markup characters, such as '<' and '&', in 'value' should not and can not be escaped with entity or character references. The value is automatically escaped as needed if the fragment is converted to XML text. Whitespace is handled according to 'wshandling'. If the value is XMLWHITESPACEHANDLING_DEFAULT, whitespace is normalized as described in the description of SetDefaultWhitespaceHandling, otherwise the value is not modified and all whitespace characters other than space in the attribute value will be escaped in generated XML source code, to keep the next XML parser parsing it from normalizing those whitespace characters into spaces. @param name The attribute's name. @param value The attribute's value. @param wshandling Whitespace handling. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS SetAttributeFormat(const XMLCompleteName &name, const uni_char *format, ...); /**< Like SetAttribute, but the value is preprocessed as if by a call to OpString::AppendFormat. */ void CloseElement(); /**< Closes the current element, making its parent element the current element and moving the position to after its end tag. */ OP_STATUS AddText(const uni_char *text, unsigned text_length = ~0u, XMLWhitespaceHandling wshandling = XMLWHITESPACEHANDLING_DEFAULT); /**< Adds text. The added text is automatically merged with any text content right before or after the position where the new text is inserted. Whitespace is handled according to the 'wshandling' attribute, see SetDefaultWhitespaceHandling for the interpretation of different values. Any xml:space attributes on the current element or its ancestors are not directly taken into account, but such an attribute is added on the current element if necessary when the fragment is serialized to XML text, in order to preserve the whitespace handling when the fragment is parsed again. Note that if xml:space attributes are added manually, or if text is added in the same element with different whitespace handling specified, the end result may not be what you intend. Note: the text added is really text. It is not parsed for markup, and any markup characters in it are escaped with character references if the fragment is converted to XML text. @param text Text to add. Need not be null terminated if its length is specified. @param text_length Length of 'text' or ~0u to calculate length using uni_strlen. @param wshandling Whitespace handling. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS AddText(const XMLExpandedName &name, const uni_char *text, unsigned text_length = ~0u, XMLWhitespaceHandling wshandling = XMLWHITESPACEHANDLING_DEFAULT); /**< Adds an element named 'name' containing the specified text. Calling this function corresponds to the sequence OpenElement(name); AddText(text, text_length, wshandling); CloseElement(); @param name Name of element to create. @param text Text to add. Need not be null terminated if its length is specified. @param text_length Length of 'text' or ~0u to calculate length using uni_strlen. @param wshandling Whitespace handling. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS AddBinaryData(const XMLExpandedName &name, const char *data, unsigned length); /**< Adds an element named 'name' containing the binary data encoded using base64 encoding. Calling this function corresponds to the sequence OpenElement(name); AddText(base64); CloseElement(); where base64 is the string resulting from converting data. Note: this is the only way to add data that can contain null characters and should always be used when storing data that is not actually text. @param name Name of element to create. @param data Binary data to add. @param length Number of bytes in 'data'. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS AddBinaryData(const XMLExpandedName &name, const ByteBuffer &buffer); /**< Like AddBinaryData(const XMLExpandedName &, const char *, unsigned) but adds all data from the supplied buffer. @param name Name of element to create. @param buffer Buffer containing data to add. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ OP_BOOLEAN GetBinaryData(const XMLExpandedName &name, char *&data, unsigned &length); /**< Retrieves base64 encoded binary data from the next element, if that element is named 'name'. Calling this function corresponds to the code if (EnterElement(name)) { TempBuffer buffer; GetAllText(buffer); // decode base64 into data/length return OpBoolean::IS_TRUE; } else return OpBoolean::IS_FALSE; The returned data is stored in an array allocated with new char[] that must be freed by the caller using delete[]. Note: only you know that the contents of the element really is base64 encoded binary data. This function only knows if it isn't, and returns OpStatus::ERR if it isn't. @param name Name of element. @param data Set to an allocated array, on success. @param length Set to the number of bytes in 'data' on success. @return OpBoolean::IS_TRUE on success, OpBoolean::IS_FALSE if the next element is not named 'name', OpStatus::ERR if base64 decoding failed and OpStatus::OUT_OF_MEMORY on OOM. */ OP_BOOLEAN GetBinaryData(const XMLExpandedName &name, ByteBuffer &buffer); /**< Like GetBinaryData(const XMLExpandedName &, char *&, unsigned &) but appends the extracted data to the supplied buffer. @param name Name of element. @param buffer Buffer to which data is appended on success. @return OpBoolean::IS_TRUE on success, OpBoolean::IS_FALSE if the next element is not named 'name', OpStatus::ERR if base64 decoding failed and OpStatus::OUT_OF_MEMORY on OOM. */ OP_STATUS AddFragment(XMLFragment *fragment); /**< Adds all content from a fragment (regardless of the fragments current element or position.) The argument fragment will be empty after the operation. Note: if the first or last inserted content is text, and it is inserted right after or right before text, that adjacent text content is merged. After the operation, position will be after the last inserted content, or, if the last inserted content was text that was merged with adjacent text, after the merged text content. The current element will not be changed. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY on OOM. */ class GetXMLOptions { public: GetXMLOptions(BOOL include_xml_declaration) : include_xml_declaration(include_xml_declaration), encoding(NULL), format_pretty_print(FALSE), #ifdef XMLUTILS_CANONICAL_XML_SUPPORT canonicalize(CANONICALIZE_NONE), #endif // XMLUTILS_CANONICAL_XML_SUPPORT scope(SCOPE_WHOLE_FRAGMENT) { } BOOL include_xml_declaration; /**< If TRUE, an XML declaration is appended before the rest of the content, saying this is XML 1.0 and what encoding it uses, if an encoding is supplied. Note: if an XML declaration is requested, and no encoding is supplied, the resulting text will in fact not be a well- formed external parsed entity (it will not match the extParsedEnt production,) since its XML declaration will not be a valid text declaration (it will not match the TextDecl production.) If this is important to you, don't include the XML declaration or do supply an encoding. */ const char *encoding; /**< If not NULL, characters in character data and attribute values that are not possible to represent in that encoding are escaped using character references. Any such characters in element names, attribute names, processing instruction targets or data or in any other markup besides comments will cause a serialization failure and the GetXML() or GetEncodedXML() function will return OpStatus::ERR. Unrepresentable characters in comments will be replaced by question marks. Note: when GetXML() is used the result will still be an ordinary unicode string, no actual conversion to the specified encoding will be performed. But the unicode string will be guaranteed to be convertible into the specified encoding without complications. */ BOOL format_pretty_print; /**< If TRUE, the generated XML will indented according to simple rules. No character data will be modified inside elements with xml:space="preserve". Note that there is no guarantee that this option doesn't modify the meaning of the document according to whatever content language the document is in. */ #ifdef XMLUTILS_CANONICAL_XML_SUPPORT enum Canonicalize { CANONICALIZE_NONE, /**< The default; the generated XML will not be canonicalized, instead it will be output as is, or pretty printed if requested, and with namespace declarations normalized as required to preserve document semantics. */ CANONICALIZE_WITHOUT_COMMENTS, /**< Canonicalize without comments. */ CANONICALIZE_WITH_COMMENTS, /**< Canonicalize with comments. The function SetStoreCommentsAndPIs() must be used, or else there will not be any comments to include. */ CANONICALIZE_WITHOUT_COMMENTS_EXCLUSIVE, /**< Same as CANONICALIZE_WITHOUT_COMMENTS but using the "Exclusive" algorithm. */ CANONICALIZE_WITH_COMMENTS_EXCLUSIVE /**< Same as CANONICALIZE_WITH_COMMENTS but using the "Exclusive" algorithm. */ }; Canonicalize canonicalize; /**< If not CANONICALIZE_NONE, the generated XML will follow the rules in 'Canonical XML 1.0'. This overrides all the other options, since canonical XML cannot include an XML declaration, must use UTF-8 and shouldn't be pretty printed in any way. Note that in practice, 'Canonical XML 1.0' compatible serialization can only be performed on documents parsed while loading external entities, and that none of the Parse() functions in XMLFragment typically does this. But if the document is standalone (does not have an external DTD subset, or reference any external entities declared in the internal DTD subset,) this of course doesn't matter as the serialization will be canonical in any case. Also note that 'Canonical XML 1.0' defines its own rules for how to serialize XML namespace declarations, that in practice means that the normal automatic fixup of such attributes made by the XML serializer is disabled. This means that the serialized fragment must contain all the XML namespace declaration attributes itself, or the result of the serialization will not be well-formed, or will mean something else than it was meant to mean. */ #endif // XMLUTILS_CANONICAL_XML_SUPPORT enum Scope { SCOPE_WHOLE_FRAGMENT, /**< All content in the fragment, regardless of current element or position. */ SCOPE_CURRENT_ELEMENT_INCLUSIVE, /**< The current element is rendered as the root element of the generated XML code. */ SCOPE_CURRENT_ELEMENT_EXCLUSIVE /**< The children of the current element are rendered. This can lead to a result that is not a well-formed XML document, since it may produce more than one top-level element and/or top-level character data. */ }; Scope scope; /**< Scope of serialization. When SCOPE_CURRENT_ELEMENT_INCLUSIVE or SCOPE_CURRENT_ELEMENT_EXCLUSIVE are combined with the 'canonicalize' option, attributes on ancestor elements of the current element (and in the latter case on the current element itself) may affect the result even though those elements are not included in the result, as specified in 'Canonical XML 1.0'. */ }; OP_STATUS GetXML(TempBuffer &buffer, const GetXMLOptions &options); /**< Appends all the contents of this fragment (ignoring current element and position) as a well-formed XML entity (and document, if there is only a single top-level element and no non-whitespace top-level character data) to 'buffer'. @param buffer Buffer into which the result is appended. @param options Serialization options. @return OpStatus::OK, OpStatus::ERR if the serialization fails or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS GetXML(TempBuffer &buffer, BOOL include_xml_declaration, const char *encoding = NULL, BOOL format_pretty_print = FALSE); /**< Appends all the contents of this fragment (ignoring current element and position) as a well-formed XML entity (and document, if there is only a single top-level element and no non-whitespace top-level character data) to 'buffer'. See the documentation for the corresponding members of the class GetXMLOptions for more information about the arguments. @param buffer Buffer into which the result is appended. @param include_xml_declaration If TRUE, an XML declaration is included. @param encoding A character encoding name or NULL. @param format_pretty_print If TRUE, the output is reformatted by adding white-space. @return OpStatus::OK, OpStatus::ERR on if 'encoding' is invalid or if the serialization failed, or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS GetEncodedXML(ByteBuffer &buffer, const GetXMLOptions &options); /**< Like GetXML, but converts the result to the specified encoding after the serialization. @param buffer Buffer into which the result is appended. @param options Serialization options. @return OpStatus::OK, OpStatus::ERR if the serialization fails or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS GetEncodedXML(ByteBuffer &buffer, BOOL include_xml_declaration, const char *encoding = "UTF-8", BOOL format_pretty_print = FALSE); /**< Like GetXML, but converts the result to the specified encoding after the serialization. @param buffer Buffer into which the encoded result is appended. @param include_xml_declaration If TRUE, an XML declaration is included. @param encoding A character encoding name. @param format_pretty_print If TRUE, the output is reformatted by adding white-space. @return OpStatus::OK, OpStatus::ERR on if 'encoding' is invalid or if the serialization failed, or OpStatus::ERR_NO_MEMORY on OOM. */ #ifdef XMLUTILS_XMLFRAGMENT_XMLTREEACCESSOR_SUPPORT /* Enabled by importing API_XMLUTILS_XMLFRAGMENT_XMLTREEACCESSOR. */ OP_STATUS CreateXMLTreeAccessor(XMLTreeAccessor *&treeaccessor); /**< Creates an XMLTreeAccessor instance that accesses the tree represented by this fragment. The tree accessor is "live" meaning any future changes made to the fragment are reflected by it, but typically tree accessors are assumed to access immutable trees, so it's best to finish the fragment and then create and use a tree accessor. The created object is owned by the caller and must be destroyed using FreeXMLTreeAccessor(). The tree accessor must not be used after the fragment has been destroyed, but can be destroyed after it. @param treeaccessor Set to the created object on success. @return OpStatus::OK or OpStatus::ERR_NO_MEMORY. */ static void FreeXMLTreeAccessor(XMLTreeAccessor *treeaccessor); /**< Destroys an XMLTreeAccessor instance previously created using CreateXMLTreeAccessor(). @param treeaccessor An XMLTreeAccessor instance create by CreateXMLTreeAccessor(), or NULL. */ #endif // XMLUTILS_XMLFRAGMENT_XMLTREEACCESSOR_SUPPORT #ifdef XMLUTILS_XMLFRAGMENT_XPATH_SUPPORT /* Enabled by importing API_XMLUTILS_XMLFRAGMENT_XPATH. */ OP_STATUS EvaluateXPathToNumber(double &result, const uni_char *expression, XMLNamespaceDeclaration *namespaces = NULL); /**< Evaluate the expression and convert the result to a number as by the XPath function number(). If the expression is invalid or the evaluation fails, OpStatus::ERR is returned. The context node for the evaluation is the current element, or the root node if there is no current element. If 'namespaces' is not NULL, it is used to resolve any namespace prefixes in the expression. If 'namespaces' is NULL and there are qualified names in the expression, or if any prefix in the expression is not declared, OpStatus::ERR is returned. @param result Set to TRUE or FALSE on success, otherwise not modified. @return OpStatus::OK, OpStatus::ERR on XPath errors or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS EvaluateXPathToBoolean(BOOL &result, const uni_char *expression, XMLNamespaceDeclaration *namespaces = NULL); /**< Evaluate the expression and convert the result to a boolean as by the XPath function boolean(). If the expression is invalid or the evaluation fails, OpStatus::ERR is returned. The context node for the evaluation is the current element, or the root node if there is no current element. If 'namespaces' is not NULL, it is used to resolve any namespace prefixes in the expression. If 'namespaces' is NULL and there are qualified names in the expression, or if any prefix in the expression is not declared, OpStatus::ERR is returned. @param result Set to TRUE or FALSE on success, otherwise not modified. @return OpStatus::OK, OpStatus::ERR on XPath errors or OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS EvaluateXPathToString(OpString &result, const uni_char *expression, XMLNamespaceDeclaration *namespaces = NULL); /**< Evaluate the expression and convert the result to a string as by the XPath function string(). If the expression is invalid or the evaluation fails, OpStatus::ERR is returned. The context node for the evaluation is the current element, or the root node if there is no current element. If 'namespaces' is not NULL, it is used to resolve any namespace prefixes in the expression. If 'namespaces' is NULL and there are qualified names in the expression, or if any prefix in the expression is not declared, OpStatus::ERR is returned. @param result Set to TRUE or FALSE on success, otherwise not modified. @return OpStatus::OK, OpStatus::ERR on XPath errors or OpStatus::ERR_NO_MEMORY on OOM. */ #endif // XMLUTILS_XMLFRAGMENT_XPATH_SUPPORT }; #endif // XMLUTILS_XMLFRAGMENT_SUPPORT #endif // XMLFRAGMENT_H
#include <dmp_lib/DMP/DMP_.h> #include <dmp_lib/trainMethods/LeastSquares.h> #include <dmp_lib/trainMethods/LWR.h> #include <dmp_lib/io/io.h> #include <dmp_lib/DMP/DMP.h> #include <dmp_lib/DMP/DMP_bio.h> namespace as64_ { namespace dmp_ { DMP_::DMP_(int N_kernels, double a_z, double b_z, std::shared_ptr<CanonicalClock> can_clock_ptr, std::shared_ptr<GatingFunction> shape_attr_gating_ptr) { this->zero_tol = 1e-30; // realmin; this->N_kernels = N_kernels; this->a_z = a_z; this->b_z = b_z; this->can_clock_ptr = can_clock_ptr; this->shape_attr_gating_ptr = shape_attr_gating_ptr; this->w = arma::vec().zeros(this->N_kernels); this->setCenters(); this->setStds(1.0); this->setY0(0); } void DMP_::train(dmp_::TrainMethod train_method, const arma::rowvec &Time, const arma::rowvec &yd_data, const arma::rowvec &dyd_data, const arma::rowvec &ddyd_data, double *train_err) { int n_data = Time.size(); int i_end = n_data-1; double tau = Time(i_end); double y0 = yd_data(0); double g = yd_data(i_end); this->setTau(tau); this->setY0(y0); arma::rowvec x(n_data); arma::rowvec s(n_data); arma::rowvec Fd(n_data); arma::mat Psi(this->numOfKernels(), n_data); for (int i=0; i<n_data; i++) { x(i) = this->phase(Time(i)); s(i) = this->forcingTermScaling(g) * this->shapeAttrGating(x(i)); Fd(i) = this->calcFd(x(i), yd_data(i), dyd_data(i), ddyd_data(i), g); Psi.col(i) = this->kernelFunction(x(i)); } switch (train_method) { case dmp_::TrainMethod::LWR: this->w = localWeightRegress(Psi, s, Fd, this->zero_tol); break; case dmp_::TrainMethod::LS: this->w = leastSquares(Psi, s, Fd, this->zero_tol); break; default: throw std::runtime_error("[DMP_::train]: Unsopported training method"); } if (train_err) { arma::rowvec F(Fd.size()); for (int i=0; i<F.size(); i++) { F(i) = this->calcLearnedFd(x(i), g); } *train_err = arma::norm(F-Fd)/F.size(); } } void DMP_::update(double x, double y, double z, double g, double y_c, double z_c) { double tau = this->getTau(); double shape_attr = this->shapeAttractor(x, g); double goal_attr = this->goalAttractor(x, y, z, g); this->dz = ( goal_attr + shape_attr + z_c) / tau; this->dy = ( z + y_c) / tau; this->dx = this->phaseDot(x); } double DMP_::calcYddot(double x, double y, double dy, double g, double tau_dot, double yc, double zc, double yc_dot) const { double tau = this->getTau(); double z = dy*tau - yc; double shape_attr = this->shapeAttractor(x, g); double goal_attr = this->goalAttractor(x, y, z, g); double dz = ( goal_attr + shape_attr + zc) / tau; double ddy = (dz + yc_dot - tau_dot*dy)/tau; return ddy; } double DMP_::getYddot(double tau_dot, double yc_dot) const { return (this->getZdot() + yc_dot - tau_dot*this->getYdot()) / this->getTau(); } int DMP_::numOfKernels() const { return w.size(); } void DMP_::setY0(double y0) { this->y0 = y0; } double DMP_::getY0() const { return this->y0; } void DMP_::setTau(double tau) { this->can_clock_ptr->setTau(tau); } double DMP_::getTau() const { return this->can_clock_ptr->getTau(); } double DMP_::phase(double t) const { return this->can_clock_ptr->getPhase(t); } double DMP_::phaseDot(double x) const { return this->can_clock_ptr->getPhaseDot(x); } arma::vec DMP_::kernelFunction(double x) const { arma::vec psi = arma::exp(-this->h % (arma::pow(x-this->c,2))); return psi; } double DMP_::goalAttractor(double x, double y, double z, double g) const { double goal_attr = this->a_z*(this->b_z*(g-y)-z); goal_attr *= this->goalAttrGating(x); return goal_attr; } double DMP_::goalAttrGating(double x) const { double gAttrGat = 1.0; return gAttrGat; } double DMP_::shapeAttrGating(double x) const { double sAttrGat = this->shape_attr_gating_ptr->getOutput(x); if (sAttrGat<0) sAttrGat = 0.0; return sAttrGat; } double DMP_::forcingTerm(double x) const { arma::vec Psi = this->kernelFunction(x); double f = arma::dot(Psi,this->w) / (arma::sum(Psi)+this->zero_tol); // add 'zero_tol' to avoid numerical issues return f; } void DMP_::setCenters() { int N_kernels = this->numOfKernels(); this->c.resize(N_kernels); arma::rowvec t = arma::linspace<arma::rowvec>(0,N_kernels-1, N_kernels)/(N_kernels-1); for (int i=0;i<t.size();i++) { this->c(i) = this->phase(t(i)*this->getTau()); } } void DMP_::setStds(double kernelStdScaling) { int N_kernels = this->numOfKernels(); this->h.resize(N_kernels); for (int i=0; i<N_kernels-1; i++) { this->h(i) = 1 / std::pow(kernelStdScaling*(this->c(i+1)-this->c(i)),2); } this->h(N_kernels-1) = this->h(N_kernels-2); } arma::vec DMP_::getAcellPartDev_g_tau(double t, double y, double dy, double y0, double x_hat, double g_hat, double tau_hat) const { arma::vec dC_dtheta = arma::vec().zeros(2); double K_dmp = this->a_z*this->b_z; double D_dmp = this->a_z; arma::vec psi = this->kernelFunction(x_hat); double sum_psi = arma::sum(psi) + this->zero_tol; double sum_w_psi = arma::dot(psi, this->w); double shape_attr_gat = this->shapeAttrGating(x_hat); double theta1 = g_hat; double theta2 = 1/tau_hat; double dshape_attr_gat_dtheta2 = this->shape_attr_gating_ptr->getPartDev_1oTau(t,x_hat); arma::vec dPsidtheta2 = -2*t*this->h%(theta2*t-this->c)%psi; double sum_w_dPsidtheta2 = arma::dot(this->w, dPsidtheta2); double dSumWPsi_dtheta2 = (sum_w_dPsidtheta2*sum_psi - sum_w_psi*arma::sum(dPsidtheta2) ) / std::pow(sum_psi,2); dC_dtheta(0) = (K_dmp + shape_attr_gat*sum_w_psi/sum_psi)*std::pow(theta2,2); dC_dtheta(1) = 2*theta2* (K_dmp*(theta1-y) + shape_attr_gat*(theta1-y0)*sum_w_psi/sum_psi) \ -D_dmp*dy + std::pow(theta2,2)*(theta1-y0)*( dshape_attr_gat_dtheta2*sum_w_psi/sum_psi + shape_attr_gat*dSumWPsi_dtheta2 ); dC_dtheta(1) = dC_dtheta(1)*(-1/std::pow(tau_hat,2)); return dC_dtheta; } void DMP_::exportToFile(std::ostream &out) const { throw std::runtime_error("[DMP_::exportToFile]: The object must be assigned a derived class pointer!"); } std::shared_ptr<DMP_> DMP_::importFromFile(std::istream &in) { int type_int; dmp_::read_scalar(type_int, in); dmp_::TYPE type = static_cast<dmp_::TYPE>(type_int); switch (type) { case TYPE::STD: return DMP::importFromFile(in); case TYPE::BIO: return DMP_bio::importFromFile(in); default: throw std::runtime_error("[DMP_::importFromfile]: Cannot import unsupported dmp type."); } } } // namespace dmp_ } // namespace as64_
#include "global.h" clock_t time_start() { return std::clock(); } void time(clock_t c_start) { if (!SHOW_INFO) return; std::clock_t c_end = std::clock(); std::cout << "CPU time used: " << 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC << " ms\n"; } void INFO(const char *s) { INFO(s,"",false); } void INFO(const char *s,bool ERR) { INFO(s,"",ERR); } void INFO(const char *s1,const char *s2,bool ERR) { if (ERR) { cout<<"ERR: "; } else { if (!SHOW_INFO) return; cout<<"i: "; } cout<<s1<<" "<<s2<<endl; if (ERR) { cin.get();cin.get(); } } void filename(char *out, const char* name) { char* dir = "..//..//inout//computation//"; sprintf(out,"%s%s",dir,name); } void filename(char *out,const char* name,const char* proc_name,const int ID) { char* dir = "..//..//inout//computation//"; sprintf(out,"%s%s%d%s",dir,proc_name,ID,name); } void print_point_neighbours(int ii,int jj,int kk,int r) { cout.precision(4); cout<<"okolie bodu "<<ii<<","<<jj<<","<<kk<<endl; for (int i=max(0,ii-r);i<=min(nx-1,ii+r);i++) { for (int j=max(0,jj-r);j<=min(ny-1,jj+r);j++) { for (int k=max(0,kk-r);k<=min(nz-1,kk+r);k++) { cout<<at[i][j][k]<<" "; } cout<<endl; } cout<<endl; } } void print_point_neighbours_slowness(int ii,int jj,int kk,int r) { cout.precision(4); cout<<"okolie bodu "<<ii<<","<<jj<<","<<kk<<" - slowness"<<endl; for (int i=max(0,ii-r);i<=min(nx-1,ii+r);i++) { for (int j=max(0,jj-r);j<=min(ny-1,jj+r);j++) { for (int k=max(0,kk-r);k<=min(nz-1,kk+r);k++) { cout<<1/v[i][j][k]<<" "; } cout<<endl; } cout<<endl; } }
#ifndef HTTP_TO_TAP_LOOP_HPP #define HTTP_TO_TAP_LOOP_HPP #include <boost/asio/posix/stream_descriptor.hpp> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include "socket.hpp" #include "loop_stop.hpp" #include "http_parser.hpp" namespace sp { typedef boost::function<bool(const http_parser*)> headers_complete_handler; class http_to_tap_loop { public: http_to_tap_loop(boost::shared_ptr<socket> socket, boost::asio::posix::stream_descriptor& tap, headers_complete_handler hch, loop_stop_handler lsh); void start(); private: class private_t; boost::shared_ptr<private_t> p; }; } #endif // HTTP_TO_TAP_LOOP_HPP
#pragma once #include <UtH/UtHEngine.hpp> struct EnemyFactory { static uth::GameObject* CreateEnemy(uth::PhysicsWorld& pworld, const std::string& texture, const pmath::Vec2& position); };
/* -*- coding: utf-8 -*- !@time: 2020/3/4 21:42 !@author: superMC @email: 18758266469@163.com !@fileName: 0046_children_s_games.cpp */ #include <environment.h> class Solution { public: int findLastNumber(int n, int m) { if (n < 1 || m < 1) return -1; int array[n]; int i = -1, step = 0, count = n; while (count > 0) { //跳出循环时将最后一个元素也设置为了-1 i++; //指向上一个被删除对象的下一个元素。 if (i >= n) i = 0; //模拟环。 if (array[i] == -1) continue; //跳过被删除的对象。 step++; //记录已走过的。 if (step == m) { //找到待删除的对象。 array[i] = -1; step = 0; count--; } } return i;//返回跳出循环时的i,即最后一个被设置为-1的元素 } int findLastNumber_recursive(unsigned int n, unsigned int m) { if (n == 0) return -1; if (n == 1) return 0; else return (findLastNumber_recursive(n - 1, m) + m) % n; } }; int fun() { int n = 8, m = 9; printf("%d\n", Solution().findLastNumber(n, m)); printf("%d", Solution().findLastNumber_recursive(n, m)); return 0; }
#include "..\coordtrans.h" int main() { return 0; }
#include <queue> #include <moveit/move_group_interface/move_group_interface.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <std_msgs/Int16.h> #include "panda_status.h" //////////////////////////////////////////////////////////////////////////////// static std::queue<geometry_msgs::Pose> targets_; //////////////////////////////////////////////////////////////////////////////// void update_pose(geometry_msgs::Pose new_target) { targets_.push(new_target); } //////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { ros::init(argc, argv, "robot"); ros::NodeHandle nh; ros::AsyncSpinner spinner(1); spinner.start(); ros::Subscriber pose_sub = nh.subscribe("pose", 100, update_pose); ros::Publisher panda_status_pub = nh.advertise<std_msgs::Int16>("panda_status", 100); static const std::string PLANNING_GROUP_ = "panda_arm"; moveit::planning_interface::MoveGroupInterface move_group(PLANNING_GROUP_); move_group.startStateMonitor(); std_msgs::Int16 status_msg; status_msg.data = PANDA_STOPPED; panda_status_pub.publish(status_msg); while (true) { for (uint32_t i = 0; i < targets_.size(); i++) { status_msg.data = PANDA_MOVING; panda_status_pub.publish(status_msg); ROS_INFO("Moving to target"); geometry_msgs::Pose target = targets_.front(); targets_.pop(); move_group.setPoseTarget(target); moveit::planning_interface::MoveGroupInterface::Plan my_plan; moveit::planning_interface::MoveItErrorCode success = move_group.plan(my_plan); if (success == moveit::planning_interface::MoveItErrorCode::SUCCESS) { move_group.move(); ROS_INFO("Signalling stop"); status_msg.data = PANDA_STOPPED; panda_status_pub.publish(status_msg); } else ROS_INFO("Error: No path available to target pose"); } } return 0; } /// @file
/* This file is part of the VRender library. Copyright (C) 2005 Cyril Soler (Cyril.Soler@imag.fr) Version 1.0.0, released on June 27, 2005. http://artis.imag.fr/Members/Cyril.Soler/VRender VRender is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. VRender is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VRender; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ /**************************************************************************** Copyright (C) 2002-2014 Gilles Debunne. All rights reserved. This file is part of the QGLViewer library version 2.6.3. http://www.libqglviewer.com - contact@libqglviewer.com This file may be used under the terms of the GNU General Public License versions 2.0 or 3.0 as published by the Free Software Foundation and appearing in the LICENSE file included in the packaging of this file. In addition, as a special exception, Gilles Debunne gives you certain additional rights, described in the file GPL_EXCEPTION in this package. libQGLViewer uses dual licensing. Commercial/proprietary software must purchase a libQGLViewer Commercial License. This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *****************************************************************************/ #include "VRender.h" #include "Exporter.h" #include "../qglviewer.h" #include <QFile> #include <QMessageBox> using namespace vrender ; using namespace std ; Exporter::Exporter() { _xmin=_xmax=_ymin=_ymax=_zmin=_zmax = 0.0 ; _pointSize=1 ; } void Exporter::exportToFile(const QString& filename, const vector<PtrPrimitive>& primitive_tab, VRenderParams& vparams) { QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::warning(NULL, QGLViewer::tr("Exporter error", "Message box window title"), QGLViewer::tr("Unable to open file %1.").arg(filename)); return; } QTextStream out(&file); writeHeader(out) ; unsigned int N = primitive_tab.size()/200 + 1 ; for(unsigned int i=0;i<primitive_tab.size();++i) { Point *p = dynamic_cast<Point *>(primitive_tab[i]) ; Segment *s = dynamic_cast<Segment *>(primitive_tab[i]) ; Polygone *P = dynamic_cast<Polygone *>(primitive_tab[i]) ; if(p != NULL) spewPoint(p,out) ; if(s != NULL) spewSegment(s,out) ; if(P != NULL) spewPolygone(P,out) ; if(i%N == 0) vparams.progress(i/(float)primitive_tab.size(),QGLViewer::tr("Exporting to file %1").arg(filename)) ; } writeFooter(out) ; file.close(); } void Exporter::setBoundingBox(float xmin,float ymin,float xmax,float ymax) { _xmin = xmin ; _ymin = ymin ; _xmax = xmax ; _ymax = ymax ; } void Exporter::setClearColor(float r, float g, float b) { _clearR=r; _clearG=g; _clearB=b; } void Exporter::setClearBackground(bool b) { _clearBG=b; } void Exporter::setBlackAndWhite(bool b) { _blackAndWhite = b; }
#include "stdafx.h" #include "ReturnButton.h" #include "../GameCursor.h" ReturnButton::ReturnButton() { m_fade = FindGO<Fade>("fade"); m_button = NewGO<SpriteRender>(2, "sp"); m_buttonSize.x /= 2; m_buttonSize.y /= 2; m_button->Init(L"Assets/sprite/returnButton.dds", m_buttonSize.x, m_buttonSize.y,true); m_button->SetPivot({ 0,0 }); m_button->SetPosition({ -640,-360,0 }); m_arrow = NewGO<SpriteRender>(2,"sp"); //m_arrow->Init(L"Assets/sprite/returnArrow.dds", m_buttonSize.x, m_buttonSize.y); m_arrow->Init(L"Assets/sprite/Rarrow0.dds", m_buttonSize.x, m_buttonSize.y); m_arrow->SetPivot({ 0,0 }); m_arrow->SetPosition({ -640,-360,0 }); m_arrowpos = { -508,-275.5f,0 }; m_bow = NewGO<SpriteRender>(2, "sp"); m_bow->Init(L"Assets/sprite/Rarrow2.dds", m_bowsize.x * m_scale, m_bowsize.y * m_scale); m_bow->SetScale({ m_bowsca,1,1 }); m_bow->SetPosition(m_arrowpos); m_bow->SetPivot({ 1,0.5 }); m_top = NewGO<SpriteRender>(2, "sp"); m_top->Init(L"Assets/sprite/Rarrow1.dds", m_topsize.x * m_scale, m_topsize.y * m_scale); CVector3 bowpos = m_arrowpos; bowpos.x -= m_bowsca * 80; m_top->SetPosition(bowpos); } void ReturnButton::SetScene(GameObject* scene) { m_scene = scene; } void ReturnButton::OnDestroy() { DeleteGO(m_button); DeleteGO(m_arrow); DeleteGO(m_top); DeleteGO(m_bow); }
#include <Tanker/ReceiveKey.hpp> #include <Tanker/ResourceKeyAccessor.hpp> #include <Tanker/Serialization/Serialization.hpp> #include <Tanker/Trustchain/Actions/KeyPublish.hpp> #include <Tanker/Trustchain/Block.hpp> namespace Tanker { ResourceKeyAccessor::ResourceKeyAccessor( Client* client, TrustchainVerifier* verifier, UserKeyStore* userKeyStore, Groups::IAccessor* groupAccessor, ProvisionalUserKeysStore* provisionalKeyStore, ResourceKeyStore* resourceKeyStore) : _client(client), _verifier(verifier), _userKeyStore(userKeyStore), _groupAccessor(groupAccessor), _provisionalUserKeysStore(provisionalKeyStore), _resourceKeyStore(resourceKeyStore) { } // Try to get the key, in order: // - from the resource key store // - from the tanker server // In all cases, we put the key in the resource key store tc::cotask<std::optional<Crypto::SymmetricKey>> ResourceKeyAccessor::findKey( Trustchain::ResourceId const& resourceId) { auto key = (TC_AWAIT(_resourceKeyStore->findKey(resourceId))); if (!key) { auto blocks = TC_AWAIT(_client->getKeyPublishes(gsl::make_span(&resourceId, 1))); for (auto const& block : blocks) { auto const keyPublish = blockToServerEntry(Serialization::deserialize<Trustchain::Block>( cppcodec::base64_rfc4648::decode(block))); auto keyEntry = TC_AWAIT(_verifier->verify(keyPublish)); TC_AWAIT(ReceiveKey::decryptAndStoreKey( *_resourceKeyStore, *_userKeyStore, *_groupAccessor, *_provisionalUserKeysStore, keyEntry.action.get<Trustchain::Actions::KeyPublish>())); } key = TC_AWAIT(_resourceKeyStore->findKey(resourceId)); } TC_RETURN(key); } }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2002 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef XMLPARSER_XMLBUFFER_H #define XMLPARSER_XMLBUFFER_H #include "modules/xmlparser/xmldoctype.h" class XMLDataSource; class XMLValidityReport; class XMLBuffer { public: XMLBuffer (XMLDataSource *source, BOOL is_xml_1_1); ~XMLBuffer (); OP_STATUS Initialize (unsigned literalsize); /**< Initializes the buffer and sets the sizes of the work buffer and literal parts. Can only be called once per buffer. */ void SetIsXML11 (); /**< The document is parsed as XML 1.1. */ void Consume (BOOL leave_entity_reference = FALSE, BOOL no_linebreaks = FALSE); /**< Consume the first 'length' characters as the parser sees it. */ void ConsumeEntityReference (BOOL consume); BOOL GrowL (BOOL leave_entity_reference); /**< Make more data available for the parser. May change the values of the parser's 'buffer', 'index', 'length' and 'offset' fields. Returns TRUE if more data is available after the call. Leaves if out of memory */ void ConsumeFromDataSource (); /**< Consume all internally consumed data from the external data source. */ BOOL IsAtEnd (); /**< Returns TRUE if all data has been processed. */ BOOL IsAllSeen (); /**< Returns TRUE if all data has seen (if the current parser buffer contains all remaining data.) */ void ExpandCharacterReference (unsigned length, unsigned character); /**< Expand a character reference at 'index', replacing 'length' characters. The 'index' should be local (that is, relative the parser's 'buffer' pointer.) */ void ExpandEntityReference (unsigned length, XMLDoctype::Entity *entity); /**< Expand a entity reference at 'index', replacing 'length' characters. The 'index' should be local (that is, relative the parser's 'buffer' pointer.) If 'add_padding' is TRUE, a pair of space characters are added surrounding the expanded text. If 'signal_end' is TRUE the end of the reference will be signal by simulating an end-of-buffer situation after which IsAtEntityEnd returns TRUE. */ BOOL CheckEntityAt (unsigned start, unsigned end, unsigned &line, unsigned &column, XMLDoctype::Entity *&entity); /**< Check that the range ['start', 'end') does not cross the start or end of an expanded entity reference. The indeces 'start' and 'end should be global. If the function returns FALSE, 'line' and 'column' will have been set to the location of the offending entity expansion and 'entity' will have been set to the offending entity. */ BOOL IsInEntityReference (XMLDoctype::Entity *entity); /**< Returns TRUE if the character at 'index' comes from an expanded reference to 'entity'. Used to check for recursive entities. The 'index' should be local (that is, relative the parser's 'buffer' pointer.) */ BOOL IsInEntityReference () { return current_state != first_state; } /**< Returns TRUE if parser's 'buffer' is the replacement text of an entity. */ XMLDoctype::Entity *GetCurrentEntity (); /**< Returns current entity (valid when IsInEntityReference returns TRUE.) */ void SetParserFields (const uni_char *&buffer, unsigned &index, unsigned &length); /**< Set the parser's 'buffer', 'length', 'index' and 'offset' fields. Updates the value's of the fields as well as stores pointers to them so that they can be updated by other functions. They are updated by Consume, Flush, Grow and ExpandEntity. */ void LiteralStart (BOOL leave_entity_reference); /**< Mark the start of literal data. */ void LiteralEnd (BOOL leave_entity_reference); /**< Mark the end of literal data. */ BOOL GetLiteralIsWhitespace (); /**< Returns TRUE if the current literal matches the 'S' production. */ BOOL GetLiteralIsSimple (); /**< Returns TRUE if the current literal is contained entirely in the work buffer. If it is, the pointer returned by GetLiteral points directly into the work buffer and needs to be copied. If not, the pointer returned by GetLiteral is allocated and needs to be freed by the caller (using delete[].) */ uni_char *GetLiteral (BOOL copy = TRUE); /**< Returns the current literal. See GetLiteralIsSimple. */ unsigned GetLiteralLength (); /**< Returns the length of the current literal. */ void GetLiteralPart (unsigned index, uni_char *&data, unsigned &data_length, BOOL &need_copy); /**< Retrieves the 'index'th part of the current literal. The 'data' and 'data_length' arguments will be set to the part's contents and length, respectively. The 'need_copy' argument is set to FALSE if the caller can take over ownership of the part by calling ReleaseLiteralPart with the same index. */ void ReleaseLiteralPart (unsigned index); /**< Releases the 'index'th part of the current literal, so that it is not reused and not freed by the buffer later. */ unsigned GetLiteralPartsCount (); /**< Returns the number of parts in the current literal. Each part can be retrieved using the GetLiteralPart function. */ void SetCopyBuffer (TempBuffer *buffer); void NormalizeLinebreaks (uni_char *buffer, unsigned &length); /**< Normalize linebreaks in the text in 'buffer'. 'Buffer' is not null terminated; the first 'length' characters are used. Upon return, 'length' will have been adjusted to exclude any linebreak characters that were normalized away. */ #ifdef XMLUTILS_XMLPARSER_PROCESSTOKEN void InsertCharacterData (const uni_char *data, unsigned data_length); #endif // XMLUTILS_XMLPARSER_PROCESSTOKEN #ifdef XML_VALIDATING void SetValidityReport (XMLValidityReport *validity_report); #endif // XML_VALIDATING #ifdef XML_ERRORS void GetLocation (unsigned index, XMLPoint &point, BOOL no_linebreaks = FALSE); /**< Gets the line and column (in the base data source) of the character with the global index 'index'. */ #endif // XML_ERRORS protected: class State { public: const uni_char *buffer; unsigned index; unsigned length; unsigned literal_start; unsigned literal_end; unsigned consumed; unsigned consumed_before; XMLDoctype::Entity *entity; /**< The referenced entity. */ State *previous_state; State *next_state; #ifdef XML_ERRORS unsigned line; /**< Line number of the first character of the entity reference. */ unsigned column; /**< Column number of the first character of the entity reference. */ #endif // XML_ERRORS }; void DiscardState (); void DeleteStates (State *state); void CopyFromParserFields (); void CopyToParserFields (); void FlushToLiteral (); void CopyToLiteral (const uni_char *data, unsigned data_length, BOOL normalize_linebreaks); uni_char *AddLiteralBuffer (); State *NewState (); #ifdef XML_VALIDATING void CopyToLineBuffer (const uni_char *data, unsigned data_length); #endif // XML_VALIDATING #ifdef XML_ERRORS void UpdateLine (const uni_char *data, unsigned data_length); #endif // XML_ERRORS State *current_state; /**< Innermost current entity expansion. */ State *first_state; /**< Outermost current entity expansion. */ BOOL in_literal; uni_char **literal_buffers; unsigned literal_copied; unsigned literal_buffers_used, literal_buffers_count, literal_buffers_total; unsigned literal_buffer_offset, literal_buffer_size; const uni_char **parser_buffer; /**< Pointer to the parser's 'buffer' field. */ unsigned *parser_index; /**< Pointer to the parser's 'index' field. */ unsigned *parser_length; /**< Pointer to the parser's 'length' field. */ XMLDataSource *data_source; /**< Base data source. */ BOOL is_xml_1_1; /**< TRUE if the document is parsed as XML 1.1. */ BOOL at_end; /**< TRUE if IsAtEnd returnes TRUE. See IsAtEnd. */ BOOL last_was_carriage_return; /**< Last character copied into the literal buffer was a CARRIAGE RETURN that was converted to a LINE FEED as part of normal line-break normalization. */ #ifdef XML_VALIDATING BOOL is_validating; uni_char *line_buffer; unsigned line_buffer_offset, line_buffer_size; XMLValidityReport *validity_report; #endif // XML_VALIDATING #ifdef XML_ERRORS unsigned line; /**< Line (in the base data source) of the first non-consumed character from the data source. */ unsigned column; /**< Column (in the base data source) of the first non-consumed character from the data source. */ unsigned character; /**< Index (in the base data source) of the first non-consumed character from the data source. */ uni_char previous_ch; /**< The previous character from the base data source (essentially 'data_source->GetData ()[base_offset-1]', except base_offset might be zero and the character flushed.) */ unsigned cached_index, cached_line, cached_column; #endif // XML_ERRORS TempBuffer *copy_buffer; State *free_state; }; #endif // XMLPARSER_XMLBUFFER_H
// // Game.cpp // #include "pch.h" #include <DirectXMath.h> #include <sstream> #include "Game.h" extern void ExitGame(); using namespace DirectX; using Microsoft::WRL::ComPtr; Game::Game() noexcept : m_window(nullptr), m_outputWidth(1280), m_outputHeight(720) { } // Initialize the Direct3D resources required to run. void Game::Initialize(HWND window, int width, int height) { m_window = window; m_outputWidth = std::max(width, 1); m_outputHeight = std::max(height, 1); m_Graphics = std::make_shared<Graphics>(); if (!m_Graphics->Initialize(window, width, height)) { OnDeviceLost(); } m_Input = std::make_shared<Input>(); m_Input->Initialize(window); m_GameState = std::make_unique<GameState>(); if (!m_GameState->Initialize(m_Graphics, window, m_Input)) { OnDeviceLost(); } m_GameState->Start(); // minden kuka //CreateDevice(); //CreateResources(); // TODO: Change the timer settings if you want something other than the default variable timestep mode. // e.g. for 60 FPS fixed timestep update logic, call: /* m_timer.SetFixedTimeStep(true); m_timer.SetTargetElapsedSeconds(1.0 / 60); //*/ } // Executes the basic game loop. void Game::Tick() { m_timer.Tick([&]() { Update(m_timer); }); Render(); } // Updates the world. void Game::Update(DX::StepTimer const& timer) { m_GameState->Update(timer); } // Draws the scene. void Game::Render() { // Don't try to render anything before the first Update. if (m_timer.GetFrameCount() == 0) { return; } m_GameState->Render(); } // Message handlers void Game::OnActivated() { // TODO: Game is becoming active window. } void Game::OnDeactivated() { // TODO: Game is becoming background window. } void Game::OnSuspending() { // TODO: Game is being power-suspended (or minimized). } void Game::OnResuming() { m_timer.ResetElapsedTime(); // TODO: Game is being power-resumed (or returning from minimize). } void Game::OnWindowSizeChanged(int width, int height) { m_outputWidth = std::max(width, 1); m_outputHeight = std::max(height, 1); m_Graphics->updateScreenSize(m_window, m_outputWidth, m_outputHeight); m_GameState->UpdateScreenSize(width, height); //m_Camera->UpdateScreenSize(width, height); //CreateResources(); // TODO: Game window is being resized. } // Properties void Game::GetDefaultSize(int& width, int& height) const { // TODO: Change to desired default window size (note minimum size is 320x200). width = 1280; height = 720; } // These are the resources that depend on the device. void Game::CreateDevice() { //m_shape1 = GeometricPrimitive::CreateSphere(m_d3dContext.Get()); //m_shape2 = GeometricPrimitive::CreateSphere(m_d3dContext.Get()); } // Allocate all memory resources that change on a window SizeChanged event. void Game::CreateResources() { // TODO: Initialize windows-size dependent objects here. //m_view = DirectX::SimpleMath::Matrix::CreateLookAt(DirectX::SimpleMath::Vector3(0.f, 0.f, 4.f), //DirectX::SimpleMath::Vector3::Zero, DirectX::SimpleMath::Vector3::UnitY); //m_projection = DirectX::SimpleMath::Matrix::CreatePerspectiveFieldOfView(XM_PI / 4.f, //float(1280) / float(720), 0.1f, 1000.f); //m_view = m_Camera->GetViewMatrix(); //m_projection = XMMatrixPerspectiveFovLH(XM_PI / 4.f, float(1280) / float(720), 0.1f, 1000.f); //m_projection = m_Camera->GetProjectionMatrix(); } void Game::OnDeviceLost() { // TODO: Add Direct3D resource cleanup here. m_Graphics.reset(); m_GameState.reset(); m_Input.reset(); }
#ifndef RECT_H #define RECT_H namespace ld { struct Rect { Rect(int x_, int y_, int w_, int h_) : x(x_), y(y_), w(w_), h(h_) {} int x, y; int w, h; }; } #endif /* RECT_H */
#include <bits/stdc++.h> using namespace std; int main(){ int n, k; cin >> n >> k; vector<char> v(k); for(int i=0; i<k; i++) cin >> v[i]; for(int i=n; i<1000000; i++){ string s = to_string(i); bool flag = false; for(int j=0; j<s.size(); j++){ for(int l=0; l<k; l++) if(s[j] == v[l]) flag = true; } if(!flag){ cout << i << endl; return 0; } } }
byte chessdata[10][18]; void CbaiwinllkDlg::OnBnClickedReadchessdata() { //获取窗口句柄 HWND gameh = ::FindWindow(NULL,"无标题-记事本"); //获取窗口进程ID DWORD processid; ::GetWindowThreadProcessId(gameh,&processid); //打开指定进程 HANDLE processh=::OpenProcess(PROCESS_ALL_ACCESS,false,processid); //读取进程内存数据 DWORD byread; DWORD tmp; LPCVOID pbase=(LPCVOID)0x4455C8; //棋盘数据基址 LPVOID nbuffer=(LPVOID)&chessdata; //存放棋盘数据 ::ReadProcessMemory(processh,pbase,&tmp,4,&byread); ::ReadProcessMemory(processh,(LPCVOID)(tmp+0x8),&tmp,4,&byread); ::ReadProcessMemory(processh,(LPCVOID)(tmp+0x8),&tmp,4,&byread); ::ReadProcessMemory(processh,(LPCVOID)(tmp+0xA0),nbuffer,10*18,&byread); //显示棋盘数据 char buf[10]; m_chessdata=_T(""); for(int y=0;y<10;y++) { for(int x=0;x<18*4;x+=4) //读一行 { itoa(chessdata[y][x],buf,16); //转换成字串 m_chessdata+=buf; m_chessdata+=_T(" "); } //换行 m_chessdata+="\r\n"; } UpdateData(false); }
#pragma GCC optimize("Ofast") #include <algorithm> #include <bitset> #include <deque> #include <iostream> #include <iterator> #include <string> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; void abhisheknaiidu() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } struct Node { int data; Node* left; Node* right; }; // utitlity function to create new Node. Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return(temp); } void inorder(Node* root) { stack <Node*> s; // s.push(root); while(!s.empty() || root != NULL) { while(root != NULL) { //push left children if available s.push(root); root = root->left; } //retrieve top node and store its right child if exists root = s.top(); s.pop(); cout << root->data << " "; root = root->right; } } void inorderRecursive(Node* root) { if(root == NULL) return; inorderRecursive(root->left); cout << root->data << " "; inorderRecursive(root->right); } void preorder(Node* root) { stack<Node*> s; s.push(root); while(!s.empty()) { Node* cur = s.top(); s.pop(); if(cur != NULL) { // preorder cout << cur->data << " "; // push unvisited neighbours to stack | order matters here, if you reverse it // it would still be a DFS but a symmetric one to preorder out of the 6 possible combinations. s.push(cur->right); s.push(cur->left); } } } void preorderRecursive(Node* root) { if(root == NULL) return; cout << root->data << " "; preorderRecursive(root->left); preorderRecursive(root->right); } void postorder(Node* root) { stack <Node*> s1; stack <Node*> s2; s1.push(root); while(!s1.empty()) { root = s1.top(); s1.pop(); s2.push(root); if(root->left) s1.push(root->left); if(root->right) s1.push(root->right); } while(!s2.empty()) { root = s2.top(); s2.pop(); cout << root->data << " "; } } void postorderRecursive(Node* root) { if(root == NULL) return; postorderRecursive(root->left); postorderRecursive(root->right); cout << root->data << " "; } int main(int argc, char* argv[]) { abhisheknaiidu(); Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->right = newNode(6); cout << "Inorder Iterative: "; inorder(root); cout << endl; cout << "Inorder Recursive: "; inorderRecursive(root); cout << endl; cout << "Preorder Iterative: "; preorder(root); cout << endl; cout << "Preorder Recursive: "; preorderRecursive(root); cout << endl; cout << "Postorder Iterative: "; postorder(root); cout << endl; cout << "Postorder Recursive: "; postorderRecursive(root); return 0; }
#include <iomanip> #include "CHAR.hpp" CHAR::CHAR() { } CHAR::CHAR(char x) { this->x = x; } string CHAR::concatenar(char c, char c2) { string respuesta; respuesta += c; respuesta += c2; return respuesta; }
// Created on: 1991-08-09 // Created by: Jean Claude VAUTHIER // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BSplCLib_HeaderFile #define _BSplCLib_HeaderFile #include <BSplCLib_EvaluatorFunction.hxx> #include <BSplCLib_KnotDistribution.hxx> #include <BSplCLib_MultDistribution.hxx> #include <GeomAbs_BSplKnotDistribution.hxx> #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <Standard_Real.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <TColStd_Array1OfReal.hxx> #include <TColStd_Array2OfReal.hxx> #include <TColStd_HArray1OfInteger.hxx> #include <TColStd_HArray1OfReal.hxx> class gp_Pnt; class gp_Pnt2d; class gp_Vec; class gp_Vec2d; class math_Matrix; //! BSplCLib B-spline curve Library. //! //! The BSplCLib package is a basic library for BSplines. It //! provides three categories of functions. //! //! * Management methods to process knots and multiplicities. //! //! * Multi-Dimensions spline methods. BSpline methods where //! poles have an arbitrary number of dimensions. They divides //! in two groups : //! //! - Global methods modifying the whole set of poles. The //! poles are described by an array of Reals and a //! Dimension. Example : Inserting knots. //! //! - Local methods computing points and derivatives. The //! poles are described by a pointer on a local array of //! Reals and a Dimension. The local array is modified. //! //! * 2D and 3D spline curves methods. //! //! Methods for 2d and 3d BSplines curves rational or not //! rational. //! //! Those methods have the following structure : //! //! - They extract the pole information in a working array. //! //! - They process the working array with the //! multi-dimension methods. (for example a 3d rational //! curve is processed as a 4 dimension curve). //! //! - They get back the result in the original dimension. //! //! Note that the bspline surface methods found in the //! package BSplSLib uses the same structure and rely on //! BSplCLib. //! //! In the following list of methods the 2d and 3d curve //! methods will be described with the corresponding //! multi-dimension method. //! //! The 3d or 2d B-spline curve is defined with : //! //! . its control points : TColgp_Array1OfPnt(2d) Poles //! . its weights : TColStd_Array1OfReal Weights //! . its knots : TColStd_Array1OfReal Knots //! . its multiplicities : TColStd_Array1OfInteger Mults //! . its degree : Standard_Integer Degree //! . its periodicity : Standard_Boolean Periodic //! //! Warnings : //! The bounds of Poles and Weights should be the same. //! The bounds of Knots and Mults should be the same. //! //! Note: weight and multiplicity arrays can be passed by pointer for //! some functions so that NULL pointer is valid. //! That means no weights/no multiplicities passed. //! //! No weights (BSplCLib::NoWeights()) means the curve is non rational. //! No mults (BSplCLib::NoMults()) means the knots are "flat" knots. //! //! KeyWords : //! B-spline curve, Functions, Library //! //! References : //! . A survey of curves and surfaces methods in CADG Wolfgang //! BOHM CAGD 1 (1984) //! . On de Boor-like algorithms and blossoming Wolfgang BOEHM //! cagd 5 (1988) //! . Blossoming and knot insertion algorithms for B-spline curves //! Ronald N. GOLDMAN //! . Modelisation des surfaces en CAO, Henri GIAUME Peugeot SA //! . Curves and Surfaces for Computer Aided Geometric Design, //! a practical guide Gerald Farin class BSplCLib { public: DEFINE_STANDARD_ALLOC //! This routine searches the position of the real value theX //! in the monotonically increasing set of real values theArray using bisection algorithm. //! //! If the given value is out of range or array values, algorithm returns either //! theArray.Lower()-1 or theArray.Upper()+1 depending on theX position in the ordered set. //! //! This routine is used to locate a knot value in a set of knots. Standard_EXPORT static void Hunt (const TColStd_Array1OfReal& theArray, const Standard_Real theX, Standard_Integer& theXPos); //! Computes the index of the knots value which gives //! the start point of the curve. Standard_EXPORT static Standard_Integer FirstUKnotIndex (const Standard_Integer Degree, const TColStd_Array1OfInteger& Mults); //! Computes the index of the knots value which gives //! the end point of the curve. Standard_EXPORT static Standard_Integer LastUKnotIndex (const Standard_Integer Degree, const TColStd_Array1OfInteger& Mults); //! Computes the index of the flats knots sequence //! corresponding to <Index> in the knots sequence //! which multiplicities are <Mults>. Standard_EXPORT static Standard_Integer FlatIndex (const Standard_Integer Degree, const Standard_Integer Index, const TColStd_Array1OfInteger& Mults, const Standard_Boolean Periodic); //! Locates the parametric value U in the knots //! sequence between the knot K1 and the knot K2. //! The value return in Index verifies. //! //! Knots(Index) <= U < Knots(Index + 1) //! if U <= Knots (K1) then Index = K1 //! if U >= Knots (K2) then Index = K2 - 1 //! //! If Periodic is True U may be modified to fit in //! the range Knots(K1), Knots(K2). In any case the //! correct value is returned in NewU. //! //! Warnings :Index is used as input data to initialize the //! searching function. //! Warning: Knots have to be "withe repetitions" Standard_EXPORT static void LocateParameter (const Standard_Integer Degree, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const Standard_Real U, const Standard_Boolean IsPeriodic, const Standard_Integer FromK1, const Standard_Integer ToK2, Standard_Integer& KnotIndex, Standard_Real& NewU); //! Locates the parametric value U in the knots //! sequence between the knot K1 and the knot K2. //! The value return in Index verifies. //! //! Knots(Index) <= U < Knots(Index + 1) //! if U <= Knots (K1) then Index = K1 //! if U >= Knots (K2) then Index = K2 - 1 //! //! If Periodic is True U may be modified to fit in //! the range Knots(K1), Knots(K2). In any case the //! correct value is returned in NewU. //! //! Warnings :Index is used as input data to initialize the //! searching function. //! Warning: Knots have to be "flat" Standard_EXPORT static void LocateParameter (const Standard_Integer Degree, const TColStd_Array1OfReal& Knots, const Standard_Real U, const Standard_Boolean IsPeriodic, const Standard_Integer FromK1, const Standard_Integer ToK2, Standard_Integer& KnotIndex, Standard_Real& NewU); Standard_EXPORT static void LocateParameter (const Standard_Integer Degree, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, const Standard_Real U, const Standard_Boolean Periodic, Standard_Integer& Index, Standard_Real& NewU); //! Finds the greatest multiplicity in a set of knots //! between K1 and K2. Mults is the multiplicity //! associated with each knot value. Standard_EXPORT static Standard_Integer MaxKnotMult (const TColStd_Array1OfInteger& Mults, const Standard_Integer K1, const Standard_Integer K2); //! Finds the lowest multiplicity in a set of knots //! between K1 and K2. Mults is the multiplicity //! associated with each knot value. Standard_EXPORT static Standard_Integer MinKnotMult (const TColStd_Array1OfInteger& Mults, const Standard_Integer K1, const Standard_Integer K2); //! Returns the number of poles of the curve. Returns 0 if //! one of the multiplicities is incorrect. //! //! * Non positive. //! //! * Greater than Degree, or Degree+1 at the first and //! last knot of a non periodic curve. //! //! * The last periodicity on a periodic curve is not //! equal to the first. Standard_EXPORT static Standard_Integer NbPoles (const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfInteger& Mults); //! Returns the length of the sequence of knots with //! repetition. //! //! Periodic : //! //! Sum(Mults(i), i = Mults.Lower(); i <= Mults.Upper()); //! //! Non Periodic : //! //! Sum(Mults(i); i = Mults.Lower(); i < Mults.Upper()) //! + 2 * Degree Standard_EXPORT static Standard_Integer KnotSequenceLength (const TColStd_Array1OfInteger& Mults, const Standard_Integer Degree, const Standard_Boolean Periodic); Standard_EXPORT static void KnotSequence (const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColStd_Array1OfReal& KnotSeq, const Standard_Boolean Periodic = Standard_False); //! Computes the sequence of knots KnotSeq with //! repetition of the knots of multiplicity greater //! than 1. //! //! Length of KnotSeq must be KnotSequenceLength(Mults,Degree,Periodic) Standard_EXPORT static void KnotSequence (const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const Standard_Integer Degree, const Standard_Boolean Periodic, TColStd_Array1OfReal& KnotSeq); //! Returns the length of the sequence of knots (and //! Mults) without repetition. Standard_EXPORT static Standard_Integer KnotsLength (const TColStd_Array1OfReal& KnotSeq, const Standard_Boolean Periodic = Standard_False); //! Computes the sequence of knots Knots without //! repetition of the knots of multiplicity greater //! than 1. //! //! Length of <Knots> and <Mults> must be //! KnotsLength(KnotSequence,Periodic) Standard_EXPORT static void Knots (const TColStd_Array1OfReal& KnotSeq, TColStd_Array1OfReal& Knots, TColStd_Array1OfInteger& Mults, const Standard_Boolean Periodic = Standard_False); //! Analyses if the knots distribution is "Uniform" //! or "NonUniform" between the knot FromK1 and the //! knot ToK2. There is no repetition of knot in the //! knots'sequence <Knots>. Standard_EXPORT static BSplCLib_KnotDistribution KnotForm (const TColStd_Array1OfReal& Knots, const Standard_Integer FromK1, const Standard_Integer ToK2); //! Analyses the distribution of multiplicities between //! the knot FromK1 and the Knot ToK2. Standard_EXPORT static BSplCLib_MultDistribution MultForm (const TColStd_Array1OfInteger& Mults, const Standard_Integer FromK1, const Standard_Integer ToK2); //! Analyzes the array of knots. //! Returns the form and the maximum knot multiplicity. Standard_EXPORT static void KnotAnalysis (const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& CKnots, const TColStd_Array1OfInteger& CMults, GeomAbs_BSplKnotDistribution& KnotForm, Standard_Integer& MaxKnotMult); //! Reparametrizes a B-spline curve to [U1, U2]. //! The knot values are recomputed such that Knots (Lower) = U1 //! and Knots (Upper) = U2 but the knot form is not modified. //! Warnings : //! In the array Knots the values must be in ascending order. //! U1 must not be equal to U2 to avoid division by zero. Standard_EXPORT static void Reparametrize (const Standard_Real U1, const Standard_Real U2, TColStd_Array1OfReal& Knots); //! Reverses the array knots to become the knots //! sequence of the reversed curve. Standard_EXPORT static void Reverse (TColStd_Array1OfReal& Knots); //! Reverses the array of multiplicities. Standard_EXPORT static void Reverse (TColStd_Array1OfInteger& Mults); //! Reverses the array of poles. Last is the index of //! the new first pole. On a non periodic curve last //! is Poles.Upper(). On a periodic curve last is //! //! (number of flat knots - degree - 1) //! //! or //! //! (sum of multiplicities(but for the last) + degree //! - 1) Standard_EXPORT static void Reverse (TColgp_Array1OfPnt& Poles, const Standard_Integer Last); //! Reverses the array of poles. Standard_EXPORT static void Reverse (TColgp_Array1OfPnt2d& Poles, const Standard_Integer Last); //! Reverses the array of poles. Standard_EXPORT static void Reverse (TColStd_Array1OfReal& Weights, const Standard_Integer Last); //! Returns False if all the weights of the array <Weights> //! between I1 an I2 are identic. Epsilon is used for //! comparing weights. If Epsilon is 0. the Epsilon of the //! first weight is used. Standard_EXPORT static Standard_Boolean IsRational (const TColStd_Array1OfReal& Weights, const Standard_Integer I1, const Standard_Integer I2, const Standard_Real Epsilon = 0.0); //! returns the degree maxima for a BSplineCurve. static Standard_Integer MaxDegree(); //! Perform the Boor algorithm to evaluate a point at //! parameter <U>, with <Degree> and <Dimension>. //! //! Poles is an array of Reals of size //! //! <Dimension> * <Degree>+1 //! //! Containing the poles. At the end <Poles> contains //! the current point. Standard_EXPORT static void Eval (const Standard_Real U, const Standard_Integer Degree, Standard_Real& Knots, const Standard_Integer Dimension, Standard_Real& Poles); //! Performs the Boor Algorithm at parameter <U> with //! the given <Degree> and the array of <Knots> on the //! poles <Poles> of dimension <Dimension>. The schema //! is computed until level <Depth> on a basis of //! <Length+1> poles. //! //! * Knots is an array of reals of length : //! //! <Length> + <Degree> //! //! * Poles is an array of reals of length : //! //! (2 * <Length> + 1) * <Dimension> //! //! The poles values must be set in the array at the //! positions. //! //! 0..Dimension, //! //! 2 * Dimension .. //! 3 * Dimension //! //! 4 * Dimension .. //! 5 * Dimension //! //! ... //! //! The results are found in the array poles depending //! on the Depth. (See the method GetPole). Standard_EXPORT static void BoorScheme (const Standard_Real U, const Standard_Integer Degree, Standard_Real& Knots, const Standard_Integer Dimension, Standard_Real& Poles, const Standard_Integer Depth, const Standard_Integer Length); //! Compute the content of Pole before the BoorScheme. //! This method is used to remove poles. //! //! U is the poles to remove, Knots should contains the //! knots of the curve after knot removal. //! //! The first and last poles do not change, the other //! poles are computed by averaging two possible values. //! The distance between the two possible poles is //! computed, if it is higher than <Tolerance> False is //! returned. Standard_EXPORT static Standard_Boolean AntiBoorScheme (const Standard_Real U, const Standard_Integer Degree, Standard_Real& Knots, const Standard_Integer Dimension, Standard_Real& Poles, const Standard_Integer Depth, const Standard_Integer Length, const Standard_Real Tolerance); //! Computes the poles of the BSpline giving the //! derivatives of order <Order>. //! //! The formula for the first order is //! //! Pole(i) = Degree * (Pole(i+1) - Pole(i)) / //! (Knots(i+Degree+1) - Knots(i+1)) //! //! This formula is repeated (Degree is decremented at //! each step). Standard_EXPORT static void Derivative (const Standard_Integer Degree, Standard_Real& Knots, const Standard_Integer Dimension, const Standard_Integer Length, const Standard_Integer Order, Standard_Real& Poles); //! Performs the Bohm Algorithm at parameter <U>. This //! algorithm computes the value and all the derivatives //! up to order N (N <= Degree). //! //! <Poles> is the original array of poles. //! //! The result in <Poles> is the value and the //! derivatives. Poles[0] is the value, Poles[Degree] //! is the last derivative. Standard_EXPORT static void Bohm (const Standard_Real U, const Standard_Integer Degree, const Standard_Integer N, Standard_Real& Knots, const Standard_Integer Dimension, Standard_Real& Poles); //! Used as argument for a non rational curve. static TColStd_Array1OfReal* NoWeights(); //! Used as argument for a flatknots evaluation. static TColStd_Array1OfInteger* NoMults(); //! Stores in LK the useful knots for the BoorSchem //! on the span Knots(Index) - Knots(Index+1) Standard_EXPORT static void BuildKnots (const Standard_Integer Degree, const Standard_Integer Index, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, Standard_Real& LK); //! Return the index of the first Pole to use on the //! span Mults(Index) - Mults(Index+1). This index //! must be added to Poles.Lower(). Standard_EXPORT static Standard_Integer PoleIndex (const Standard_Integer Degree, const Standard_Integer Index, const Standard_Boolean Periodic, const TColStd_Array1OfInteger& Mults); Standard_EXPORT static void BuildEval (const Standard_Integer Degree, const Standard_Integer Index, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal* Weights, Standard_Real& LP); Standard_EXPORT static void BuildEval (const Standard_Integer Degree, const Standard_Integer Index, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, Standard_Real& LP); //! Copy in <LP> the poles and weights for the Eval //! scheme. starting from Poles(Poles.Lower()+Index) Standard_EXPORT static void BuildEval (const Standard_Integer Degree, const Standard_Integer Index, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, Standard_Real& LP); //! Copy in <LP> poles for <Dimension> Boor scheme. //! Starting from <Index> * <Dimension>, copy //! <Length+1> poles. Standard_EXPORT static void BuildBoor (const Standard_Integer Index, const Standard_Integer Length, const Standard_Integer Dimension, const TColStd_Array1OfReal& Poles, Standard_Real& LP); //! Returns the index in the Boor result array of the //! poles <Index>. If the Boor algorithm was perform //! with <Length> and <Depth>. Standard_EXPORT static Standard_Integer BoorIndex (const Standard_Integer Index, const Standard_Integer Length, const Standard_Integer Depth); //! Copy the pole at position <Index> in the Boor //! scheme of dimension <Dimension> to <Position> in //! the array <Pole>. <Position> is updated. Standard_EXPORT static void GetPole (const Standard_Integer Index, const Standard_Integer Length, const Standard_Integer Depth, const Standard_Integer Dimension, Standard_Real& LocPoles, Standard_Integer& Position, TColStd_Array1OfReal& Pole); //! Returns in <NbPoles, NbKnots> the new number of poles //! and knots if the sequence of knots <AddKnots, //! AddMults> is inserted in the sequence <Knots, Mults>. //! //! Epsilon is used to compare knots for equality. //! //! If Add is True the multiplicities on equal knots are //! added. //! //! If Add is False the max value of the multiplicities is //! kept. //! //! Return False if : //! The knew knots are knot increasing. //! The new knots are not in the range. Standard_EXPORT static Standard_Boolean PrepareInsertKnots (const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const TColStd_Array1OfReal& AddKnots, const TColStd_Array1OfInteger* AddMults, Standard_Integer& NbPoles, Standard_Integer& NbKnots, const Standard_Real Epsilon, const Standard_Boolean Add = Standard_True); Standard_EXPORT static void InsertKnots (const Standard_Integer Degree, const Standard_Boolean Periodic, const Standard_Integer Dimension, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const TColStd_Array1OfReal& AddKnots, const TColStd_Array1OfInteger* AddMults, TColStd_Array1OfReal& NewPoles, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, const Standard_Real Epsilon, const Standard_Boolean Add = Standard_True); Standard_EXPORT static void InsertKnots (const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const TColStd_Array1OfReal& AddKnots, const TColStd_Array1OfInteger* AddMults, TColgp_Array1OfPnt& NewPoles, TColStd_Array1OfReal* NewWeights, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, const Standard_Real Epsilon, const Standard_Boolean Add = Standard_True); //! Insert a sequence of knots <AddKnots> with //! multiplicities <AddMults>. <AddKnots> must be a non //! decreasing sequence and verifies : //! //! Knots(Knots.Lower()) <= AddKnots(AddKnots.Lower()) //! Knots(Knots.Upper()) >= AddKnots(AddKnots.Upper()) //! //! The NewPoles and NewWeights arrays must have a length : //! Poles.Length() + Sum(AddMults()) //! //! When a knot to insert is identic to an existing knot the //! multiplicities are added. //! //! Epsilon is used to test knots for equality. //! //! When AddMult is negative or null the knot is not inserted. //! No multiplicity will becomes higher than the degree. //! //! The new Knots and Multiplicities are copied in <NewKnots> //! and <NewMults>. //! //! All the New arrays should be correctly dimensioned. //! //! When all the new knots are existing knots, i.e. only the //! multiplicities will change it is safe to use the same //! arrays as input and output. Standard_EXPORT static void InsertKnots (const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const TColStd_Array1OfReal& AddKnots, const TColStd_Array1OfInteger* AddMults, TColgp_Array1OfPnt2d& NewPoles, TColStd_Array1OfReal* NewWeights, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, const Standard_Real Epsilon, const Standard_Boolean Add = Standard_True); Standard_EXPORT static void InsertKnot (const Standard_Integer UIndex, const Standard_Real U, const Standard_Integer UMult, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColgp_Array1OfPnt& NewPoles, TColStd_Array1OfReal* NewWeights); //! Insert a new knot U of multiplicity UMult in the //! knot sequence. //! //! The location of the new Knot should be given as an input //! data. UIndex locates the new knot U in the knot sequence //! and Knots (UIndex) < U < Knots (UIndex + 1). //! //! The new control points corresponding to this insertion are //! returned. Knots and Mults are not updated. Standard_EXPORT static void InsertKnot (const Standard_Integer UIndex, const Standard_Real U, const Standard_Integer UMult, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColgp_Array1OfPnt2d& NewPoles, TColStd_Array1OfReal* NewWeights); Standard_EXPORT static void RaiseMultiplicity (const Standard_Integer KnotIndex, const Standard_Integer Mult, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColgp_Array1OfPnt& NewPoles, TColStd_Array1OfReal* NewWeights); //! Raise the multiplicity of knot to <UMult>. //! //! The new control points are returned. Knots and Mults are //! not updated. Standard_EXPORT static void RaiseMultiplicity (const Standard_Integer KnotIndex, const Standard_Integer Mult, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColgp_Array1OfPnt2d& NewPoles, TColStd_Array1OfReal* NewWeights); Standard_EXPORT static Standard_Boolean RemoveKnot (const Standard_Integer Index, const Standard_Integer Mult, const Standard_Integer Degree, const Standard_Boolean Periodic, const Standard_Integer Dimension, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColStd_Array1OfReal& NewPoles, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, const Standard_Real Tolerance); Standard_EXPORT static Standard_Boolean RemoveKnot (const Standard_Integer Index, const Standard_Integer Mult, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColgp_Array1OfPnt& NewPoles, TColStd_Array1OfReal* NewWeights, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, const Standard_Real Tolerance); //! Decrement the multiplicity of <Knots(Index)> //! to <Mult>. If <Mult> is null the knot is //! removed. //! //! As there are two ways to compute the new poles //! the midlle will be used as long as the //! distance is lower than Tolerance. //! //! If a distance is bigger than tolerance the //! methods returns False and the new arrays are //! not modified. //! //! A low tolerance can be used to test if the //! knot can be removed without modifying the //! curve. //! //! A high tolerance can be used to "smooth" the //! curve. Standard_EXPORT static Standard_Boolean RemoveKnot (const Standard_Integer Index, const Standard_Integer Mult, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColgp_Array1OfPnt2d& NewPoles, TColStd_Array1OfReal* NewWeights, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, const Standard_Real Tolerance); //! Returns the number of knots of a curve with //! multiplicities <Mults> after elevating the degree from //! <Degree> to <NewDegree>. See the IncreaseDegree method //! for more comments. Standard_EXPORT static Standard_Integer IncreaseDegreeCountKnots (const Standard_Integer Degree, const Standard_Integer NewDegree, const Standard_Boolean Periodic, const TColStd_Array1OfInteger& Mults); Standard_EXPORT static void IncreaseDegree (const Standard_Integer Degree, const Standard_Integer NewDegree, const Standard_Boolean Periodic, const Standard_Integer Dimension, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColStd_Array1OfReal& NewPoles, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults); Standard_EXPORT static void IncreaseDegree (const Standard_Integer Degree, const Standard_Integer NewDegree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColgp_Array1OfPnt& NewPoles, TColStd_Array1OfReal* NewWeights, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults); Standard_EXPORT static void IncreaseDegree (const Standard_Integer Degree, const Standard_Integer NewDegree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, TColgp_Array1OfPnt2d& NewPoles, TColStd_Array1OfReal* NewWeights, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults); Standard_EXPORT static void IncreaseDegree (const Standard_Integer NewDegree, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, TColgp_Array1OfPnt& NewPoles, TColStd_Array1OfReal* NewWeights); //! Increase the degree of a bspline (or bezier) curve //! of dimension theDimension form theDegree to theNewDegree. //! //! The number of poles in the new curve is: //! @code //! Poles.Length() + (NewDegree - Degree) * Number of spans //! @endcode //! Where the number of spans is: //! @code //! LastUKnotIndex(Mults) - FirstUKnotIndex(Mults) + 1 //! @endcode //! for a non-periodic curve, and //! @code //! Knots.Length() - 1 //! @endcode //! for a periodic curve. //! //! The multiplicities of all knots are increased by the degree elevation. //! //! The new knots are usually the same knots with the //! exception of a non-periodic curve with the first //! and last multiplicity not equal to Degree+1 where //! knots are removed form the start and the bottom //! until the sum of the multiplicities is equal to //! NewDegree+1 at the knots corresponding to the //! first and last parameters of the curve. //! //! Example: Suppose a curve of degree 3 starting //! with following knots and multiplicities: //! @code //! knot : 0. 1. 2. //! mult : 1 2 1 //! @endcode //! //! The FirstUKnot is 2.0 because the sum of multiplicities is //! @code //! Degree+1 : 1 + 2 + 1 = 4 = 3 + 1 //! @endcode //! i.e. the first parameter of the curve is 2.0 and //! will still be 2.0 after degree elevation. //! Let raise this curve to degree 4. //! The multiplicities are increased by 2. //! //! They become 2 3 2. //! But we need a sum of multiplicities of 5 at knot 2. //! So the first knot is removed and the new knots are: //! @code //! knot : 1. 2. //! mult : 3 2 //! @endcode //! The multipicity of the first knot may also be reduced if the sum is still to big. //! //! In the most common situations (periodic curve or curve with first //! and last multiplicities equals to Degree+1) the knots are knot changes. //! //! The method IncreaseDegreeCountKnots can be used to compute the new number of knots. Standard_EXPORT static void IncreaseDegree (const Standard_Integer theNewDegree, const TColgp_Array1OfPnt2d& thePoles, const TColStd_Array1OfReal* theWeights, TColgp_Array1OfPnt2d& theNewPoles, TColStd_Array1OfReal* theNewWeights); //! Set in <NbKnots> and <NbPolesToAdd> the number of Knots and //! Poles of the NotPeriodic Curve identical at the //! periodic curve with a degree <Degree> , a //! knots-distribution with Multiplicities <Mults>. Standard_EXPORT static void PrepareUnperiodize (const Standard_Integer Degree, const TColStd_Array1OfInteger& Mults, Standard_Integer& NbKnots, Standard_Integer& NbPoles); Standard_EXPORT static void Unperiodize (const Standard_Integer Degree, const Standard_Integer Dimension, const TColStd_Array1OfInteger& Mults, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfReal& Poles, TColStd_Array1OfInteger& NewMults, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfReal& NewPoles); Standard_EXPORT static void Unperiodize (const Standard_Integer Degree, const TColStd_Array1OfInteger& Mults, const TColStd_Array1OfReal& Knots, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, TColStd_Array1OfInteger& NewMults, TColStd_Array1OfReal& NewKnots, TColgp_Array1OfPnt& NewPoles, TColStd_Array1OfReal* NewWeights); Standard_EXPORT static void Unperiodize (const Standard_Integer Degree, const TColStd_Array1OfInteger& Mults, const TColStd_Array1OfReal& Knots, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, TColStd_Array1OfInteger& NewMults, TColStd_Array1OfReal& NewKnots, TColgp_Array1OfPnt2d& NewPoles, TColStd_Array1OfReal* NewWeights); //! Set in <NbKnots> and <NbPoles> the number of Knots and //! Poles of the curve resulting from the trimming of the //! BSplinecurve defined with <degree>, <knots>, <mults> Standard_EXPORT static void PrepareTrimming (const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const Standard_Real U1, const Standard_Real U2, Standard_Integer& NbKnots, Standard_Integer& NbPoles); Standard_EXPORT static void Trimming (const Standard_Integer Degree, const Standard_Boolean Periodic, const Standard_Integer Dimension, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const TColStd_Array1OfReal& Poles, const Standard_Real U1, const Standard_Real U2, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, TColStd_Array1OfReal& NewPoles); Standard_EXPORT static void Trimming (const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const Standard_Real U1, const Standard_Real U2, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, TColgp_Array1OfPnt& NewPoles, TColStd_Array1OfReal* NewWeights); Standard_EXPORT static void Trimming (const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger& Mults, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const Standard_Real U1, const Standard_Real U2, TColStd_Array1OfReal& NewKnots, TColStd_Array1OfInteger& NewMults, TColgp_Array1OfPnt2d& NewPoles, TColStd_Array1OfReal* NewWeights); Standard_EXPORT static void D0 (const Standard_Real U, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, Standard_Real& P); Standard_EXPORT static void D0 (const Standard_Real U, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Pnt& P); Standard_EXPORT static void D0 (const Standard_Real U, const Standard_Integer UIndex, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Pnt2d& P); Standard_EXPORT static void D0 (const Standard_Real U, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& P); Standard_EXPORT static void D0 (const Standard_Real U, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& P); Standard_EXPORT static void D1 (const Standard_Real U, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, Standard_Real& P, Standard_Real& V); Standard_EXPORT static void D1 (const Standard_Real U, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Pnt& P, gp_Vec& V); Standard_EXPORT static void D1 (const Standard_Real U, const Standard_Integer UIndex, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Pnt2d& P, gp_Vec2d& V); Standard_EXPORT static void D1 (const Standard_Real U, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& P, gp_Vec& V); Standard_EXPORT static void D1 (const Standard_Real U, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& P, gp_Vec2d& V); Standard_EXPORT static void D2 (const Standard_Real U, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, Standard_Real& P, Standard_Real& V1, Standard_Real& V2); Standard_EXPORT static void D2 (const Standard_Real U, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2); Standard_EXPORT static void D2 (const Standard_Real U, const Standard_Integer UIndex, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2); Standard_EXPORT static void D2 (const Standard_Real U, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2); Standard_EXPORT static void D2 (const Standard_Real U, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2); Standard_EXPORT static void D3 (const Standard_Real U, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, Standard_Real& P, Standard_Real& V1, Standard_Real& V2, Standard_Real& V3); Standard_EXPORT static void D3 (const Standard_Real U, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2, gp_Vec& V3); Standard_EXPORT static void D3 (const Standard_Real U, const Standard_Integer UIndex, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3); Standard_EXPORT static void D3 (const Standard_Real U, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2, gp_Vec& V3); Standard_EXPORT static void D3 (const Standard_Real U, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3); Standard_EXPORT static void DN (const Standard_Real U, const Standard_Integer N, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, Standard_Real& VN); Standard_EXPORT static void DN (const Standard_Real U, const Standard_Integer N, const Standard_Integer Index, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Vec& VN); Standard_EXPORT static void DN (const Standard_Real U, const Standard_Integer N, const Standard_Integer UIndex, const Standard_Integer Degree, const Standard_Boolean Periodic, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& Knots, const TColStd_Array1OfInteger* Mults, gp_Vec2d& V); Standard_EXPORT static void DN (const Standard_Real U, const Standard_Integer N, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal& Weights, gp_Pnt& P, gp_Vec& VN); //! The above functions compute values and //! derivatives in the following situations : //! //! * 3D, 2D and 1D //! //! * Rational or not Rational. //! //! * Knots and multiplicities or "flat knots" without //! multiplicities. //! //! * The <Index> is the localization of the //! parameter in the knot sequence. If <Index> is out //! of range the correct value will be searched. //! //! VERY IMPORTANT!!! //! USE BSplCLib::NoWeights() as Weights argument for non //! rational curves computations. Standard_EXPORT static void DN (const Standard_Real U, const Standard_Integer N, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal& Weights, gp_Pnt2d& P, gp_Vec2d& VN); //! This evaluates the Bspline Basis at a //! given parameter Parameter up to the //! requested DerivativeOrder and store the //! result in the array BsplineBasis in the //! following fashion //! BSplineBasis(1,1) = //! value of first non vanishing //! Bspline function which has Index FirstNonZeroBsplineIndex //! BsplineBasis(1,2) = //! value of second non vanishing //! Bspline function which has Index //! FirstNonZeroBsplineIndex + 1 //! BsplineBasis(1,n) = //! value of second non vanishing non vanishing //! Bspline function which has Index //! FirstNonZeroBsplineIndex + n (n <= Order) //! BSplineBasis(2,1) = //! value of derivative of first non vanishing //! Bspline function which has Index FirstNonZeroBsplineIndex //! BSplineBasis(N,1) = //! value of Nth derivative of first non vanishing //! Bspline function which has Index FirstNonZeroBsplineIndex //! if N <= DerivativeOrder + 1 Standard_EXPORT static Standard_Integer EvalBsplineBasis (const Standard_Integer DerivativeOrder, const Standard_Integer Order, const TColStd_Array1OfReal& FlatKnots, const Standard_Real Parameter, Standard_Integer& FirstNonZeroBsplineIndex, math_Matrix& BsplineBasis, const Standard_Boolean isPeriodic = Standard_False); //! This Builds a fully blown Matrix of //! (ni) //! Bi (tj) //! //! with i and j within 1..Order + NumPoles //! The integer ni is the ith slot of the //! array OrderArray, tj is the jth slot of //! the array Parameters Standard_EXPORT static Standard_Integer BuildBSpMatrix (const TColStd_Array1OfReal& Parameters, const TColStd_Array1OfInteger& OrderArray, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer Degree, math_Matrix& Matrix, Standard_Integer& UpperBandWidth, Standard_Integer& LowerBandWidth); //! this factors the Banded Matrix in //! the LU form with a Banded storage of //! components of the L matrix //! WARNING : do not use if the Matrix is //! totally positive (It is the case for //! Bspline matrices build as above with //! parameters being the Schoenberg points Standard_EXPORT static Standard_Integer FactorBandedMatrix (math_Matrix& Matrix, const Standard_Integer UpperBandWidth, const Standard_Integer LowerBandWidth, Standard_Integer& PivotIndexProblem); //! This solves the system Matrix.X = B //! with when Matrix is factored in LU form //! The Array is an seen as an //! Array[1..N][1..ArrayDimension] with N = //! the rank of the matrix Matrix. The //! result is stored in Array when each //! coordinate is solved that is B is the //! array whose values are //! B[i] = Array[i][p] for each p in 1..ArrayDimension Standard_EXPORT static Standard_Integer SolveBandedSystem (const math_Matrix& Matrix, const Standard_Integer UpperBandWidth, const Standard_Integer LowerBandWidth, const Standard_Integer ArrayDimension, Standard_Real& Array); //! This solves the system Matrix.X = B //! with when Matrix is factored in LU form //! The Array has the length of //! the rank of the matrix Matrix. The //! result is stored in Array when each //! coordinate is solved that is B is the //! array whose values are //! B[i] = Array[i][p] for each p in 1..ArrayDimension Standard_EXPORT static Standard_Integer SolveBandedSystem (const math_Matrix& Matrix, const Standard_Integer UpperBandWidth, const Standard_Integer LowerBandWidth, TColgp_Array1OfPnt2d& Array); //! This solves the system Matrix.X = B //! with when Matrix is factored in LU form //! The Array has the length of //! the rank of the matrix Matrix. The //! result is stored in Array when each //! coordinate is solved that is B is the //! array whose values are //! B[i] = Array[i][p] for each p in 1..ArrayDimension Standard_EXPORT static Standard_Integer SolveBandedSystem (const math_Matrix& Matrix, const Standard_Integer UpperBandWidth, const Standard_Integer LowerBandWidth, TColgp_Array1OfPnt& Array); Standard_EXPORT static Standard_Integer SolveBandedSystem (const math_Matrix& Matrix, const Standard_Integer UpperBandWidth, const Standard_Integer LowerBandWidth, const Standard_Boolean HomogenousFlag, const Standard_Integer ArrayDimension, Standard_Real& Array, Standard_Real& Weights); //! This solves the system Matrix.X = B //! with when Matrix is factored in LU form //! The Array is an seen as an //! Array[1..N][1..ArrayDimension] with N = //! the rank of the matrix Matrix. The //! result is stored in Array when each //! coordinate is solved that is B is the //! array whose values are B[i] = //! Array[i][p] for each p in //! 1..ArrayDimension. If HomogeneousFlag == //! 0 the Poles are multiplied by the //! Weights upon Entry and once //! interpolation is carried over the //! result of the poles are divided by the //! result of the interpolation of the //! weights. Otherwise if HomogenousFlag == 1 //! the Poles and Weigths are treated homogeneously //! that is that those are interpolated as they //! are and result is returned without division //! by the interpolated weigths. Standard_EXPORT static Standard_Integer SolveBandedSystem (const math_Matrix& Matrix, const Standard_Integer UpperBandWidth, const Standard_Integer LowerBandWidth, const Standard_Boolean HomogenousFlag, TColgp_Array1OfPnt2d& Array, TColStd_Array1OfReal& Weights); //! This solves the system Matrix.X = B //! with when Matrix is factored in LU form //! The Array is an seen as an //! Array[1..N][1..ArrayDimension] with N = //! the rank of the matrix Matrix. The //! result is stored in Array when each //! coordinate is solved that is B is the //! array whose values are //! B[i] = Array[i][p] for each p in 1..ArrayDimension //! If HomogeneousFlag == //! 0 the Poles are multiplied by the //! Weights upon Entry and once //! interpolation is carried over the //! result of the poles are divided by the //! result of the interpolation of the //! weights. Otherwise if HomogenousFlag == 1 //! the Poles and Weigths are treated homogeneously //! that is that those are interpolated as they //! are and result is returned without division //! by the interpolated weigths. Standard_EXPORT static Standard_Integer SolveBandedSystem (const math_Matrix& Matrix, const Standard_Integer UpperBandWidth, const Standard_Integer LowerBandWidth, const Standard_Boolean HomogeneousFlag, TColgp_Array1OfPnt& Array, TColStd_Array1OfReal& Weights); //! Merges two knot vector by setting the starting and //! ending values to StartValue and EndValue Standard_EXPORT static void MergeBSplineKnots (const Standard_Real Tolerance, const Standard_Real StartValue, const Standard_Real EndValue, const Standard_Integer Degree1, const TColStd_Array1OfReal& Knots1, const TColStd_Array1OfInteger& Mults1, const Standard_Integer Degree2, const TColStd_Array1OfReal& Knots2, const TColStd_Array1OfInteger& Mults2, Standard_Integer& NumPoles, Handle(TColStd_HArray1OfReal)& NewKnots, Handle(TColStd_HArray1OfInteger)& NewMults); //! This function will compose a given Vectorial BSpline F(t) //! defined by its BSplineDegree and BSplineFlatKnotsl, //! its Poles array which are coded as an array of Real //! of the form [1..NumPoles][1..PolesDimension] with a //! function a(t) which is assumed to satisfy the //! following: //! //! 1. F(a(t)) is a polynomial BSpline //! that can be expressed exactly as a BSpline of degree //! NewDegree on the knots FlatKnots //! //! 2. a(t) defines a differentiable //! isomorphism between the range of FlatKnots to the range //! of BSplineFlatKnots which is the //! same as the range of F(t) //! //! Warning: it is //! the caller's responsibility to insure that conditions //! 1. and 2. above are satisfied : no check whatsoever //! is made in this method //! //! theStatus will return 0 if OK else it will return the pivot index //! of the matrix that was inverted to compute the multiplied //! BSpline : the method used is interpolation at Schoenenberg //! points of F(a(t)) Standard_EXPORT static void FunctionReparameterise (const BSplCLib_EvaluatorFunction& Function, const Standard_Integer BSplineDegree, const TColStd_Array1OfReal& BSplineFlatKnots, const Standard_Integer PolesDimension, Standard_Real& Poles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer NewDegree, Standard_Real& NewPoles, Standard_Integer& theStatus); //! This function will compose a given Vectorial BSpline F(t) //! defined by its BSplineDegree and BSplineFlatKnotsl, //! its Poles array which are coded as an array of Real //! of the form [1..NumPoles][1..PolesDimension] with a //! function a(t) which is assumed to satisfy the //! following: //! //! 1. F(a(t)) is a polynomial BSpline //! that can be expressed exactly as a BSpline of degree //! NewDegree on the knots FlatKnots //! //! 2. a(t) defines a differentiable //! isomorphism between the range of FlatKnots to the range //! of BSplineFlatKnots which is the //! same as the range of F(t) //! //! Warning: it is //! the caller's responsibility to insure that conditions //! 1. and 2. above are satisfied : no check whatsoever //! is made in this method //! //! theStatus will return 0 if OK else it will return the pivot index //! of the matrix that was inverted to compute the multiplied //! BSpline : the method used is interpolation at Schoenenberg //! points of F(a(t)) Standard_EXPORT static void FunctionReparameterise (const BSplCLib_EvaluatorFunction& Function, const Standard_Integer BSplineDegree, const TColStd_Array1OfReal& BSplineFlatKnots, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer NewDegree, TColStd_Array1OfReal& NewPoles, Standard_Integer& theStatus); //! this will compose a given Vectorial BSpline F(t) //! defined by its BSplineDegree and BSplineFlatKnotsl, //! its Poles array which are coded as an array of Real //! of the form [1..NumPoles][1..PolesDimension] with a //! function a(t) which is assumed to satisfy the //! following : 1. F(a(t)) is a polynomial BSpline //! that can be expressed exactly as a BSpline of degree //! NewDegree on the knots FlatKnots //! 2. a(t) defines a differentiable //! isomorphism between the range of FlatKnots to the range //! of BSplineFlatKnots which is the //! same as the range of F(t) //! Warning: it is //! the caller's responsibility to insure that conditions //! 1. and 2. above are satisfied : no check whatsoever //! is made in this method //! theStatus will return 0 if OK else it will return the pivot index //! of the matrix that was inverted to compute the multiplied //! BSpline : the method used is interpolation at Schoenenberg //! points of F(a(t)) Standard_EXPORT static void FunctionReparameterise (const BSplCLib_EvaluatorFunction& Function, const Standard_Integer BSplineDegree, const TColStd_Array1OfReal& BSplineFlatKnots, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer NewDegree, TColgp_Array1OfPnt& NewPoles, Standard_Integer& theStatus); //! this will compose a given Vectorial BSpline F(t) //! defined by its BSplineDegree and BSplineFlatKnotsl, //! its Poles array which are coded as an array of Real //! of the form [1..NumPoles][1..PolesDimension] with a //! function a(t) which is assumed to satisfy the //! following : 1. F(a(t)) is a polynomial BSpline //! that can be expressed exactly as a BSpline of degree //! NewDegree on the knots FlatKnots //! 2. a(t) defines a differentiable //! isomorphism between the range of FlatKnots to the range //! of BSplineFlatKnots which is the //! same as the range of F(t) //! Warning: it is //! the caller's responsibility to insure that conditions //! 1. and 2. above are satisfied : no check whatsoever //! is made in this method //! theStatus will return 0 if OK else it will return the pivot index //! of the matrix that was inverted to compute the multiplied //! BSpline : the method used is interpolation at Schoenenberg //! points of F(a(t)) Standard_EXPORT static void FunctionReparameterise (const BSplCLib_EvaluatorFunction& Function, const Standard_Integer BSplineDegree, const TColStd_Array1OfReal& BSplineFlatKnots, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer NewDegree, TColgp_Array1OfPnt2d& NewPoles, Standard_Integer& theStatus); //! this will multiply a given Vectorial BSpline F(t) //! defined by its BSplineDegree and BSplineFlatKnotsl, //! its Poles array which are coded as an array of Real //! of the form [1..NumPoles][1..PolesDimension] by a //! function a(t) which is assumed to satisfy the //! following : 1. a(t) * F(t) is a polynomial BSpline //! that can be expressed exactly as a BSpline of degree //! NewDegree on the knots FlatKnots 2. the range of a(t) //! is the same as the range of F(t) //! Warning: it is //! the caller's responsibility to insure that conditions //! 1. and 2. above are satisfied : no check whatsoever //! is made in this method //! theStatus will return 0 if OK else it will return the pivot index //! of the matrix that was inverted to compute the multiplied //! BSpline : the method used is interpolation at Schoenenberg //! points of a(t)*F(t) Standard_EXPORT static void FunctionMultiply (const BSplCLib_EvaluatorFunction& Function, const Standard_Integer BSplineDegree, const TColStd_Array1OfReal& BSplineFlatKnots, const Standard_Integer PolesDimension, Standard_Real& Poles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer NewDegree, Standard_Real& NewPoles, Standard_Integer& theStatus); //! this will multiply a given Vectorial BSpline F(t) //! defined by its BSplineDegree and BSplineFlatKnotsl, //! its Poles array which are coded as an array of Real //! of the form [1..NumPoles][1..PolesDimension] by a //! function a(t) which is assumed to satisfy the //! following : 1. a(t) * F(t) is a polynomial BSpline //! that can be expressed exactly as a BSpline of degree //! NewDegree on the knots FlatKnots 2. the range of a(t) //! is the same as the range of F(t) //! Warning: it is //! the caller's responsibility to insure that conditions //! 1. and 2. above are satisfied : no check whatsoever //! is made in this method //! theStatus will return 0 if OK else it will return the pivot index //! of the matrix that was inverted to compute the multiplied //! BSpline : the method used is interpolation at Schoenenberg //! points of a(t)*F(t) Standard_EXPORT static void FunctionMultiply (const BSplCLib_EvaluatorFunction& Function, const Standard_Integer BSplineDegree, const TColStd_Array1OfReal& BSplineFlatKnots, const TColStd_Array1OfReal& Poles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer NewDegree, TColStd_Array1OfReal& NewPoles, Standard_Integer& theStatus); //! this will multiply a given Vectorial BSpline F(t) //! defined by its BSplineDegree and BSplineFlatKnotsl, //! its Poles array which are coded as an array of Real //! of the form [1..NumPoles][1..PolesDimension] by a //! function a(t) which is assumed to satisfy the //! following : 1. a(t) * F(t) is a polynomial BSpline //! that can be expressed exactly as a BSpline of degree //! NewDegree on the knots FlatKnots 2. the range of a(t) //! is the same as the range of F(t) //! Warning: it is //! the caller's responsibility to insure that conditions //! 1. and 2. above are satisfied : no check whatsoever //! is made in this method //! theStatus will return 0 if OK else it will return the pivot index //! of the matrix that was inverted to compute the multiplied //! BSpline : the method used is interpolation at Schoenenberg //! points of a(t)*F(t) Standard_EXPORT static void FunctionMultiply (const BSplCLib_EvaluatorFunction& Function, const Standard_Integer BSplineDegree, const TColStd_Array1OfReal& BSplineFlatKnots, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer NewDegree, TColgp_Array1OfPnt2d& NewPoles, Standard_Integer& theStatus); //! this will multiply a given Vectorial BSpline F(t) //! defined by its BSplineDegree and BSplineFlatKnotsl, //! its Poles array which are coded as an array of Real //! of the form [1..NumPoles][1..PolesDimension] by a //! function a(t) which is assumed to satisfy the //! following : 1. a(t) * F(t) is a polynomial BSpline //! that can be expressed exactly as a BSpline of degree //! NewDegree on the knots FlatKnots 2. the range of a(t) //! is the same as the range of F(t) //! Warning: it is //! the caller's responsibility to insure that conditions //! 1. and 2. above are satisfied : no check whatsoever //! is made in this method //! theStatus will return 0 if OK else it will return the pivot index //! of the matrix that was inverted to compute the multiplied //! BSpline : the method used is interpolation at Schoenenberg //! points of a(t)*F(t) Standard_EXPORT static void FunctionMultiply (const BSplCLib_EvaluatorFunction& Function, const Standard_Integer BSplineDegree, const TColStd_Array1OfReal& BSplineFlatKnots, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer NewDegree, TColgp_Array1OfPnt& NewPoles, Standard_Integer& theStatus); //! Perform the De Boor algorithm to evaluate a point at //! parameter <U>, with <Degree> and <Dimension>. //! //! Poles is an array of Reals of size //! //! <Dimension> * <Degree>+1 //! //! Containing the poles. At the end <Poles> contains //! the current point. Poles Contain all the poles of //! the BsplineCurve, Knots also Contains all the knots //! of the BsplineCurve. ExtrapMode has two slots [0] = //! Degree used to extrapolate before the first knot [1] //! = Degre used to extrapolate after the last knot has //! to be between 1 and Degree Standard_EXPORT static void Eval (const Standard_Real U, const Standard_Boolean PeriodicFlag, const Standard_Integer DerivativeRequest, Standard_Integer& ExtrapMode, const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer ArrayDimension, Standard_Real& Poles, Standard_Real& Result); //! Perform the De Boor algorithm to evaluate a point at //! parameter <U>, with <Degree> and <Dimension>. //! Evaluates by multiplying the Poles by the Weights and //! gives the homogeneous result in PolesResult that is //! the results of the evaluation of the numerator once it //! has been multiplied by the weights and in //! WeightsResult one has the result of the evaluation of //! the denominator //! //! Warning: <PolesResult> and <WeightsResult> must be dimensionned //! properly. Standard_EXPORT static void Eval (const Standard_Real U, const Standard_Boolean PeriodicFlag, const Standard_Integer DerivativeRequest, Standard_Integer& ExtrapMode, const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer ArrayDimension, Standard_Real& Poles, Standard_Real& Weights, Standard_Real& PolesResult, Standard_Real& WeightsResult); //! Perform the evaluation of the Bspline Basis //! and then multiplies by the weights //! this just evaluates the current point Standard_EXPORT static void Eval (const Standard_Real U, const Standard_Boolean PeriodicFlag, const Standard_Boolean HomogeneousFlag, Standard_Integer& ExtrapMode, const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal& Weights, gp_Pnt& Point, Standard_Real& Weight); //! Perform the evaluation of the Bspline Basis //! and then multiplies by the weights //! this just evaluates the current point Standard_EXPORT static void Eval (const Standard_Real U, const Standard_Boolean PeriodicFlag, const Standard_Boolean HomogeneousFlag, Standard_Integer& ExtrapMode, const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal& Weights, gp_Pnt2d& Point, Standard_Real& Weight); //! Extend a BSpline nD using the tangency map //! <C1Coefficient> is the coefficient of reparametrisation //! <Continuity> must be equal to 1, 2 or 3. //! <Degree> must be greater or equal than <Continuity> + 1. //! //! Warning: <KnotsResult> and <PolesResult> must be dimensionned //! properly. Standard_EXPORT static void TangExtendToConstraint (const TColStd_Array1OfReal& FlatKnots, const Standard_Real C1Coefficient, const Standard_Integer NumPoles, Standard_Real& Poles, const Standard_Integer Dimension, const Standard_Integer Degree, const TColStd_Array1OfReal& ConstraintPoint, const Standard_Integer Continuity, const Standard_Boolean After, Standard_Integer& NbPolesResult, Standard_Integer& NbKnotsRsult, Standard_Real& KnotsResult, Standard_Real& PolesResult); //! Perform the evaluation of the of the cache //! the parameter must be normalized between //! the 0 and 1 for the span. //! The Cache must be valid when calling this //! routine. Geom Package will insure that. //! and then multiplies by the weights //! this just evaluates the current point //! the CacheParameter is where the Cache was //! constructed the SpanLength is to normalize //! the polynomial in the cache to avoid bad conditioning //! effects Standard_EXPORT static void CacheD0 (const Standard_Real U, const Standard_Integer Degree, const Standard_Real CacheParameter, const Standard_Real SpanLenght, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& Point); //! Perform the evaluation of the Bspline Basis //! and then multiplies by the weights //! this just evaluates the current point //! the parameter must be normalized between //! the 0 and 1 for the span. //! The Cache must be valid when calling this //! routine. Geom Package will insure that. //! and then multiplies by the weights //! ththe CacheParameter is where the Cache was //! constructed the SpanLength is to normalize //! the polynomial in the cache to avoid bad conditioning //! effectsis just evaluates the current point Standard_EXPORT static void CacheD0 (const Standard_Real U, const Standard_Integer Degree, const Standard_Real CacheParameter, const Standard_Real SpanLenght, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& Point); //! Calls CacheD0 for Bezier Curves Arrays computed with //! the method PolesCoefficients. //! Warning: To be used for Beziercurves ONLY!!! static void CoefsD0 (const Standard_Real U, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& Point); //! Calls CacheD0 for Bezier Curves Arrays computed with //! the method PolesCoefficients. //! Warning: To be used for Beziercurves ONLY!!! static void CoefsD0 (const Standard_Real U, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& Point); //! Perform the evaluation of the of the cache //! the parameter must be normalized between //! the 0 and 1 for the span. //! The Cache must be valid when calling this //! routine. Geom Package will insure that. //! and then multiplies by the weights //! this just evaluates the current point //! the CacheParameter is where the Cache was //! constructed the SpanLength is to normalize //! the polynomial in the cache to avoid bad conditioning //! effects Standard_EXPORT static void CacheD1 (const Standard_Real U, const Standard_Integer Degree, const Standard_Real CacheParameter, const Standard_Real SpanLenght, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& Point, gp_Vec& Vec); //! Perform the evaluation of the Bspline Basis //! and then multiplies by the weights //! this just evaluates the current point //! the parameter must be normalized between //! the 0 and 1 for the span. //! The Cache must be valid when calling this //! routine. Geom Package will insure that. //! and then multiplies by the weights //! ththe CacheParameter is where the Cache was //! constructed the SpanLength is to normalize //! the polynomial in the cache to avoid bad conditioning //! effectsis just evaluates the current point Standard_EXPORT static void CacheD1 (const Standard_Real U, const Standard_Integer Degree, const Standard_Real CacheParameter, const Standard_Real SpanLenght, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& Point, gp_Vec2d& Vec); //! Calls CacheD1 for Bezier Curves Arrays computed with //! the method PolesCoefficients. //! Warning: To be used for Beziercurves ONLY!!! static void CoefsD1 (const Standard_Real U, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& Point, gp_Vec& Vec); //! Calls CacheD1 for Bezier Curves Arrays computed with //! the method PolesCoefficients. //! Warning: To be used for Beziercurves ONLY!!! static void CoefsD1 (const Standard_Real U, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& Point, gp_Vec2d& Vec); //! Perform the evaluation of the of the cache //! the parameter must be normalized between //! the 0 and 1 for the span. //! The Cache must be valid when calling this //! routine. Geom Package will insure that. //! and then multiplies by the weights //! this just evaluates the current point //! the CacheParameter is where the Cache was //! constructed the SpanLength is to normalize //! the polynomial in the cache to avoid bad conditioning //! effects Standard_EXPORT static void CacheD2 (const Standard_Real U, const Standard_Integer Degree, const Standard_Real CacheParameter, const Standard_Real SpanLenght, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& Point, gp_Vec& Vec1, gp_Vec& Vec2); //! Perform the evaluation of the Bspline Basis //! and then multiplies by the weights //! this just evaluates the current point //! the parameter must be normalized between //! the 0 and 1 for the span. //! The Cache must be valid when calling this //! routine. Geom Package will insure that. //! and then multiplies by the weights //! ththe CacheParameter is where the Cache was //! constructed the SpanLength is to normalize //! the polynomial in the cache to avoid bad conditioning //! effectsis just evaluates the current point Standard_EXPORT static void CacheD2 (const Standard_Real U, const Standard_Integer Degree, const Standard_Real CacheParameter, const Standard_Real SpanLenght, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& Point, gp_Vec2d& Vec1, gp_Vec2d& Vec2); //! Calls CacheD1 for Bezier Curves Arrays computed with //! the method PolesCoefficients. //! Warning: To be used for Beziercurves ONLY!!! static void CoefsD2 (const Standard_Real U, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& Point, gp_Vec& Vec1, gp_Vec& Vec2); //! Calls CacheD1 for Bezier Curves Arrays computed with //! the method PolesCoefficients. //! Warning: To be used for Beziercurves ONLY!!! static void CoefsD2 (const Standard_Real U, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& Point, gp_Vec2d& Vec1, gp_Vec2d& Vec2); //! Perform the evaluation of the of the cache //! the parameter must be normalized between //! the 0 and 1 for the span. //! The Cache must be valid when calling this //! routine. Geom Package will insure that. //! and then multiplies by the weights //! this just evaluates the current point //! the CacheParameter is where the Cache was //! constructed the SpanLength is to normalize //! the polynomial in the cache to avoid bad conditioning //! effects Standard_EXPORT static void CacheD3 (const Standard_Real U, const Standard_Integer Degree, const Standard_Real CacheParameter, const Standard_Real SpanLenght, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& Point, gp_Vec& Vec1, gp_Vec& Vec2, gp_Vec& Vec3); //! Perform the evaluation of the Bspline Basis //! and then multiplies by the weights //! this just evaluates the current point //! the parameter must be normalized between //! the 0 and 1 for the span. //! The Cache must be valid when calling this //! routine. Geom Package will insure that. //! and then multiplies by the weights //! ththe CacheParameter is where the Cache was //! constructed the SpanLength is to normalize //! the polynomial in the cache to avoid bad conditioning //! effectsis just evaluates the current point Standard_EXPORT static void CacheD3 (const Standard_Real U, const Standard_Integer Degree, const Standard_Real CacheParameter, const Standard_Real SpanLenght, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& Point, gp_Vec2d& Vec1, gp_Vec2d& Vec2, gp_Vec2d& Vec3); //! Calls CacheD1 for Bezier Curves Arrays computed with //! the method PolesCoefficients. //! Warning: To be used for Beziercurves ONLY!!! static void CoefsD3 (const Standard_Real U, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt& Point, gp_Vec& Vec1, gp_Vec& Vec2, gp_Vec& Vec3); //! Calls CacheD1 for Bezier Curves Arrays computed with //! the method PolesCoefficients. //! Warning: To be used for Beziercurves ONLY!!! static void CoefsD3 (const Standard_Real U, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, gp_Pnt2d& Point, gp_Vec2d& Vec1, gp_Vec2d& Vec2, gp_Vec2d& Vec3); //! Perform the evaluation of the Taylor expansion //! of the Bspline normalized between 0 and 1. //! If rational computes the homogeneous Taylor expension //! for the numerator and stores it in CachePoles Standard_EXPORT static void BuildCache (const Standard_Real U, const Standard_Real InverseOfSpanDomain, const Standard_Boolean PeriodicFlag, const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, TColgp_Array1OfPnt& CachePoles, TColStd_Array1OfReal* CacheWeights); //! Perform the evaluation of the Taylor expansion //! of the Bspline normalized between 0 and 1. //! If rational computes the homogeneous Taylor expension //! for the numerator and stores it in CachePoles Standard_EXPORT static void BuildCache (const Standard_Real U, const Standard_Real InverseOfSpanDomain, const Standard_Boolean PeriodicFlag, const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, TColgp_Array1OfPnt2d& CachePoles, TColStd_Array1OfReal* CacheWeights); //! Perform the evaluation of the Taylor expansion //! of the Bspline normalized between 0 and 1. //! Structure of result optimized for BSplCLib_Cache. Standard_EXPORT static void BuildCache (const Standard_Real theParameter, const Standard_Real theSpanDomain, const Standard_Boolean thePeriodicFlag, const Standard_Integer theDegree, const Standard_Integer theSpanIndex, const TColStd_Array1OfReal& theFlatKnots, const TColgp_Array1OfPnt& thePoles, const TColStd_Array1OfReal* theWeights, TColStd_Array2OfReal& theCacheArray); //! Perform the evaluation of the Taylor expansion //! of the Bspline normalized between 0 and 1. //! Structure of result optimized for BSplCLib_Cache. Standard_EXPORT static void BuildCache (const Standard_Real theParameter, const Standard_Real theSpanDomain, const Standard_Boolean thePeriodicFlag, const Standard_Integer theDegree, const Standard_Integer theSpanIndex, const TColStd_Array1OfReal& theFlatKnots, const TColgp_Array1OfPnt2d& thePoles, const TColStd_Array1OfReal* theWeights, TColStd_Array2OfReal& theCacheArray); static void PolesCoefficients (const TColgp_Array1OfPnt2d& Poles, TColgp_Array1OfPnt2d& CachePoles); Standard_EXPORT static void PolesCoefficients (const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, TColgp_Array1OfPnt2d& CachePoles, TColStd_Array1OfReal* CacheWeights); static void PolesCoefficients (const TColgp_Array1OfPnt& Poles, TColgp_Array1OfPnt& CachePoles); //! Encapsulation of BuildCache to perform the //! evaluation of the Taylor expansion for beziercurves //! at parameter 0. //! Warning: To be used for Beziercurves ONLY!!! Standard_EXPORT static void PolesCoefficients (const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, TColgp_Array1OfPnt& CachePoles, TColStd_Array1OfReal* CacheWeights); //! Returns pointer to statically allocated array representing //! flat knots for bezier curve of the specified degree. //! Raises OutOfRange if Degree > MaxDegree() Standard_EXPORT static const Standard_Real& FlatBezierKnots (const Standard_Integer Degree); //! builds the Schoenberg points from the flat knot //! used to interpolate a BSpline since the //! BSpline matrix is invertible. Standard_EXPORT static void BuildSchoenbergPoints (const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, TColStd_Array1OfReal& Parameters); //! Performs the interpolation of the data given in //! the Poles array according to the requests in //! ContactOrderArray that is : if //! ContactOrderArray(i) has value d it means that //! Poles(i) contains the dth derivative of the //! function to be interpolated. The length L of the //! following arrays must be the same : //! Parameters, ContactOrderArray, Poles, //! The length of FlatKnots is Degree + L + 1 //! Warning: //! the method used to do that interpolation is //! gauss elimination WITHOUT pivoting. Thus if the //! diagonal is not dominant there is no guarantee //! that the algorithm will work. Nevertheless for //! Cubic interpolation or interpolation at Scheonberg //! points the method will work //! The InversionProblem will report 0 if there was no //! problem else it will give the index of the faulty //! pivot Standard_EXPORT static void Interpolate (const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColStd_Array1OfReal& Parameters, const TColStd_Array1OfInteger& ContactOrderArray, TColgp_Array1OfPnt& Poles, Standard_Integer& InversionProblem); //! Performs the interpolation of the data given in //! the Poles array according to the requests in //! ContactOrderArray that is : if //! ContactOrderArray(i) has value d it means that //! Poles(i) contains the dth derivative of the //! function to be interpolated. The length L of the //! following arrays must be the same : //! Parameters, ContactOrderArray, Poles, //! The length of FlatKnots is Degree + L + 1 //! Warning: //! the method used to do that interpolation is //! gauss elimination WITHOUT pivoting. Thus if the //! diagonal is not dominant there is no guarantee //! that the algorithm will work. Nevertheless for //! Cubic interpolation at knots or interpolation at Scheonberg //! points the method will work. //! The InversionProblem w //! ll report 0 if there was no //! problem else it will give the index of the faulty //! pivot Standard_EXPORT static void Interpolate (const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColStd_Array1OfReal& Parameters, const TColStd_Array1OfInteger& ContactOrderArray, TColgp_Array1OfPnt2d& Poles, Standard_Integer& InversionProblem); //! Performs the interpolation of the data given in //! the Poles array according to the requests in //! ContactOrderArray that is : if //! ContactOrderArray(i) has value d it means that //! Poles(i) contains the dth derivative of the //! function to be interpolated. The length L of the //! following arrays must be the same : //! Parameters, ContactOrderArray, Poles, //! The length of FlatKnots is Degree + L + 1 //! Warning: //! the method used to do that interpolation is //! gauss elimination WITHOUT pivoting. Thus if the //! diagonal is not dominant there is no guarantee //! that the algorithm will work. Nevertheless for //! Cubic interpolation at knots or interpolation at Scheonberg //! points the method will work. //! The InversionProblem will report 0 if there was no //! problem else it will give the index of the faulty //! pivot Standard_EXPORT static void Interpolate (const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColStd_Array1OfReal& Parameters, const TColStd_Array1OfInteger& ContactOrderArray, TColgp_Array1OfPnt& Poles, TColStd_Array1OfReal& Weights, Standard_Integer& InversionProblem); //! Performs the interpolation of the data given in //! the Poles array according to the requests in //! ContactOrderArray that is : if //! ContactOrderArray(i) has value d it means that //! Poles(i) contains the dth derivative of the //! function to be interpolated. The length L of the //! following arrays must be the same : //! Parameters, ContactOrderArray, Poles, //! The length of FlatKnots is Degree + L + 1 //! Warning: //! the method used to do that interpolation is //! gauss elimination WITHOUT pivoting. Thus if the //! diagonal is not dominant there is no guarantee //! that the algorithm will work. Nevertheless for //! Cubic interpolation at knots or interpolation at Scheonberg //! points the method will work. //! The InversionProblem w //! ll report 0 if there was no //! problem else it will give the i Standard_EXPORT static void Interpolate (const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColStd_Array1OfReal& Parameters, const TColStd_Array1OfInteger& ContactOrderArray, TColgp_Array1OfPnt2d& Poles, TColStd_Array1OfReal& Weights, Standard_Integer& InversionProblem); //! Performs the interpolation of the data given in //! the Poles array according to the requests in //! ContactOrderArray that is : if //! ContactOrderArray(i) has value d it means that //! Poles(i) contains the dth derivative of the //! function to be interpolated. The length L of the //! following arrays must be the same : //! Parameters, ContactOrderArray //! The length of FlatKnots is Degree + L + 1 //! The PolesArray is an seen as an //! Array[1..N][1..ArrayDimension] with N = tge length //! of the parameters array //! Warning: //! the method used to do that interpolation is //! gauss elimination WITHOUT pivoting. Thus if the //! diagonal is not dominant there is no guarantee //! that the algorithm will work. Nevertheless for //! Cubic interpolation or interpolation at Scheonberg //! points the method will work //! The InversionProblem will report 0 if there was no //! problem else it will give the index of the faulty //! pivot Standard_EXPORT static void Interpolate (const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColStd_Array1OfReal& Parameters, const TColStd_Array1OfInteger& ContactOrderArray, const Standard_Integer ArrayDimension, Standard_Real& Poles, Standard_Integer& InversionProblem); Standard_EXPORT static void Interpolate (const Standard_Integer Degree, const TColStd_Array1OfReal& FlatKnots, const TColStd_Array1OfReal& Parameters, const TColStd_Array1OfInteger& ContactOrderArray, const Standard_Integer ArrayDimension, Standard_Real& Poles, Standard_Real& Weights, Standard_Integer& InversionProblem); //! Find the new poles which allows an old point (with a //! given u as parameter) to reach a new position //! Index1 and Index2 indicate the range of poles we can move //! (1, NbPoles-1) or (2, NbPoles) -> no constraint for one side //! don't enter (1,NbPoles) -> error: rigid move //! (2, NbPoles-1) -> the ends are enforced //! (3, NbPoles-2) -> the ends and the tangency are enforced //! if Problem in BSplineBasis calculation, no change for the curve //! and FirstIndex, LastIndex = 0 Standard_EXPORT static void MovePoint (const Standard_Real U, const gp_Vec2d& Displ, const Standard_Integer Index1, const Standard_Integer Index2, const Standard_Integer Degree, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& FlatKnots, Standard_Integer& FirstIndex, Standard_Integer& LastIndex, TColgp_Array1OfPnt2d& NewPoles); //! Find the new poles which allows an old point (with a //! given u as parameter) to reach a new position //! Index1 and Index2 indicate the range of poles we can move //! (1, NbPoles-1) or (2, NbPoles) -> no constraint for one side //! don't enter (1,NbPoles) -> error: rigid move //! (2, NbPoles-1) -> the ends are enforced //! (3, NbPoles-2) -> the ends and the tangency are enforced //! if Problem in BSplineBasis calculation, no change for the curve //! and FirstIndex, LastIndex = 0 Standard_EXPORT static void MovePoint (const Standard_Real U, const gp_Vec& Displ, const Standard_Integer Index1, const Standard_Integer Index2, const Standard_Integer Degree, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& FlatKnots, Standard_Integer& FirstIndex, Standard_Integer& LastIndex, TColgp_Array1OfPnt& NewPoles); //! This is the dimension free version of the utility //! U is the parameter must be within the first FlatKnots and the //! last FlatKnots Delta is the amount the curve has to be moved //! DeltaDerivative is the amount the derivative has to be moved. //! Delta and DeltaDerivative must be array of dimension //! ArrayDimension Degree is the degree of the BSpline and the //! FlatKnots are the knots of the BSpline Starting Condition if = //! -1 means the starting point of the curve can move //! = 0 means the //! starting point of the curve cannot move but tangent starting //! point of the curve cannot move //! = 1 means the starting point and tangents cannot move //! = 2 means the starting point tangent and curvature cannot move //! = ... //! Same holds for EndingCondition //! Poles are the poles of the curve //! Weights are the weights of the curve if not NULL //! NewPoles are the poles of the deformed curve //! ErrorStatus will be 0 if no error happened //! 1 if there are not enough knots/poles //! the imposed conditions //! The way to solve this problem is to add knots to the BSpline //! If StartCondition = 1 and EndCondition = 1 then you need at least //! 4 + 2 = 6 poles so for example to have a C1 cubic you will need //! have at least 2 internal knots. Standard_EXPORT static void MovePointAndTangent (const Standard_Real U, const Standard_Integer ArrayDimension, Standard_Real& Delta, Standard_Real& DeltaDerivative, const Standard_Real Tolerance, const Standard_Integer Degree, const Standard_Integer StartingCondition, const Standard_Integer EndingCondition, Standard_Real& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& FlatKnots, Standard_Real& NewPoles, Standard_Integer& ErrorStatus); //! This is the dimension free version of the utility //! U is the parameter must be within the first FlatKnots and the //! last FlatKnots Delta is the amount the curve has to be moved //! DeltaDerivative is the amount the derivative has to be moved. //! Delta and DeltaDerivative must be array of dimension //! ArrayDimension Degree is the degree of the BSpline and the //! FlatKnots are the knots of the BSpline Starting Condition if = //! -1 means the starting point of the curve can move //! = 0 means the //! starting point of the curve cannot move but tangent starting //! point of the curve cannot move //! = 1 means the starting point and tangents cannot move //! = 2 means the starting point tangent and curvature cannot move //! = ... //! Same holds for EndingCondition //! Poles are the poles of the curve //! Weights are the weights of the curve if not NULL //! NewPoles are the poles of the deformed curve //! ErrorStatus will be 0 if no error happened //! 1 if there are not enough knots/poles //! the imposed conditions //! The way to solve this problem is to add knots to the BSpline //! If StartCondition = 1 and EndCondition = 1 then you need at least //! 4 + 2 = 6 poles so for example to have a C1 cubic you will need //! have at least 2 internal knots. Standard_EXPORT static void MovePointAndTangent (const Standard_Real U, const gp_Vec& Delta, const gp_Vec& DeltaDerivative, const Standard_Real Tolerance, const Standard_Integer Degree, const Standard_Integer StartingCondition, const Standard_Integer EndingCondition, const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& FlatKnots, TColgp_Array1OfPnt& NewPoles, Standard_Integer& ErrorStatus); //! This is the dimension free version of the utility //! U is the parameter must be within the first FlatKnots and the //! last FlatKnots Delta is the amount the curve has to be moved //! DeltaDerivative is the amount the derivative has to be moved. //! Delta and DeltaDerivative must be array of dimension //! ArrayDimension Degree is the degree of the BSpline and the //! FlatKnots are the knots of the BSpline Starting Condition if = //! -1 means the starting point of the curve can move //! = 0 means the //! starting point of the curve cannot move but tangent starting //! point of the curve cannot move //! = 1 means the starting point and tangents cannot move //! = 2 means the starting point tangent and curvature cannot move //! = ... //! Same holds for EndingCondition //! Poles are the poles of the curve //! Weights are the weights of the curve if not NULL //! NewPoles are the poles of the deformed curve //! ErrorStatus will be 0 if no error happened //! 1 if there are not enough knots/poles //! the imposed conditions //! The way to solve this problem is to add knots to the BSpline //! If StartCondition = 1 and EndCondition = 1 then you need at least //! 4 + 2 = 6 poles so for example to have a C1 cubic you will need //! have at least 2 internal knots. Standard_EXPORT static void MovePointAndTangent (const Standard_Real U, const gp_Vec2d& Delta, const gp_Vec2d& DeltaDerivative, const Standard_Real Tolerance, const Standard_Integer Degree, const Standard_Integer StartingCondition, const Standard_Integer EndingCondition, const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& FlatKnots, TColgp_Array1OfPnt2d& NewPoles, Standard_Integer& ErrorStatus); //! given a tolerance in 3D space returns a //! tolerance in U parameter space such that //! all u1 and u0 in the domain of the curve f(u) //! | u1 - u0 | < UTolerance and //! we have |f (u1) - f (u0)| < Tolerance3D Standard_EXPORT static void Resolution (Standard_Real& PolesArray, const Standard_Integer ArrayDimension, const Standard_Integer NumPoles, const TColStd_Array1OfReal* Weights, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer Degree, const Standard_Real Tolerance3D, Standard_Real& UTolerance); //! given a tolerance in 3D space returns a //! tolerance in U parameter space such that //! all u1 and u0 in the domain of the curve f(u) //! | u1 - u0 | < UTolerance and //! we have |f (u1) - f (u0)| < Tolerance3D Standard_EXPORT static void Resolution (const TColgp_Array1OfPnt& Poles, const TColStd_Array1OfReal* Weights, const Standard_Integer NumPoles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer Degree, const Standard_Real Tolerance3D, Standard_Real& UTolerance); //! given a tolerance in 3D space returns a //! tolerance in U parameter space such that //! all u1 and u0 in the domain of the curve f(u) //! | u1 - u0 | < UTolerance and //! we have |f (u1) - f (u0)| < Tolerance3D Standard_EXPORT static void Resolution (const TColgp_Array1OfPnt2d& Poles, const TColStd_Array1OfReal* Weights, const Standard_Integer NumPoles, const TColStd_Array1OfReal& FlatKnots, const Standard_Integer Degree, const Standard_Real Tolerance3D, Standard_Real& UTolerance); //! Splits the given range to BSpline intervals of given continuity //! @param[in] theKnots the knots of BSpline //! @param[in] theMults the knots' multiplicities //! @param[in] theDegree the degree of BSpline //! @param[in] isPeriodic the periodicity of BSpline //! @param[in] theContinuity the target interval's continuity //! @param[in] theFirst the begin of the target range //! @param[in] theLast the end of the target range //! @param[in] theTolerance the tolerance //! @param[in,out] theIntervals the array to store intervals if isn't nullptr //! @return the number of intervals Standard_EXPORT static Standard_Integer Intervals (const TColStd_Array1OfReal& theKnots, const TColStd_Array1OfInteger& theMults, Standard_Integer theDegree, Standard_Boolean isPeriodic, Standard_Integer theContinuity, Standard_Real theFirst, Standard_Real theLast, Standard_Real theTolerance, TColStd_Array1OfReal* theIntervals); protected: private: Standard_EXPORT static void LocateParameter (const TColStd_Array1OfReal& Knots, const Standard_Real U, const Standard_Boolean Periodic, const Standard_Integer K1, const Standard_Integer K2, Standard_Integer& Index, Standard_Real& NewU, const Standard_Real Uf, const Standard_Real Ue); }; #include <BSplCLib.lxx> #endif // _BSplCLib_HeaderFile
#include<bits/stdc++.h> using namespace std; int main(){ int array[] = {6, -1, -3, 4, -2, 2, 4, 6, -12, -7}; int n = 10; for (int i = 0; i < n; i++){ int sum = 0; for (int j = i; j < n; j++){ sum += array[j]; if (sum == 0) { cout<< i << "..." <<j<<endl;; } } } return 0; }
#ifndef CFG_OTHER # error "This source should only be compiled in a non-Debug configuration." #endif #ifdef CFG_DEBUG # error "This source should not be compiled in a Debug configuration." #endif #include "iface.h" int main(int argc, char** argv) { return iface_src() + iface_other(); }
#ifndef _GUEST_LOGIN_H_ #define _GUEST_LOGIN_H_ #pragma once #include "CHttpRequestHandler.h" #include <string> class CAccountLogin : public CHttpRequestHandler { public: CAccountLogin(){} ~CAccountLogin(){} bool IsForbidLogin(std::string& ip, std::string& device_no,std::string& openudid); bool IsForbidLoginByMid(int32_t Mid); virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out); private: }; #endif
/// Executare operatiilor de comunicare, comparatie si calcul apartin propietatii de: // realizabilitate /// Algoritmul care rezolva orice equatie de gradul intai se numeste: // algoritm universal
#ifndef OTROS_H_INCLUDED #define OTROS_H_INCLUDED #include <string> using namespace std; enum tipopalabra{ cand= 0, dic= 1 }; #endif
#ifndef ApplicationManager_h__ #define ApplicationManager_h__ #include <Windows.h> #include "../../middleware/includes/gl/glew.h" #include "../../middleware/includes/gl/glfw3.h" #include <memory> #include "../Renderer.h" class ApplicationManager { int mOpenGLMajorVersion; int mOpenGLMinorVersion; double mTime; GLFWwindow* mWindow; //Why didn't we use smart pointers here? google it! ;) std::unique_ptr<Renderer> mRenderer; void InitializeComponents(); void HandleKeyboardInput(); void HandleMouseLocation(); void Update(); static void SpecialKeyPressed(GLFWwindow* window, int key, int scancode, int action, int mods); static void MouseMoved(GLFWwindow* window, double xpos, double ypos); static void MouseButtonClicked(GLFWwindow* window, int button, int action, int mods); static int KeyPressed; //Keep the code of the pressed key static int KeyAction; //Keep the code of the action static int MouseClicked; //Keep the code of the action static double MouseXPos; //Keep the x-value of the mouse position static double MouseYPos; //Keep the y-value of the mouse position bool PlayAgain; public: static int WindowSizeWidth; static int WindowSizeHeight; ApplicationManager(); bool InitalizeApplication(int pWindowSizeWidth, int pWindowSizeHeight); bool StartMainLoop(); void CloseApplication(); ~ApplicationManager(void); }; #endif // ApplicationManager_h__
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "ConsoleLogger.h" #include <iostream> #include <unordered_map> #include <Common/ConsoleTools.h> namespace logging { using common::console::Color; ConsoleLogger::ConsoleLogger(Level level) : CommonLogger(level) { } void ConsoleLogger::doLogString(const std::string& message) { std::lock_guard<std::mutex> lock(mutex); bool readingText = true; bool changedColor = false; std::string color = ""; static std::unordered_map<std::string, Color> colorMapping = { { BLUE, Color::Blue }, { GREEN, Color::Green }, { RED, Color::Red }, { YELLOW, Color::Yellow }, { WHITE, Color::White }, { CYAN, Color::Cyan }, { MAGENTA, Color::Magenta }, { BRIGHT_BLUE, Color::BrightBlue }, { BRIGHT_GREEN, Color::BrightGreen }, { BRIGHT_RED, Color::BrightRed }, { BRIGHT_YELLOW, Color::BrightYellow }, { BRIGHT_WHITE, Color::BrightWhite }, { BRIGHT_CYAN, Color::BrightCyan }, { BRIGHT_MAGENTA, Color::BrightMagenta }, { DEFAULT, Color::Default } }; for (size_t charPos = 0; charPos < message.size(); ++charPos) { if (message[charPos] == ILogger::COLOR_DELIMETER) { readingText = !readingText; color += message[charPos]; if (readingText) { auto it = colorMapping.find(color); common::console::setTextColor(it == colorMapping.end() ? Color::Default : it->second); changedColor = true; color.clear(); } } else if (readingText) { std::cout << message[charPos]; } else { color += message[charPos]; } } if (changedColor) { common::console::setTextColor(Color::Default); } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #ifndef POP_AUTHENTICATION_COMMANDS_H #define POP_AUTHENTICATION_COMMANDS_H #include "adjunct/m2/src/backend/pop/commands/PopCommand.h" #include "adjunct/m2/src/util/authenticate.h" namespace PopCommands { /** @brief Base class for authentication commands */ class AuthenticationCommand : public PopCommand { public: virtual OP_STATUS OnSuccessfulComplete(const OpStringC8& success_msg, POP3& connection); virtual OP_STATUS OnFailedComplete(const OpStringC8& error_msg, POP3& connection); virtual ProgressInfo::ProgressAction GetProgressAction() const { return ProgressInfo::AUTHENTICATING; } protected: OpAuthenticate m_info; }; /** @brief AUTH CRAM-MD5 command */ class AuthenticateCramMD5 : public AuthenticationCommand { public: AuthenticateCramMD5() : m_second_stage(FALSE) {} virtual OP_STATUS GetPopCommand(OpString8& command); virtual OP_STATUS OnContinueReq(const OpStringC8& text, POP3& connection); private: BOOL m_second_stage; }; /** @brief APOP command */ class AuthenticateApop : public AuthenticationCommand { public: virtual OP_STATUS PrepareToSend(POP3& connection); virtual OP_STATUS GetPopCommand(OpString8& command); }; /** @brief USER/PASS command */ class AuthenticatePlaintext : public AuthenticationCommand { public: AuthenticatePlaintext() : m_second_stage(FALSE) {} virtual OP_STATUS PrepareToSend(POP3& connection); virtual OP_STATUS GetPopCommand(OpString8& command); virtual OP_STATUS OnSuccessfulComplete(const OpStringC8& success_msg, POP3& connection); virtual BOOL UsesPassword() const { return m_second_stage; } private: BOOL m_second_stage; }; }; #endif // POP_AUTHENTICATION_COMMANDS_H
#ifndef DELIVERY_ACTION_LISTENER_H #define DELIVERY_ACTION_LISTENER_H #include <mqtt/publisher/pub_action_listener.h> class delivery_action_listener : public pub_action_listener { bool done_; virtual void on_failure(const mqtt::itoken &tok); virtual void on_success(const mqtt::itoken &tok); public: delivery_action_listener() : done_(false) {} bool is_done() const { return done_; } }; #endif // DELIVERY_ACTION_LISTENER_H
//Created by: Mark Marsala, Marshall Farris, and Johnathon Franco Sosa //Date: 5/4/2021 //Header file for stereo8.cpp #ifndef STEREO8_H #define STEREO8_H #include "waveHeader.h" #include "iFileIO.h" /** * Manages stereo8. * Reads and writes stereo8, as well as allocates and reallocates memory. * Uses iFileIo as an interface. */ class Stereo8 : public iFileIO { std::string fileName; unsigned char* buffer = NULL; wav_header waveHeader; unsigned char* leftBuffer = NULL; unsigned char* rightBuffer = NULL; public: /** * Paramaterized constructor for Stereo8 * @param newFile - the new file that is being used */ Stereo8(const std::string newFile); /** * Overrides method from interface * Reads an 8 bit stereo wav file */ void readFile() override; /** * Overrides method from interface * Writes an 8 bit stereo wav file * @param outFileName - pointer to the outFileName */ void writeFile(const std::string &outFileName) override; /** * Returns buffer */ unsigned char* getBuffer(); /** * Returns waveHeader.data_bytes */ int getBufferSize() const; /** * Allocates Buffer */ void allocateBuffer(); /** * Reallocates Buffer */ void reallocateBuffer(); /** * Returns left Buffer */ unsigned char* getLeftBuffer(); /** * Returns right Buffer */ unsigned char* getRightBuffer(); /** * Deconstructor for Stereo8. * Deletes buffer if not NULL */ virtual ~Stereo8(); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2009-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ /** * @file GadgetSignatureVerifier.h * * Gadget signature verifier interface. * * @author Alexei Khlebnikov <alexeik@opera.com> * */ #ifndef GADGET_SIGNATURE_VERIFIER_H #define GADGET_SIGNATURE_VERIFIER_H #ifdef SIGNED_GADGET_SUPPORT #include "modules/libcrypto/include/CryptoXmlSignature.h" #include "modules/libcrypto/include/OCSPCertificateChainVerifier.h" class GadgetSignature; class GadgetSignatureStorage; /** * @class GadgetSignatureVerifier * * This class takes a gadget and verifies it, first locally, then using OCSP. * * The class user is supposed to start the verification, then wait * for MSG_GADGET_SIGNATURE_VERIFICATION_FINISHED message, * unless an exception has been thrown during the starting process. * * This class is a processor. * It is asynchronous. * * Usage: * * 1) Starting: * * @code * // Verifier and signature storage can be allocated on heap * // or as class members. * GadgetSignatureVerifier m_verifier; * GadgetSignatureStorage m_signature_storage; * // ... * g_main_message_handler->SetCallBack(this, * MSG_GADGET_SIGNATURE_VERIFICATION_FINISHED, m_verifier.Id()); * m_verifier.SetGadgetFilenameL(zipped_gadget_filename); * m_verifier.SetCAStorage(ca_storage); * m_verifier.SetGadgetSignatureStorageContainer(&m_signature_storage); * m_verifier.ProcessL(); * @endcode * * 2) Verification result handling: * * @code * // After the class user's class has received * // MSG_GADGET_SIGNATURE_VERIFICATION_FINISHED. * CryptoXmlSignature::VerifyError verify_error = m_signature_storage.GetCommonVerifyError(); * * switch (verify_error) * { * case CryptoXmlSignature::OK_CHECKED_LOCALLY: * // Handle success. * * case CryptoXmlSignature::OK_CHECKED_WITH_OCSP: * // Handle "extended success". * * case ... * // Handle error. * } * * // Verification successful. * // Find out which signatures are present. * unsigned int author_signature_count = m_signature_storage.GetAuthorSignatureCount(); * unsigned int distributor_signature_count = m_signature_storage.GetAuthorSignatureCount(); * ... * // Get author signature. * const GadgetSignature* author_signature = m_signature_storage.GetAuthorSignature(); * ... * // Get distributor signature with index "idx". * const GadgetSignature* distributor_signature = m_signature_storage.GetDistributorSignature(idx); * ... * // Get verification result of the distributor signature. * const CryptoCertificateChain* chain = distributor_signature->GetVerifyError(); * ... * // Checking all signatures is too boring. Get the best signature at once. * const GadgetSignature* best_signature = m_signature_storage.GetBestSignature(); * // Best signature exists if verification is successful. * OP_ASSERT(best_signature); * // Best signature's verify error matches common verify error. * OP_ASSERT(best_signature->GetVerifyError() == verify_error); * ... * // Get certificate chain of the best signature. * const CryptoCertificateChain* chain = best_signature->GetCertificateChain(); * // Certificate chain exists if verification is successful. * OP_ASSERT(chain); * // Certificate chain is not empty if verification is successful. * OP_ASSERT(chain->GetNumberOfCertificates() > 0); * ... * // Get signing certificate. * const CryptoCertificate* cert = chain->GetCertificate(0); * // Certificate exists if verification is successful. * OP_ASSERT(cert); * ... * // Get root CA certificate. * int chain_len = chain->GetNumberOfCertificates(); * const CryptoCertificate* root_cert = chain->GetCertificate(chain_len - 1); * // Certificate exists if verification is successful. * OP_ASSERT(root_cert); * ... * @endcode * */ class GadgetSignatureVerifier #ifdef CRYPTO_OCSP_SUPPORT : public MessageObject #endif { public: GadgetSignatureVerifier(); virtual ~GadgetSignatureVerifier(); public: /** @name Functions to be called to start the verification. */ /** @{ */ /** Set the widget to be verified. */ void SetGadgetFilenameL(const OpString& zipped_gadget_filename); /** Set trusted CA storage. */ void SetCAStorage(const CryptoCertificateStorage* ca_storage); /** Set output container for gadget signatures. * The container's old content will be cleared if @ref ProcessL() is called. */ void SetGadgetSignatureStorageContainer(GadgetSignatureStorage* signature_storage); /** Helper function for getting this object's id. */ MH_PARAM_1 Id() const; /** Process asynchronous verification of the gadget. * * Exception means that something went wrong during launching, * for example OOM, bad input parameters or internal error. * In this case no verification-finished message will be posted afterwards. * * If the exception is not thrown - the caller (or its appointed listener) * should wait for the callback with the following parameters: * * - msg == MSG_GADGET_SIGNATURE_VERIFICATION_FINISHED; * - par1 == Id() - this verifier object's id; * - par2 == 0. */ void ProcessL(); /** @} */ public: #ifdef CRYPTO_OCSP_SUPPORT // MessageObject methods. virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); #endif private: void VerifyOffline(); void CheckWidgetFileExistsL(); void CheckWidgetIsZipFileL(); void LookForSignaturesL(); static BOOL IsAuthorSignature(const OpStringC& pathname); static BOOL IsDistributorSignature(const OpStringC& pathname, unsigned int* distributor_signature_number = NULL); void AddDistributorSignatureFilenameL(const OpStringC& pathname, unsigned int number); void ProcessAllSignaturesOfflineL(); void ProcessSignatureOfflineL(const OpStringC& signature_filename); void VerifySignatureOfflineL( const OpStringC& signature_filename, CryptoXmlSignature::VerifyError& verify_error, OpAutoPtr <CryptoCertificateChain>& signer_certificate_chain); void CheckSignaturePropertiesL( const OpStringC& signature_filename, CryptoXmlSignature::VerifyError& verify_error, const OpStringC& signature_profile, const OpStringC& signature_role, const OpStringC& signature_identifier); void CheckAllFilesSignedL( const OpStringC& signature_filename, CryptoXmlSignature::VerifyError& verify_error, const OpStringHashTable <CryptoXmlSignature::SignedReference>& reference_objects); void AddSignatureToStorageL( const OpStringC& signature_filename, CryptoXmlSignature::VerifyError& verify_error, OpAutoPtr <CryptoCertificateChain>& signer_certificate_chain); #ifdef CRYPTO_OCSP_SUPPORT void VerifyOnline(); void ScheduleOCSPProcessing(); void LaunchOCSPProcessing(); GadgetSignature* GetCurrentSignature() const; void ProcessOCSPL(GadgetSignature& gadget_signature); void ProcessOCSPVerificationResult(); void FinishOCSPVerification(CryptoXmlSignature::VerifyError signature_verify_error, BOOL upgrade_common); #endif void NotifyAboutFinishedVerification(); private: // These objects are set from outside. Pointed objects are not owned. OpString m_gadget_filename; const CryptoCertificateStorage* m_ca_storage; GadgetSignatureStorage* m_gadget_signature_storage; private: // These objects are created and owned by this object. // Gadget zip file and zip container file list. OpZip m_gadget_file; OpAutoVector <OpString> m_file_list; // Signature filename related data. // If author signature is found - it's a pointer to the string // in m_file_list. Otherwise NULL. const OpStringC* m_author_signature_filename; // Stores distributor signature numbers (as in signatureNUMBER.xml). // This list must always be sorted (ascending). // According to the W3C spec, signatures must be processed in descending // order, thus this list will be traversed backwards. OpINT32Vector m_distributor_signature_list; // Maps distributor signature numbers (as in signatureNUMBER.xml) // to pointers to filenames contained in m_file_list. // If we had a map class where keys were guaranteed to be sorted, // we could avoid using m_distributor_signature_list. OpINT32HashTable <const OpStringC> m_number2filename; // Flat index of the current signature in m_gadget_signature_storage. // It's not the distributor signature number as in signatureNUMBER.xml! // Please refer to the documentation of @ref class GadgetSignatureStorage // for more verbose description. unsigned int m_current_signature_index; #ifdef CRYPTO_OCSP_SUPPORT OCSPCertificateChainVerifier m_ocsp_verifier; #endif }; #endif // SIGNED_GADGET_SUPPORT #endif // GADGET_SIGNATURE_VERIFIER_H
#pragma once #include <FreeListObjectPool.h> #include <variant> namespace breakout { template<class containerStruct> class FreeListPoolElement { public: FreeListPoolElement(); ~FreeListPoolElement() = default; bool IsActive() const; void SetContainer(const containerStruct& container); containerStruct& GetContainer(); private: friend class FreeListObjectPool<FreeListPoolElement<containerStruct>>; FreeListPoolElement<containerStruct>* GetNext(); void SetNext(FreeListPoolElement<containerStruct>* next); void Activate(); void Deactivate(); std::variant<containerStruct, FreeListPoolElement<containerStruct>*> m_container, m_next; bool b_active = false; }; template<class containerStruct> FreeListPoolElement<containerStruct>::FreeListPoolElement() { } template<class containerStruct> FreeListPoolElement<containerStruct>* FreeListPoolElement<containerStruct>::GetNext() { return std::get<FreeListPoolElement<containerStruct>*>(m_next); } template<class containerStruct> void FreeListPoolElement<containerStruct>::SetNext(FreeListPoolElement<containerStruct>* next) { m_next = next; } template<class containerStruct> void FreeListPoolElement<containerStruct>::Activate() { b_active = true; } template<class containerStruct> void FreeListPoolElement<containerStruct>::Deactivate() { b_active = false; } template<class containerStruct> bool FreeListPoolElement<containerStruct>::IsActive() const { return b_active; } template<class containerStruct> void FreeListPoolElement<containerStruct>::SetContainer(const containerStruct& container) { m_container = container; } template<class containerStruct> containerStruct& FreeListPoolElement<containerStruct>::GetContainer() { return std::get<containerStruct>(m_container); } }
#include <stdio.h> /* printf */ #include <stdlib.h> /* system, NULL, EXIT_FAILURE */ #ifdef _WIN32 #include <Windows.h> #define GetCurrentDir _getcwd #else #include<unistd.h> #endif #include "VideoFaceDetector.h" #include"InitProc.h" #include "LQP_main.h" #include "SessionTraining.h" string Sys_language; const int PictureWidth = 60; const int PictureHeight = 80; //#ifndef _WIN32 int main(int argc, char *argv[]) { /* #else int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { #endif*/ #ifndef _WIN32 QApplication app(argc, argv); #else QApplication app(__argc, __argv); #endif PrelminarySetts(current_path, search_path); camera = Inits(); VideoFaceDetector detector(cascade_face, camera); sessionTraining(detector); return 0; }
// Lexer for C, C++, C#, Java, Rescouce Script, Asymptote, D, Objective C/C++, PHP // JavaScript, JScript, ActionScript, haXe, Groovy, Scala, Jamfile, AWK, IDL/ODL/AIDL #include <string.h> #include <assert.h> #include <ctype.h> #include <string> #include <vector> #include <map> #include <algorithm> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" //#include "SparseState.h" using namespace Scintilla; #define LEX_CPP 1 // C/C++ #define LEX_JAVA 2 // Java #define LEX_CS 3 // C# #define LEX_JS 4 // JavaScript #define LEX_RC 5 // Resouce Script #define LEX_IDL 6 // Interface Definition Language #define LEX_D 7 // D #define LEX_ASY 8 // Asymptote #define LEX_OBJC 10 // Objective C/C++ #define LEX_AS 11 // ActionScript #define LEX_HX 12 // haXe #define LEX_GROOVY 13 // Groovy Script #define LEX_SCALA 14 // Scala Script #define LEX_GO 15 // Go //#define LEX_AIDL 27 // Android Interface Definition Language #define LEX_PHP 29 #define LEX_AWK 51 // Awk #define LEX_JAM 52 // Jamfile static inline bool _hasPreprocessor(int lex) { // #[space]preprocessor return lex == LEX_CPP || lex == LEX_CS || lex == LEX_RC || lex == LEX_OBJC; } static inline bool _hasAnotation(int lex) { // @anotation return lex == LEX_JAVA || lex == LEX_GROOVY || lex == LEX_SCALA; } static inline bool _hasRegex(int lex) { // Javascript /regex/ return lex == LEX_JS || lex == LEX_GROOVY || lex == LEX_AS || lex == LEX_HX || lex == LEX_AWK; } static inline bool _hasTripleVerbatim(int lex) { return lex == LEX_GROOVY || lex == LEX_SCALA; } static inline bool _sharpComment(int lex) { return lex == LEX_AWK || lex == LEX_JAM; } static inline bool _hasXML(int lex) { return lex == LEX_JS || lex == LEX_AS || lex == LEX_SCALA; } static inline bool _squareBraceAfterType(int lex) { return lex == LEX_JAVA || lex == LEX_CS || lex == LEX_JS || lex == LEX_AS || lex == LEX_HX || lex == LEX_GROOVY || lex == LEX_SCALA; } static inline bool IsDStrFix(int ch) { return (ch < 0x80) && (ch == 'c' || ch == 'w' || ch == 'd'); } static inline bool _use2ndKeyword(int lex) { return lex == LEX_OBJC; } static inline bool _use2ndKeyword2(int lex) { return lex == LEX_CPP || lex == LEX_OBJC; } #define strequ(str1, str2) (!strcmp(str1, str2)) static inline bool IsSpaceEquiv(int state) { // including SCE_C_DEFAULT, SCE_C_COMMENT, SCE_C_COMMENTLINE // SCE_C_COMMENTDOC, SCE_C_COMMENTLINEDOC, SCE_C_COMMENTDOC_TAG, SCE_C_COMMENTDOC_TAG_XML return (state < SCE_C_IDENTIFIER) || (state == SCE_C_DNESTEDCOMMENT); } static inline bool IsEscapeChar(int ch) { return ch == '\\' || ch == '\'' || ch == '\"' || ch == '$'; // PHP } /*static const char* const cppWordLists[] = { "Primary keywords", // SCE_C_WORD "Type keywords", // SCE_C_WORD2 "Preprocessor", // SCE_C_PREPROCESSOR #preprocessor "Directive", // SCE_C_DIRECTIVE @directive @anotation // global "Attribute", // SCE_C_ATTRIBUTE [attribute] "Class", // SCE_C_CLASS "Interface", // SCE_C_INTERFACE "Enumeration", // SCE_C_ENUMERATION "Constant", // SCE_C_CONSTANT "2nd Language Keyword" // SCE_C_2NDWORD "2nd Language Type Keyword" // SCE_C_2NDWORD2 "Inline Asm Instruction" // SCE_C_ASM_INSTRUCTION "Inline Asm Register" // SCE_C_ASM_REGISTER 0 };*/ #define LEX_BLOCK_MASK_ASM 0x0001 #define LEX_BLOCK_MASK_DEFINE 0x0002 #define LEX_BLOCK_MASK_TYPEDEF 0x0004 #define LEX_BLOCK_UMASK_ASM 0xFFFE #define LEX_BLOCK_UMASK_ALL 0xFFFD #define DOC_TAG_AT 1 /// @param \ref #define DOC_TAG_INLINE_AT 2 /// {@code x+y} #define DOC_TAG_OPEN_XML 3 /// <param name="path">file path #define DOC_TAG_CLOSE_XML 4 /// </param> static void ColouriseCppDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList keywordLists, Accessor &styler) { const WordList &keywords = *keywordLists[0]; const WordList &keywords2 = *keywordLists[1]; const WordList &keywords3 = *keywordLists[2]; const WordList &keywords4 = *keywordLists[3]; // global const WordList &kwAttribute = *keywordLists[4]; const WordList &kwClass = *keywordLists[5]; const WordList &kwInterface = *keywordLists[6]; const WordList &kwEnumeration = *keywordLists[7]; const WordList &kwConstant = *keywordLists[8]; // 2nd const WordList &kw2ndKeyword = *keywordLists[9]; const WordList &kw2ndKeyword2 = *keywordLists[10]; const WordList &kwAsmInstruction = *keywordLists[11]; const WordList &kwAsmRegister = *keywordLists[12]; static bool isObjCSource = false; const int lexType = styler.GetPropertyInt("lexer.lang.type", LEX_CPP); if (lexType == LEX_PHP && startPos == 0) { initStyle = SCE_C_XML_DEFAULT; } Sci_Position lineCurrent = styler.GetLine(startPos); int curLineState = (lineCurrent > 0) ? styler.GetLineState(lineCurrent-1) : 0; int lineState = (curLineState >> 24); int numCBrace = (curLineState >> 18) & 0x3F; int numSBrace = (curLineState >> 13) & 0x1F; int numRBrace = (curLineState >> 8) & 0x1F; int curNcLevel = (curLineState >> 4) & 0x0F; int numDTSBrace = (curLineState ) & 0x0F; #define _MakeState() ((lineState << 24)|(numCBrace << 18)|(numSBrace << 13)|(numRBrace << 8)|(curNcLevel << 4)|numDTSBrace) #define _UpdateLineState() styler.SetLineState(lineCurrent, _MakeState()) #define _UpdateCurLineState() lineCurrent = styler.GetLine(sc.currentPos); \ styler.SetLineState(lineCurrent, _MakeState()) static char heredoc[256]; static Sci_PositionU heredoc_len; int outerStyle = SCE_C_DEFAULT; int varType = 0; int docTagType = 0; int chPrevNonWhite = ' '; int visibleChars = 0; bool isTypeDefine = false; bool lastWordWasUUID = false; bool lastWordWasGoto = false; bool lastWordWasAsm = false; bool lastWordWasAttr = false; int lastPPDefineWord = 0; bool continuationLine = false; bool isPragmaPreprocessor = false; bool isPreprocessorWord = false; bool isIncludePreprocessor = false; bool isMessagePreprocessor = false; bool followsReturn = false; bool followsPostfixOperator = false; bool isTripleSingle = false; bool isAssignStmt = false; if (initStyle == SCE_C_COMMENTLINE || initStyle == SCE_C_COMMENTLINEDOC || initStyle == SCE_C_PREPROCESSOR) { // Set continuationLine if last character of previous line is '\' if (lineCurrent > 0) { int chBack = styler.SafeGetCharAt(startPos-1, '\0'); int chBack2 = styler.SafeGetCharAt(startPos-2, '\0'); int lineEndChar = '!'; if (chBack2 == '\r' && chBack == '\n') { lineEndChar = styler.SafeGetCharAt(startPos-3, '\0'); } else if (chBack == '\n' || chBack == '\r') { lineEndChar = chBack2; } continuationLine = lineEndChar == '\\'; } } // look back to set chPrevNonWhite properly for better regex colouring if (startPos > 0) { Sci_Position back = startPos; while (--back && IsSpaceEquiv(styler.StyleAt(back))); if (styler.StyleAt(back) == SCE_C_OPERATOR) { chPrevNonWhite = styler.SafeGetCharAt(back); } } StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.atLineStart) { if (sc.state == SCE_C_STRING || sc.state == SCE_C_CHARACTER) { // Prevent SCE_C_STRINGEOL from leaking back to previous line which // ends with a line continuation by locking in the state upto this position. sc.SetState(sc.state); } // Reset states to begining of colourise so no surprises // if different sets of lines lexed. visibleChars = 0; lastWordWasUUID = false; lastWordWasGoto = false; lastPPDefineWord = 0; followsReturn = false; followsPostfixOperator = false; isPreprocessorWord = false; isPragmaPreprocessor = false; isIncludePreprocessor = false; isMessagePreprocessor = false; if (!continuationLine) { lineState &= LEX_BLOCK_UMASK_ALL; } _UpdateCurLineState(); } if (sc.atLineEnd) { _UpdateLineState(); lineCurrent++; } // Determine if the current state should terminate. switch (sc.state) { case SCE_C_OPERATOR: sc.SetState(SCE_C_DEFAULT); break; case SCE_C_NUMBER: if (!iswordstart(sc.ch)) { // if ((sc.ch == '+' || sc.ch == '-') && ( (sc.chPrev == 'E' || sc.chPrev == 'e') || (sc.chPrev == 'P' || sc.chPrev == 'p'))) { sc.Forward(); } else if (sc.ch == '.' && sc.chNext != '.') { sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.ch == '\'' && lexType == LEX_CPP) { sc.Forward(); } else { sc.SetState(SCE_C_DEFAULT); } } break; case SCE_C_IDENTIFIER: _label_identifier: if (!(iswordstart(sc.ch) || (sc.ch == '-' && (lexType == LEX_JAM)))) { char s[256] = {0}; if (lexType == LEX_PHP) sc.GetCurrentLowered(s, sizeof(s)); else sc.GetCurrent(s, sizeof(s)); followsReturn = false; //int len = static_cast<int>(strlen(s)); //bool pps = (len > 4 && s[0] == '_' && s[1] == '_' && s[len - 1] == '_' && s[len - 2] == '_'); //char tu[256] = {0}; //if (pps) // strncpy(tu, &s[2], len - 4); // __attribute__() bool hasAttr = (lexType == LEX_CPP || lexType == LEX_OBJC || isObjCSource || lexType == LEX_CS); bool mayAttr = lastWordWasAttr && (numRBrace > 0 || (lineState & LEX_BLOCK_MASK_DEFINE)); bool mayCSAttr = (lexType == LEX_CS) && numSBrace == 1 && numRBrace == 0; const char nextChar = LexGetNextChar(sc.currentPos, styler); if (lastPPDefineWord) { if (lastPPDefineWord == 2 && strcmp(s, "defined") == 0) sc.ChangeState(SCE_C_WORD); else if (sc.ch == '(') sc.ChangeState(SCE_C_MACRO2); else sc.ChangeState(SCE_C_MACRO); if (lastPPDefineWord != 2) lastPPDefineWord = 0; } else if (lexType == LEX_CS && isAssignStmt && keywords4.InList(s)) { sc.ChangeState(SCE_C_DIRECTIVE); } else if ((lineState & LEX_BLOCK_MASK_ASM) && kwAsmInstruction.InList(s)) { sc.ChangeState(SCE_C_ASM_INSTRUCTION); lastWordWasGoto = MakeLowerCase(s[0]) == 'j'; } else if ((lineState & LEX_BLOCK_MASK_ASM) && kwAsmRegister.InList(s)) { sc.ChangeState(SCE_C_ASM_REGISTER); } else if ((lexType == LEX_D) && (lineState & LEX_BLOCK_MASK_ASM) && kw2ndKeyword.InList(s)) { sc.ChangeState(SCE_C_2NDWORD); } else if (((s[0] == '#' || s[0] == '!') && keywords3.InList(&s[1])) || (isPreprocessorWord && keywords3.InList(s))) { sc.ChangeState(SCE_C_PREPROCESSOR); lastWordWasAttr = false; if (isPreprocessorWord) { isPreprocessorWord = false; char *ppw = s; if (s[0] == '#') ppw = &s[1]; isPragmaPreprocessor = strequ(ppw, "pragma") || strequ(ppw, "line"); isIncludePreprocessor = strcmp(ppw, "include") >= 0 || strequ(ppw, "import") || strequ(ppw, "using"); isMessagePreprocessor = strequ(ppw, "error") || strequ(ppw, "warning") || strequ(ppw, "message") || strequ(ppw, "region") || strequ(ppw, "endregion"); if (strequ(ppw, "define")) { lineState |= LEX_BLOCK_MASK_DEFINE; lastPPDefineWord = 1; } else if (strstr(ppw, "if")) { lastPPDefineWord = 2; } else if (strequ(ppw, "undef")) { lastPPDefineWord = 3; } } } else if (isPragmaPreprocessor) { isPragmaPreprocessor = false; sc.ChangeState(SCE_C_PREPROCESSOR); isMessagePreprocessor = strequ(s, "region") || strequ(s, "endregion") || strequ(s, "mark"); } else if ((!hasAttr || mayAttr || mayCSAttr) && kwAttribute.InList(s)) { sc.ChangeState(SCE_C_ATTRIBUTE); } else if (keywords.InList(s)) { sc.ChangeState(SCE_C_WORD); if (isAssignStmt && chPrevNonWhite == '=' && (strequ(s, "function") || strequ(s, "new"))) { isAssignStmt = false; } // asm __asm _asm lastWordWasAsm = strequ(s, "asm") || strequ(s, "__asm"); lastWordWasUUID = strequ(s, "uuid"); lastWordWasGoto = strequ(s, "goto") || strequ(s, "__label__") || strequ(s, "break") || strequ(s, "continue"); followsReturn = strequ(s, "return"); if (!isTypeDefine) isTypeDefine = strequ(s, "typedef"); if (!lastWordWasAttr) lastWordWasAttr = strequ(s, "__declspec") || strequ(s, "__attribute__"); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_C_WORD2); } else if (s[0] == '@' && _hasAnotation(lexType)) { sc.ChangeState(SCE_C_DIRECTIVE); while (iswordchar(sc.ch)) sc.Forward(); } else if (lexType != LEX_CS && s[0] == '@' && keywords4.InList(&s[1])) { sc.ChangeState(SCE_C_DIRECTIVE); if (lexType == LEX_CPP || lexType == LEX_OBJC || isObjCSource) { if (!isObjCSource) isObjCSource = true; if (!lastWordWasAttr) lastWordWasAttr = strequ(&s[1], "property"); } } else if (kwClass.InList(s)) { sc.ChangeState(SCE_C_CLASS); } else if (kwInterface.InList(s)) { sc.ChangeState(SCE_C_INTERFACE); } else if (lexType != LEX_PHP && kwEnumeration.InList(s)) { sc.ChangeState(SCE_C_ENUMERATION); } else if (nextChar == '(') { if (kwConstant.InListAbbreviated(s, '(')) sc.ChangeState(SCE_C_MACRO2); else sc.ChangeState(SCE_C_FUNCTION); } else if (kwConstant.InList(s)) { sc.ChangeState(SCE_C_CONSTANT); } else if ((isObjCSource || _use2ndKeyword(lexType)) && kw2ndKeyword.InList(s)) { sc.ChangeState(SCE_C_2NDWORD); } else if ((isObjCSource || _use2ndKeyword2(lexType)) && kw2ndKeyword2.InList(s)) { sc.ChangeState(SCE_C_2NDWORD2); } else if (lastWordWasGoto && (numCBrace > 0)) { sc.ChangeState(SCE_C_LABEL); lastWordWasGoto = false; } else if (sc.ch == ':' && sc.chNext != ':' && !(isAssignStmt) && (numCBrace > 0 && numSBrace == 0 && numRBrace == 0) && visibleChars == static_cast<int>(strlen(s))) { sc.ChangeState(SCE_C_LABEL); } else if (iswordchar(s[0]) && (IsASpace(sc.ch) || sc.ch == '[' || sc.ch == ')' || sc.ch == '>' || sc.ch == '*' || sc.ch == '&' || sc.ch == ':')) { bool is_class = false; Sci_PositionU pos = sc.currentPos; int next_char = IsASpace(sc.ch)? nextChar : sc.ch; if (sc.ch == ':' && sc.chNext == ':') { // C++, Java, PHP is_class = true; } else if (IsASpace(sc.ch) && iswordstart(next_char)) { is_class = true; if (isObjCSource && numSBrace > 0) { if (!IsUpperCase(s[0])) is_class = false; } } else if (next_char == ')' || next_char == '>' || next_char == '[' || next_char == '*' || next_char == '&') { while (IsASpace(styler.SafeGetCharAt(pos, '\0'))) pos++; pos++; while (IsASpace(styler.SafeGetCharAt(pos, '\0'))) pos++; int ch = styler.SafeGetCharAt(pos, '\0'); const bool next_is_word = iswordstart(ch); if (next_char == ')' || next_char == '>') { if (next_is_word || (ch == '(')) { pos = sc.currentPos - (uint32_t)strlen(s) -1; while (IsASpace(styler.SafeGetCharAt(pos, '\0'))) pos--; ch = styler.SafeGetCharAt(pos, '\0'); if (next_char == '>' && (ch == '<' || ch == ',')) { is_class = true; } else if (next_char == ')' && ch == '(') { pos--; while (IsASpace(styler.SafeGetCharAt(pos, '\0'))) pos--; ch = styler.SafeGetCharAt(pos, '\0'); if (ch == '=' || ch == '(') { is_class = true; } } } } else if (next_is_word) { pos++; while (iswordchar(styler.SafeGetCharAt(pos, '\0'))) pos++; while (IsASpace(styler.SafeGetCharAt(pos, '\0'))) pos++; ch = styler.SafeGetCharAt(pos, '\0'); if (ch == '=') { is_class = true; } else if (ch == ',' || ch == ';') { pos = sc.currentPos - (uint32_t)strlen(s) -1; while (IsASpace(styler.SafeGetCharAt(pos, '\0'))) pos--; ch = styler.SafeGetCharAt(pos, '\0'); if (iswordchar(ch) || ch == ';' || ch == '{') { is_class = true; } } } else if (ch == ')' || ch == '>' || ch == '*') { is_class = true; } else if (ch == ']' && _squareBraceAfterType(lexType)) { is_class = true; } } if (is_class) { sc.ChangeState(SCE_C_CLASS); } } if ((isIncludePreprocessor && (sc.ch == '<' || sc.ch == '\"')) || (isMessagePreprocessor && !(sc.ch == '\n' || sc.ch == '\r'))) { sc.SetState(SCE_C_STRING); if (sc.ch == '\"') { isIncludePreprocessor = false; //isMessagePreprocessor = false; } sc.Forward(); } else { sc.SetState(SCE_C_DEFAULT); } } break; case SCE_C_COMMENT: if (sc.Match('*', '/')) { sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } break; case SCE_C_COMMENTLINE: if (sc.atLineStart && !continuationLine) { sc.SetState(SCE_C_DEFAULT); } else if (lexType == LEX_PHP && sc.Match('?', '>')) { sc.SetState(SCE_C_XML_TAG); sc.Forward(); sc.ForwardSetState(SCE_C_XML_DEFAULT); } break; case SCE_C_COMMENTDOC: case SCE_C_COMMENTLINEDOC: if (sc.state == SCE_C_COMMENTDOC && sc.Match('*', '/')) { docTagType = 0; outerStyle = SCE_C_DEFAULT; sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.state == SCE_C_COMMENTLINEDOC && sc.atLineStart && !continuationLine) { docTagType = 0; outerStyle = SCE_C_DEFAULT; sc.SetState(SCE_C_DEFAULT); } else if (sc.state == SCE_C_COMMENTLINEDOC && lexType == LEX_PHP && sc.Match('?', '>')) { docTagType = 0; outerStyle = SCE_C_XML_DEFAULT; sc.SetState(SCE_C_XML_TAG); sc.Forward(); sc.ForwardSetState(SCE_C_XML_DEFAULT); } else if (sc.ch == '{' && sc.chNext == '@' && IsAlpha(sc.GetRelative(2))) { docTagType = DOC_TAG_INLINE_AT; outerStyle = sc.state; sc.SetState(SCE_C_COMMENTDOC_TAG); sc.Forward(); } else if ((sc.ch == '@' || sc.ch == '\\') && IsAlpha(sc.chNext) && (IsASpace(sc.chPrev) || sc.chPrev == '*' || sc.chPrev == '/' || sc.chPrev == '!')) { docTagType = DOC_TAG_AT; outerStyle = sc.state; sc.SetState(SCE_C_COMMENTDOC_TAG); } else if (sc.ch == '<' && IsAlpha(sc.chNext)) { docTagType = DOC_TAG_OPEN_XML; outerStyle = sc.state; sc.SetState(SCE_C_COMMENTDOC_TAG_XML); } else if (sc.ch == '<' && sc.chNext == '/' && IsAlpha(sc.GetRelative(2))) { docTagType = DOC_TAG_CLOSE_XML; outerStyle = sc.state; sc.SetState(SCE_C_COMMENTDOC_TAG_XML); sc.Forward(); } else if ((docTagType == DOC_TAG_INLINE_AT && sc.ch == '}') || (docTagType == DOC_TAG_OPEN_XML && ((sc.ch == '/' && sc.chNext == '>') || sc.ch == '>'))) { docTagType = 0; sc.SetState((sc.ch == '}') ? SCE_C_COMMENTDOC_TAG : SCE_C_COMMENTDOC_TAG_XML); sc.Forward(); if ((sc.chPrev == '/' && sc.ch == '>') || (sc.chPrev == '}' && sc.ch == '}')) sc.Forward(); bool ignore = false; if (sc.ch == '<' && (IsAlpha(sc.chNext) || (sc.chNext == '/' && IsAlpha(sc.GetRelative(2))))) { ignore = true; sc.SetState(SCE_C_COMMENTDOC_TAG_XML); sc.Forward(); docTagType = DOC_TAG_OPEN_XML; if (sc.ch == '/') { docTagType = DOC_TAG_CLOSE_XML; sc.Forward(); } } if (!ignore) { sc.SetState(outerStyle); } } break; case SCE_C_COMMENTDOC_TAG: case SCE_C_COMMENTDOC_TAG_XML: if (!iswordstart(sc.ch) && sc.ch != '-') { bool ignore = false; if (sc.ch == '>' || sc.ch == '}') { docTagType = 0; sc.Forward(); if (sc.ch == '<' && (IsAlpha(sc.chNext) || (sc.chNext == '/' && IsAlpha(sc.GetRelative(2))))) { ignore = true; sc.Forward(); docTagType = DOC_TAG_OPEN_XML; if (sc.ch == '/') { docTagType = DOC_TAG_CLOSE_XML; sc.Forward(); } } else if (sc.ch == '{' && sc.chNext == '@' && IsAlpha(sc.GetRelative(2))) { ignore = true; sc.SetState(SCE_C_COMMENTDOC_TAG); docTagType = DOC_TAG_INLINE_AT; sc.Forward(); } } if (!ignore) { sc.SetState(outerStyle); } } break; case SCE_C_DNESTEDCOMMENT: if (sc.Match('+', '/')) { if (curNcLevel > 0) --curNcLevel; sc.Forward(); if (curNcLevel == 0) { sc.ForwardSetState(SCE_C_DEFAULT); } } else if (sc.Match('/','+')) { ++curNcLevel; sc.Forward(); } break; case SCE_C_CHARACTER: if (sc.atLineEnd && !(lexType == LEX_PHP)) { sc.ChangeState(SCE_C_STRINGEOL); } else if (sc.ch == '\\' && IsEscapeChar(sc.chNext)) { sc.Forward(); } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_C_DEFAULT); } break; case SCE_C_STRINGEOL: if (sc.atLineStart) { outerStyle = SCE_C_DEFAULT; sc.SetState(SCE_C_DEFAULT); } break; case SCE_C_STRING: if (sc.atLineEnd) { if (lexType == LEX_HX || lexType == LEX_ASY || lexType == LEX_JAM || lexType == LEX_PHP) continue; else sc.ChangeState(SCE_C_STRINGEOL); } else if (isIncludePreprocessor && sc.ch == '>') { outerStyle = SCE_C_DEFAULT; sc.ForwardSetState(SCE_C_DEFAULT); isIncludePreprocessor = false; } else if (isMessagePreprocessor && sc.atLineEnd) { sc.ChangeState(SCE_C_STRINGEOL); isMessagePreprocessor = false; } else if (sc.ch == '\\' && IsEscapeChar(sc.chNext)) { sc.Forward(); } else if (lexType == LEX_PHP && sc.chPrev != '\\' && ( (sc.ch == '$' && iswordstart(sc.chNext)) || (sc.ch == '$' && sc.chNext == '{') || (sc.ch == '{' && sc.chNext == '$'))) { outerStyle = SCE_C_STRING; if (sc.ch == '{' || sc.chNext == '{') { varType = 2; ++numDTSBrace; sc.SetState(SCE_C_VARIABLE2); sc.Forward(2); } else { sc.SetState(SCE_C_VARIABLE); } } else if (sc.ch == '\"') { if ((lexType == LEX_D) && IsDStrFix(sc.chNext)) sc.Forward(); outerStyle = SCE_C_DEFAULT; sc.ForwardSetState(SCE_C_DEFAULT); } break; case SCE_C_STRINGRAW: if (sc.ch == '\"') { Sci_PositionU pos = sc.currentPos; Sci_PositionU len = 0; bool rawEnd = false; while (pos > startPos && len < 16) { char ch = styler.SafeGetCharAt(pos, '\0'); if (ch == ')') { rawEnd = true; break; } if (IsASpace(ch) || ch == '\\' || ch == '(' || ch == ')') { break; } pos--; len++; } if (rawEnd) { sc.ForwardSetState(SCE_C_DEFAULT); } } break; case SCE_C_DSTRINGX: // D if (sc.ch == '\"') { if (IsDStrFix(sc.chNext)) sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } break; case SCE_C_DSTRINGB: // D if (sc.ch == '`' && (lexType == LEX_JS || lexType == LEX_D || lexType == LEX_GO)) { if (lexType == LEX_D && IsDStrFix(sc.chNext)) sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } break; case SCE_C_DSTRINGQ: // D if (sc.ch == '\"') { sc.ForwardSetState(SCE_C_DEFAULT); } break; case SCE_C_DSTRINGT: // D if (sc.ch == '}') { if (numDTSBrace > 0) --numDTSBrace; if (numDTSBrace == 0) sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.ch == '{') { ++numDTSBrace; } break; case SCE_C_VARIABLE: if (!(iswordstart(sc.ch) || (sc.ch == '-' && lexType == LEX_JAM))) { if (lexType == LEX_PHP) { char s[256] = {0}; sc.GetCurrentLowered(s, sizeof(s)); if (kwEnumeration.InList(s)) { sc.ChangeState(SCE_C_ENUMERATION); if (outerStyle != SCE_C_DEFAULT && ((sc.ch == '-' && sc.chNext == '>') || sc.ch == '[')) { sc.SetState(SCE_C_VARIABLE); sc.Forward(2); } } } if (lexType == LEX_PHP && outerStyle != SCE_C_DEFAULT && ((sc.ch == '-' && sc.chNext == '>') || sc.ch == '[')) { sc.Forward(2); } else { if (outerStyle != SCE_C_DEFAULT && sc.ch == ']') { sc.Forward(); } sc.SetState(outerStyle); if (outerStyle == SCE_C_STRING && sc.ch == '\\' && IsEscapeChar(sc.chNext)) { sc.Forward(); } else if (outerStyle == SCE_C_STRING && sc.ch == '\"') { outerStyle = SCE_C_DEFAULT; sc.ForwardSetState(SCE_C_DEFAULT); } } } break; case SCE_C_VARIABLE2: if ((varType == 1 && sc.ch == ')') || (varType == 2 && sc.ch == '}')) { if (numDTSBrace > 0) { --numDTSBrace; } if (numDTSBrace == 0) { sc.Forward(); if (varType == 2 && sc.ch == '}') sc.Forward(); varType = 0; sc.SetState(outerStyle); if (outerStyle == SCE_C_STRING && sc.ch == '\"') { outerStyle = SCE_C_DEFAULT; sc.ForwardSetState(SCE_C_DEFAULT); } } } else if ((varType == 1 && sc.Match('$', '(')) || (varType == 2 && sc.Match('$', '{'))) { ++numDTSBrace; sc.Forward(); } break; case SCE_C_REGEX: if (sc.atLineStart && !(lexType & LEX_AWK)) { sc.SetState(SCE_C_DEFAULT); } else if (sc.ch == '/') { sc.Forward(); while ((sc.ch < 0x80) && islower(sc.ch)) sc.Forward(); // gobble regex flags sc.SetState(SCE_C_DEFAULT); } else if (sc.ch == '\\') { // Gobble up the quoted character if (sc.chNext == '\\' || sc.chNext == '/') { sc.Forward(); } } break; case SCE_C_VERBATIM: if (isObjCSource && sc.ch == '\\' && IsEscapeChar(sc.chNext)) { sc.Forward(); } else if (sc.ch == '\"') { if (sc.chNext == '\"') { sc.Forward(); } else { if ((lexType == LEX_D) && IsDStrFix(sc.chNext)) sc.Forward(); sc.ForwardSetState(SCE_C_DEFAULT); } } break; case SCE_C_TRIPLEVERBATIM: if (sc.ch == '\\' && IsEscapeChar(sc.chNext)) { sc.Forward(); } else if (isTripleSingle && sc.Match("\'\'\'")) { isTripleSingle = false; sc.Forward(2); sc.ForwardSetState(SCE_C_DEFAULT); } else if (sc.Match("\"\"\"")) { sc.Forward(2); sc.ForwardSetState(SCE_C_DEFAULT); } break; case SCE_C_UUID: if (sc.ch == '\"') { sc.ChangeState(SCE_C_STRING); sc.Forward(); } if (sc.ch == ')') { sc.SetState(SCE_C_DEFAULT); } break; // for Smali case SCE_C_2NDWORD2: // instruction case SCE_C_DIRECTIVE: case SCE_C_LABEL: if (!(iswordstart(sc.ch) || sc.ch == '-' || sc.ch == '.')) { sc.SetState(SCE_C_DEFAULT); } break; case SCE_C_ASM_REGISTER: if (!IsADigit(sc.ch)) { sc.SetState(SCE_C_DEFAULT); } break; // case SCE_C_XML_TAG: // PHP, Scala, ActionScript, Javascript if (lexType == LEX_PHP) { } else { if (sc.Match('<', '/') || sc.Match('/', '>')) { if (curNcLevel > 0) --curNcLevel; sc.Forward(); if (curNcLevel == 0) { while (sc.ch != '>') { sc.Forward(); } sc.ForwardSetState(SCE_C_DEFAULT); } } else if (sc.ch == '<' && sc.chNext != '/') { ++curNcLevel; sc.Forward(); } break; } break; case SCE_C_HEREDOC: // PHP if (sc.chPrev != '\\' && ( (sc.ch == '$' && iswordstart(sc.chNext)) || (sc.ch == '$' && sc.chNext == '{') || (sc.ch == '{' && sc.chNext == '$'))) { outerStyle = SCE_C_HEREDOC; if (sc.ch == '{' || sc.chNext == '{') { varType = 2; ++numDTSBrace; sc.SetState(SCE_C_VARIABLE2); sc.Forward(2); } else { sc.SetState(SCE_C_VARIABLE); } } else if ((visibleChars == 0) && LexMatch(sc.currentPos+1, styler, heredoc)) { sc.Forward(heredoc_len); outerStyle = SCE_C_DEFAULT; sc.ForwardSetState(SCE_C_DEFAULT); } break; case SCE_C_NOWDOC: // PHP if ((visibleChars == 0) && LexMatch(sc.currentPos+1, styler, heredoc)) { sc.Forward(heredoc_len); sc.ForwardSetState(SCE_C_DEFAULT); } break; } // Determine if a new state should be entered. if (sc.state == SCE_C_XML_DEFAULT) { if (lexType == LEX_PHP && sc.Match("<?php")) { sc.SetState(SCE_C_XML_TAG); sc.Forward(5); sc.SetState(SCE_C_DEFAULT); } } else if (sc.state == SCE_C_DEFAULT) { if (lexType == LEX_PHP && sc.Match("<?php")) { sc.SetState(SCE_C_XML_TAG); sc.Forward(5); sc.SetState(SCE_C_DEFAULT); } else if (((lexType == LEX_CS) && sc.Match('@', '\"')) || ((lexType == LEX_D) && sc.Match('r', '\"'))) { sc.SetState(SCE_C_VERBATIM); sc.Forward(); } else if (_hasTripleVerbatim(lexType) && sc.Match("\"\"\"")) { sc.SetState(SCE_C_TRIPLEVERBATIM); sc.Forward(2); } else if (lexType == LEX_GROOVY && sc.Match("\'\'\'")) { sc.SetState(SCE_C_TRIPLEVERBATIM); sc.Forward(2); isTripleSingle = true; } else if ((lexType == LEX_D) && sc.Match('x', '\"')) { sc.SetState(SCE_C_DSTRINGX); sc.Forward(); } else if ((lexType == LEX_D) && sc.Match('q', '\"')) { sc.SetState(SCE_C_DSTRINGQ); sc.Forward(); } else if ((lexType == LEX_D) && sc.Match('q', '{')) { ++numDTSBrace; sc.SetState(SCE_C_DSTRINGT); sc.Forward(); } else if (sc.ch == '`' && (lexType == LEX_JS || lexType == LEX_D || lexType == LEX_GO)) { sc.SetState(SCE_C_DSTRINGB); } else if (!_sharpComment(lexType) && sc.Match('/', '*')) { if (visibleChars == 0 && (sc.Match("/**") || sc.Match("/*!"))) { sc.SetState(SCE_C_COMMENTDOC); } else { sc.SetState(SCE_C_COMMENT); } sc.Forward(); } else if ((!(_sharpComment(lexType)) && sc.Match('/', '/')) || (lineCurrent == 0 && sc.Match('#', '!')) || ((_sharpComment(lexType) || lexType == LEX_PHP) && sc.ch == '#')) { if (visibleChars == 0 && ((sc.Match("///") && !sc.Match("////")) || sc.Match("//!"))) sc.SetState(SCE_C_COMMENTLINEDOC); else sc.SetState(SCE_C_COMMENTLINE); } else if (sc.ch == '$' && (lexType == LEX_JAM && sc.chNext == '(')) { ++numDTSBrace; if (sc.chNext == '(') varType = 1; else varType = 2; sc.SetState(SCE_C_VARIABLE2); sc.Forward(); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_C_NUMBER); } else if (sc.ch == '/') { // bug // RegExp only appears in assignment or function argument //if (_hasRegex(lexType) && (isAssignStmt || numRBrace > 0) && (strchr("([{=,:;!%^&*|?~+-", chPrevNonWhite) || followsReturn) bool isJsRegex = (isAssignStmt && (chPrevNonWhite == '=' || chPrevNonWhite == ':')) // assignment || (numRBrace > 0 && strchr("(,!&|", chPrevNonWhite)) // argument || (strchr("};", chPrevNonWhite)) || followsReturn; if (_hasRegex(lexType) && isJsRegex && !(chPrevNonWhite == '+' || chPrevNonWhite == '-' || followsPostfixOperator)) { sc.SetState(SCE_C_REGEX); // JavaScript's RegEx followsReturn = false; } else if ((lexType == LEX_D) && sc.chNext == '+'){ ++curNcLevel; sc.SetState(SCE_C_DNESTEDCOMMENT); sc.Forward(); } else { sc.SetState(SCE_C_OPERATOR); } } else if ((lexType == LEX_CPP || lexType == LEX_RC) && (sc.ch == 'u' || sc.ch == 'U' || sc.ch == 'L')) { int offset = 0; bool is_raw = false; bool isuchar = false; if (sc.chNext == '\"' || sc.chNext == '\'') { offset = 1; isuchar = sc.chNext == '\''; } else if (sc.chNext == 'R' && sc.GetRelative(2) == '\"') { offset = 2; is_raw = true; } else if (sc.chNext == '8' && sc.GetRelative(2) == 'R' && sc.GetRelative(3) == '\"') { offset = 3; is_raw = true; } if (!offset) { sc.SetState(SCE_C_IDENTIFIER); } else { if (is_raw) sc.SetState(SCE_C_STRINGRAW); else if (isuchar) sc.SetState(SCE_C_CHARACTER); else sc.SetState(SCE_C_STRING); sc.Forward(offset); } } else if (lexType == LEX_CPP && sc.ch == 'R' && sc.chNext == '\"') { sc.SetState(SCE_C_STRINGRAW); sc.Forward(); } else if (lexType == LEX_JAM && sc.ch == '\\' && IsEscapeChar(sc.chNext)) { sc.Forward(); } else if (sc.ch == '\"') { isIncludePreprocessor = false; //isMessagePreprocessor = false; sc.SetState(SCE_C_STRING); } else if (sc.ch == '\'') { if (lexType == LEX_SCALA && !(sc.chNext == '\\' || (sc.chNext != '\'' && sc.GetRelative(2) == '\''))) sc.SetState(SCE_C_OPERATOR); else sc.SetState(SCE_C_CHARACTER); } else if (_hasPreprocessor(lexType) && sc.ch == '#') { if (lineState & LEX_BLOCK_MASK_DEFINE) { sc.SetState(SCE_C_OPERATOR); if (sc.chNext == '#' || sc.chNext == '@') { sc.Forward(2); if (iswordstart(sc.ch)) sc.SetState(SCE_C_IDENTIFIER); else sc.SetState(SCE_C_DEFAULT); } } else if (visibleChars == 0) { isPreprocessorWord = true; if (isspacechar(sc.chNext)) { sc.SetState(SCE_C_PREPROCESSOR); sc.ForwardSetState(SCE_C_DEFAULT); } else if (iswordstart(sc.chNext)) { sc.SetState(SCE_C_IDENTIFIER); } } } else if (sc.ch == '$' && (lexType == LEX_HX || lexType == LEX_AWK || lexType == LEX_PHP)) { if (lexType == LEX_PHP && !iswordstart(sc.chNext)) sc.SetState(SCE_C_OPERATOR); else sc.SetState(SCE_C_VARIABLE); } else if (iswordstart(sc.ch) || (iswordstart(sc.chNext) && (lexType != LEX_PHP) && (sc.ch == '@' || (sc.ch == '#' && (lexType == LEX_D || lexType == LEX_HX || lexType == LEX_JAM))))) { sc.SetState(SCE_C_IDENTIFIER); } else if (sc.ch == '.') { sc.SetState(SCE_C_OPERATOR); if (sc.chNext == '.') sc.Forward(); } else if (lexType == LEX_PHP && sc.Match('?', '>')) { sc.SetState(SCE_C_XML_TAG); sc.Forward(); sc.ForwardSetState(SCE_C_XML_DEFAULT); } else if (sc.ch == '<') { if (_hasXML(lexType) && chPrevNonWhite == '=') { sc.SetState(SCE_C_XML_TAG); if (sc.chNext != '/') { ++curNcLevel; } sc.Forward(); } else if (isIncludePreprocessor) { sc.SetState(SCE_C_STRING); } else if (lexType == LEX_PHP && sc.chNext == '<' && sc.GetRelative(2) == '<') { // <<<EOT, <<<"EOT", <<<'EOT' if (sc.GetRelative(3) == '\'') sc.SetState(SCE_C_NOWDOC); else sc.SetState(SCE_C_HEREDOC); sc.Forward(3); if (sc.ch == '\'' || sc.ch == '\"') sc.Forward(); heredoc_len = LexGetRange(sc.currentPos + 1, styler, iswordstart, heredoc, sizeof(heredoc)); sc.Forward(heredoc_len); if (sc.ch == '\'' || sc.ch == '\"') sc.Forward(); } else { sc.SetState(SCE_C_OPERATOR); } } else if (isoperator(static_cast<char>(sc.ch)) || ((lexType == LEX_CS || lexType == LEX_D || lexType == LEX_JS) && sc.ch == '$') || sc.ch == '@' || (lexType == LEX_PHP && sc.ch == '\\')) { sc.SetState(SCE_C_OPERATOR); isPragmaPreprocessor = false; if ((sc.ch == '+' && sc.chPrev == '+') || (sc.ch == '-' && sc.chPrev == '-')) followsPostfixOperator = true; else followsPostfixOperator = false; if (lastWordWasUUID && sc.ch == '(') { sc.ForwardSetState(SCE_C_UUID); lastWordWasUUID = false; isAssignStmt = false; } if (sc.ch == '=' && !(sc.chPrev == '=' || sc.chNext == '=')) { isAssignStmt = true; } if (sc.ch == ';') { isAssignStmt = false; lastWordWasGoto = false; followsReturn = false; //if (numCBrace == 0) isTypeDefine = false; } if (sc.ch == '{') { if (lastWordWasAsm) { lineState |= LEX_BLOCK_MASK_ASM; lastWordWasAsm = false; } //if (isTypeDefine) { // lineState |= LEX_BLOCK_MASK_TYPEDEF; // isTypeDefine = false; //} } else if (sc.ch == '}') { lastWordWasGoto = false; followsReturn = false; lastWordWasAsm = false; if (lineState & LEX_BLOCK_MASK_ASM) { lineState &= LEX_BLOCK_UMASK_ASM; } } if(!(lineState & LEX_BLOCK_MASK_DEFINE)) { if (sc.ch == '{') { ++numCBrace; } else if (sc.ch == '}') { if (numCBrace > 0) --numCBrace; } else if (sc.ch == '(') { ++numRBrace; } else if (sc.ch == ')') { if (numRBrace > 0) --numRBrace; if (lastWordWasAttr && numRBrace == 0) lastWordWasAttr = false; } else if (sc.ch == '[') { ++numSBrace; } else if (sc.ch == ']') { if (numSBrace > 0) --numSBrace; } } } } // Handle line continuation generically. if (sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { lineCurrent++; sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continuationLine = true; continue; } } if (!(isspacechar(sc.ch) || IsSpaceEquiv(sc.state))) { chPrevNonWhite = sc.ch; visibleChars++; } continuationLine = false; } if (sc.state == SCE_C_IDENTIFIER) goto _label_identifier; sc.Complete(); } static bool IsCppDefineLine(Sci_Position line, LexAccessor &styler, Sci_Position &DefinePos) { Sci_Position pos = styler.LineStart(line); Sci_Position endPos = styler.LineStart(line + 1) - 1; pos = LexSkipSpaceTab(pos, endPos, styler); if (styler[pos] == '#' && styler.StyleAt(pos) == SCE_C_PREPROCESSOR){ pos++; pos = LexSkipSpaceTab(pos, endPos, styler); if (styler.Match(pos, "define") && IsASpaceOrTab(styler[pos + 6])) { DefinePos = pos + 6; return true; } } return false; } // also used in LexAsm.cxx bool IsCppInDefine(Sci_Position currentPos, LexAccessor &styler) { Sci_Position line = styler.GetLine(currentPos); Sci_Position pos; if (IsCppDefineLine(line, styler, pos)) { if (pos < currentPos) return true; } line--; while (line > 0 && IsBackslashLine(line, styler) && !IsCppDefineLine(line, styler, pos)) line--; if (line >= 0 && IsCppDefineLine(line, styler, pos) && IsBackslashLine(line, styler)) { return true; } return false; } static bool IsCppFoldingLine(Sci_Position line, LexAccessor &styler, int kind) { Sci_Position startPos = styler.LineStart(line); Sci_Position endPos = styler.LineStart(line + 1) - 1; Sci_Position pos = LexSkipSpaceTab(startPos, endPos, styler); int stl = styler.StyleAt(pos); char ch = styler[pos]; switch (kind) { //case 0: // return (ch == '/' || ch == '#') && (stl == SCE_C_COMMENTLINE || stl == SCE_C_COMMENTLINEDOC); case 1: return stl == SCE_C_WORD && (ch == 'i' || ch == 'u' || ch == 't') && (styler.Match(pos, "using") || styler.Match(pos, "import") || styler.Match(pos, "typedef")); case 2: return stl == SCE_C_DIRECTIVE && (ch == '@') && (styler.Match(pos, "@property") || styler.Match(pos, "@synthesize")); default: if (!(stl == SCE_C_PREPROCESSOR && (ch == '#' || ch == '!'))) return false; pos++; pos = LexSkipSpaceTab(pos, endPos, styler); ch = styler[pos]; if (kind == 3 && (ch == 'i' || ch == 'u')) { return styler.Match(pos, "include") || styler.Match(pos, "using") || styler.Match(pos, "import"); } else if (kind == 4 && ch == 'd') { return styler.Match(pos, "define") && !IsBackslashLine(line, styler); // multi-line #define } else if (kind == 5 && ch == 'u') { return styler.Match(pos, "undef"); } return false; } } #define IsCommentLine(line) IsLexCommentLine(line, styler, MultiStyle(SCE_C_COMMENTLINE, SCE_C_COMMENTLINEDOC)) //#define IsCommentLine(line) IsCppFoldingLine(line, styler, 0) #define IsUsingLine(line) IsCppFoldingLine(line, styler, 1) //#define IsPropertyLine(line) IsCppFoldingLine(line, styler, 2) #define IsIncludeLine(line) IsCppFoldingLine(line, styler, 3) #define IsDefineLine(line) IsCppFoldingLine(line, styler, 4) #define IsUnDefLine(line) IsCppFoldingLine(line, styler, 5) static inline bool IsStreamCommentStyle(int style) { return style == SCE_C_COMMENT || style == SCE_C_COMMENTDOC || style == SCE_C_COMMENTDOC_TAG || style == SCE_C_COMMENTDOC_TAG_XML; } static inline bool IsHear_NowDocStyle(int style) { return style == SCE_C_HEREDOC || style == SCE_C_NOWDOC; } static bool IsOpenBraceLine(Sci_Position line, LexAccessor &styler) { // above line Sci_Position startPos = styler.LineStart(line-1); Sci_Position endPos = styler.LineStart(line)-1; Sci_Position pos = LexSkipSpaceTab(startPos, endPos, styler); char ch = styler[pos]; int stl = styler.StyleAt(pos); if (ch == '\r' || ch == '\n' || IsSpaceEquiv(stl) || (stl == SCE_C_PREPROCESSOR || stl == SCE_C_XML_TAG)) return false; while (endPos >= pos && isspacechar(styler[endPos])) endPos--; ch = styler[endPos]; stl = styler.StyleAt(endPos); if (stl == SCE_C_OPERATOR && !(ch == ')' || ch == '>' || ch == '=' || ch == ':' || ch == ']' || ch == '^' || ch == '.' || ch == ';')) return false; //if (styler[endPos-1] == '\n' || styler[endPos-1] == '\r' // || (styler.StyleAt(endPos) == SCE_C_OPERATOR // && !(ch == ')' || ch == '>' || ch == '=' || ch == ':' || ch == ']'))) //return false; // current line startPos = styler.LineStart(line); endPos = styler.LineStart(line + 1) - 1; pos = LexSkipSpaceTab(startPos, endPos, styler); // only '{' line if (styler.StyleAt(pos) == SCE_C_OPERATOR && styler[pos] == '{') { return true; //pos++; //pos = LexSkipSpaceTab(pos, endPos, styler); //ch = styler[pos]; //stl = styler.StyleAt(pos); //return (ch == '\n') || (ch == '\r') || IsSpaceEquiv(stl); } return false; } static void FoldCppDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList, Accessor &styler) { if (styler.GetPropertyInt("fold") == 0) return; const bool foldComment = styler.GetPropertyInt("fold.comment", 1) != 0; const bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor", 1) != 0; //const bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; const bool foldCompact = styler.GetPropertyInt("fold.compact", 0) != 0; const int lexType = styler.GetPropertyInt("lexer.lang.type", LEX_CPP); const bool hasPreprocessor = _hasPreprocessor(lexType); Sci_PositionU endPos = startPos + length; int visibleChars = 0; Sci_Position lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) levelCurrent = styler.LevelAt(lineCurrent - 1) >> 16; //int levelMinCurrent = levelCurrent; int levelNext = levelCurrent; int chNext = styler[startPos]; int style = initStyle; int styleNext = styler.StyleAt(startPos); bool isObjCProtocol = false; for (Sci_PositionU i = startPos; i < endPos; i++) { int ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (foldComment && atEOL && IsCommentLine(lineCurrent)) { if(!IsCommentLine(lineCurrent - 1) && IsCommentLine(lineCurrent + 1)) levelNext++; else if(IsCommentLine(lineCurrent - 1) && !IsCommentLine(lineCurrent + 1)) levelNext--; } if (foldComment && IsStreamCommentStyle(style) && !IsCommentLine(lineCurrent)) { if (!IsStreamCommentStyle(stylePrev)) { levelNext++; } else if (!IsStreamCommentStyle(styleNext) && !atEOL) { levelNext--; } } if (lexType == LEX_D && foldComment && style == SCE_C_DNESTEDCOMMENT) { if (ch == '/' && chNext == '+') levelNext++; else if (ch == '+' && chNext == '/') levelNext--; } if (lexType == LEX_PHP && IsHear_NowDocStyle(style)) { if (!IsHear_NowDocStyle(stylePrev)) { levelNext++; } else if (!IsHear_NowDocStyle(styleNext) && !atEOL) { levelNext--; } } if (style == SCE_C_TRIPLEVERBATIM) { if (stylePrev != SCE_C_TRIPLEVERBATIM) { levelNext++; } else if (styleNext != SCE_C_TRIPLEVERBATIM && !atEOL) { levelNext--; } } if (atEOL && IsUsingLine(lineCurrent)) { if(!IsUsingLine(lineCurrent-1) && IsUsingLine(lineCurrent+1)) levelNext++; else if(IsUsingLine(lineCurrent-1) && !IsUsingLine(lineCurrent+1)) levelNext--; } //if (hasPreprocessor && atEOL && IsPropertyLine(lineCurrent)) { // if(!IsPropertyLine(lineCurrent-1) && IsPropertyLine(lineCurrent+1)) // levelNext++; // else if(IsPropertyLine(lineCurrent-1) && !IsPropertyLine(lineCurrent+1)) // levelNext--; //} if (hasPreprocessor && atEOL && IsIncludeLine(lineCurrent)) { if(!IsIncludeLine(lineCurrent-1) && IsIncludeLine(lineCurrent+1)) levelNext++; else if(IsIncludeLine(lineCurrent-1) && !IsIncludeLine(lineCurrent+1)) levelNext--; } if (hasPreprocessor && atEOL && IsDefineLine(lineCurrent)) { if(!IsDefineLine(lineCurrent-1) && IsDefineLine(lineCurrent+1)) levelNext++; else if(IsDefineLine(lineCurrent-1) && !IsDefineLine(lineCurrent+1)) levelNext--; } if (hasPreprocessor && atEOL && IsUnDefLine(lineCurrent)) { if(!IsUnDefLine(lineCurrent-1) && IsUnDefLine(lineCurrent+1)) levelNext++; else if(IsUnDefLine(lineCurrent-1) && !IsUnDefLine(lineCurrent+1)) levelNext--; } if (atEOL && !IsStreamCommentStyle(style) && IsBackslashLine(lineCurrent, styler) && !IsBackslashLine(lineCurrent-1, styler)) { levelNext++; } if (atEOL && !IsStreamCommentStyle(style) && !IsBackslashLine(lineCurrent, styler) && IsBackslashLine(lineCurrent-1, styler)) { levelNext--; } if (atEOL && !(hasPreprocessor && IsCppInDefine(i, styler)) && IsOpenBraceLine(lineCurrent+1, styler)) { levelNext++; } if ((hasPreprocessor || lexType == LEX_HX) && foldPreprocessor && (ch == '#') && style == SCE_C_PREPROCESSOR) { Sci_Position pos = LexSkipSpaceTab(i+1, endPos, styler); if (styler.Match(pos, "if") || styler.Match(pos, "region")) { levelNext++; } else if (styler.Match(pos, "end")) { levelNext--; } else if (styler.Match(pos, "pragma")) { // #pragma region, #pragma endregion pos = LexSkipSpaceTab(pos+7, endPos, styler); if (styler.StyleAt(pos) == SCE_C_PREPROCESSOR) { if (styler.Match(pos, "region")) { levelNext++; } else if (styler.Match(pos, "endregion")) { levelNext--; } } } } // Objctive C/C++ if ((lexType == LEX_CPP || lexType == LEX_OBJC) && ch == '@' && style == SCE_C_DIRECTIVE) { if (styler.Match(i+1, "interface") || styler.Match(i+1, "implementation")) { levelNext++; } else if (styler.Match(i+1, "end")) { levelNext--; isObjCProtocol = false; } else if (styler.Match(i+1, "protocol")) { //char ch = LexGetNextChar(i+9, styler); if (LexGetNextChar(i+9, styler) != '(') { // @protocol() isObjCProtocol = true; levelNext++; } } } if (style == SCE_C_OPERATOR && !(hasPreprocessor && IsCppInDefine(i, styler))) { // maybe failed in multi-line define section, MFC's afx.h is a example if (ch == '{' && !(lineCurrent > 0 && visibleChars == 0 && IsOpenBraceLine(lineCurrent, styler))) { levelNext++; //if (levelMinCurrent > levelNext) { // levelMinCurrent = levelNext; //} } else if (ch == '}') { levelNext--; } else if (ch == '[' || ch == '(') { levelNext++; } else if (ch == ']' || ch == ')') { levelNext--; } if (isObjCProtocol && ch == ';') { isObjCProtocol = false; levelNext--; } } // Go if ((lexType == LEX_JS || lexType == LEX_GO) && style == SCE_C_DSTRINGB) { if (ch == '`') { if (styleNext == SCE_C_DSTRINGB) levelNext++; else if (stylePrev == SCE_C_DSTRINGB) levelNext--; } } // Resource Script if (style == SCE_C_WORD && stylePrev != SCE_C_WORD) { if (lexType == LEX_RC && (ch == 'B' || ch == 'E')) { if (styler.Match(i, "BEGIN")) { levelNext++; } else if (styler.Match(i, "END")) { levelNext--; } } } if (style == SCE_C_XML_TAG) { if (styler.Match(i, "</") || styler.Match(i, "/>") || styler.Match(i, "?>")) levelNext--; else if (ch == '<' && chNext != '/') levelNext++; } if (!isspacechar(ch)) visibleChars++; if (atEOL || (i == endPos-1)) { int levelUse = levelCurrent; //if (foldAtElse) { // levelUse = levelMinCurrent; //} int lev = levelUse | levelNext << 16; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (levelUse < levelNext) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelCurrent = levelNext; //levelMinCurrent = levelCurrent; visibleChars = 0; isObjCProtocol = false; } } } LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc);
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> // GJCNativeShare struct GJCNativeShare_t1694253608; // System.String struct String_t; // System.Object struct Il2CppObject; // UnityEngine.Texture2D struct Texture2D_t3884108195; // GJCNativeShare/OnNativeEvent struct OnNativeEvent_t3263283613; // System.IAsyncResult struct IAsyncResult_t2754620036; // System.AsyncCallback struct AsyncCallback_t1369114871; // GJCNativeShare/OnShareCancel struct OnShareCancel_t1124720659; // GJCNativeShare/OnShareSuccess struct OnShareSuccess_t2384183690; // InitShare struct InitShare_t1734853775; // System.Collections.IEnumerator struct IEnumerator_t3464575207; // InitShare/<TakeScreenshot>c__Iterator0 struct U3CTakeScreenshotU3Ec__Iterator0_t1360893940; // Main struct Main_t2390489; #include "class-internals.h" #include "codegen/il2cpp-codegen.h" #include "mscorlib_System_Array1146569071.h" #include "AssemblyU2DCSharp_U3CModuleU3E86524790.h" #include "AssemblyU2DCSharp_U3CModuleU3E86524790MethodDeclarations.h" #include "AssemblyU2DCSharp_GJCNativeShare1694253608.h" #include "AssemblyU2DCSharp_GJCNativeShare1694253608MethodDeclarations.h" #include "mscorlib_System_Void2863195528.h" #include "UnityEngine_UnityEngine_MonoBehaviour667441552MethodDeclarations.h" #include "mscorlib_System_String7231557.h" #include "UnityEngine_UnityEngine_Object3071478659MethodDeclarations.h" #include "mscorlib_System_Type2863145774MethodDeclarations.h" #include "UnityEngine_UnityEngine_GameObject3674682005MethodDeclarations.h" #include "UnityEngine_UnityEngine_Component3501516275MethodDeclarations.h" #include "mscorlib_System_Object4170816371MethodDeclarations.h" #include "mscorlib_System_Boolean476798718.h" #include "UnityEngine_UnityEngine_Object3071478659.h" #include "mscorlib_System_Type2863145774.h" #include "mscorlib_System_RuntimeTypeHandle2669177232.h" #include "UnityEngine_UnityEngine_GameObject3674682005.h" #include "UnityEngine_UnityEngine_Texture2D3884108195.h" #include "UnityEngine_UnityEngine_Debug4195163081MethodDeclarations.h" #include "UnityEngine_UnityEngine_Texture2D3884108195MethodDeclarations.h" #include "mscorlib_System_Convert1363677321MethodDeclarations.h" #include "mscorlib_ArrayTypes.h" #include "mscorlib_System_Byte2862609660.h" #include "mscorlib_System_Object4170816371.h" #include "mscorlib_System_String7231557MethodDeclarations.h" #include "AssemblyU2DCSharp_GJCNativeShare_OnShareSuccess2384183690MethodDeclarations.h" #include "AssemblyU2DCSharp_GJCNativeShare_OnShareSuccess2384183690.h" #include "AssemblyU2DCSharp_GJCNativeShare_OnShareCancel1124720659MethodDeclarations.h" #include "AssemblyU2DCSharp_GJCNativeShare_OnShareCancel1124720659.h" #include "AssemblyU2DCSharp_GJCNativeShare_OnNativeEvent3263283613MethodDeclarations.h" #include "AssemblyU2DCSharp_GJCNativeShare_OnNativeEvent3263283613.h" #include "mscorlib_System_IntPtr4010401971.h" #include "mscorlib_System_AsyncCallback1369114871.h" #include "AssemblyU2DCSharp_InitShare1734853775.h" #include "AssemblyU2DCSharp_InitShare1734853775MethodDeclarations.h" #include "UnityEngine_UnityEngine_Coroutine3621161934.h" #include "AssemblyU2DCSharp_InitShare_U3CTakeScreenshotU3Ec_1360893940MethodDeclarations.h" #include "AssemblyU2DCSharp_InitShare_U3CTakeScreenshotU3Ec_1360893940.h" #include "UnityEngine_UnityEngine_WaitForEndOfFrame2372756133MethodDeclarations.h" #include "UnityEngine_UnityEngine_Screen3187157168MethodDeclarations.h" #include "mscorlib_System_UInt3224667981.h" #include "mscorlib_System_Int321153838500.h" #include "UnityEngine_UnityEngine_WaitForEndOfFrame2372756133.h" #include "UnityEngine_UnityEngine_TextureFormat4189619560.h" #include "UnityEngine_UnityEngine_Rect4241904616.h" #include "UnityEngine_UnityEngine_Rect4241904616MethodDeclarations.h" #include "mscorlib_System_Single4291918972.h" #include "mscorlib_System_NotSupportedException1732551818MethodDeclarations.h" #include "mscorlib_System_NotSupportedException1732551818.h" #include "AssemblyU2DCSharp_Main2390489.h" #include "AssemblyU2DCSharp_Main2390489MethodDeclarations.h" // !!0 UnityEngine.GameObject::AddComponent<System.Object>() extern "C" Il2CppObject * GameObject_AddComponent_TisIl2CppObject_m337943659_gshared (GameObject_t3674682005 * __this, const MethodInfo* method); #define GameObject_AddComponent_TisIl2CppObject_m337943659(__this, method) (( Il2CppObject * (*) (GameObject_t3674682005 *, const MethodInfo*))GameObject_AddComponent_TisIl2CppObject_m337943659_gshared)(__this, method) // !!0 UnityEngine.GameObject::AddComponent<GJCNativeShare>() #define GameObject_AddComponent_TisGJCNativeShare_t1694253608_m1764644618(__this, method) (( GJCNativeShare_t1694253608 * (*) (GameObject_t3674682005 *, const MethodInfo*))GameObject_AddComponent_TisIl2CppObject_m337943659_gshared)(__this, method) #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void GJCNativeShare::.ctor() extern "C" void GJCNativeShare__ctor_m4148000627 (GJCNativeShare_t1694253608 * __this, const MethodInfo* method) { { MonoBehaviour__ctor_m2022291967(__this, /*hidden argument*/NULL); return; } } // System.Void GJCNativeShare::.cctor() extern "C" void GJCNativeShare__cctor_m3551871642 (Il2CppObject * __this /* static, unused */, const MethodInfo* method) { { return; } } extern "C" void DEFAULT_CALL _GJC_NativeShare(char*, char*); // System.Void GJCNativeShare::_GJC_NativeShare(System.String,System.String) extern "C" void GJCNativeShare__GJC_NativeShare_m1444674659 (Il2CppObject * __this /* static, unused */, String_t* ___text0, String_t* ___encodedMedia1, const MethodInfo* method) { typedef void (DEFAULT_CALL *PInvokeFunc) (char*, char*); // Marshaling of parameter '___text0' to native representation char* ____text0_marshaled = NULL; ____text0_marshaled = il2cpp_codegen_marshal_string(___text0); // Marshaling of parameter '___encodedMedia1' to native representation char* ____encodedMedia1_marshaled = NULL; ____encodedMedia1_marshaled = il2cpp_codegen_marshal_string(___encodedMedia1); // Native function invocation reinterpret_cast<PInvokeFunc>(_GJC_NativeShare)(____text0_marshaled, ____encodedMedia1_marshaled); // Marshaling cleanup of parameter '___text0' native representation il2cpp_codegen_marshal_free(____text0_marshaled); ____text0_marshaled = NULL; // Marshaling cleanup of parameter '___encodedMedia1' native representation il2cpp_codegen_marshal_free(____encodedMedia1_marshaled); ____encodedMedia1_marshaled = NULL; } extern "C" void DEFAULT_CALL _GJC_OpenAppStore(char*); // System.Void GJCNativeShare::_GJC_OpenAppStore(System.String) extern "C" void GJCNativeShare__GJC_OpenAppStore_m2743546025 (Il2CppObject * __this /* static, unused */, String_t* ___appID0, const MethodInfo* method) { typedef void (DEFAULT_CALL *PInvokeFunc) (char*); // Marshaling of parameter '___appID0' to native representation char* ____appID0_marshaled = NULL; ____appID0_marshaled = il2cpp_codegen_marshal_string(___appID0); // Native function invocation reinterpret_cast<PInvokeFunc>(_GJC_OpenAppStore)(____appID0_marshaled); // Marshaling cleanup of parameter '___appID0' native representation il2cpp_codegen_marshal_free(____appID0_marshaled); ____appID0_marshaled = NULL; } // GJCNativeShare GJCNativeShare::get_Instance() extern const Il2CppType* GJCNativeShare_t1694253608_0_0_0_var; extern Il2CppClass* GJCNativeShare_t1694253608_il2cpp_TypeInfo_var; extern Il2CppClass* Object_t3071478659_il2cpp_TypeInfo_var; extern Il2CppClass* Type_t_il2cpp_TypeInfo_var; extern Il2CppClass* GameObject_t3674682005_il2cpp_TypeInfo_var; extern const MethodInfo* GameObject_AddComponent_TisGJCNativeShare_t1694253608_m1764644618_MethodInfo_var; extern const uint32_t GJCNativeShare_get_Instance_m2894719076_MetadataUsageId; extern "C" GJCNativeShare_t1694253608 * GJCNativeShare_get_Instance_m2894719076 (Il2CppObject * __this /* static, unused */, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (GJCNativeShare_get_Instance_m2894719076_MetadataUsageId); s_Il2CppMethodIntialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare_t1694253608 * L_0 = ((GJCNativeShare_t1694253608_StaticFields*)GJCNativeShare_t1694253608_il2cpp_TypeInfo_var->static_fields)->get__instance_5(); IL2CPP_RUNTIME_CLASS_INIT(Object_t3071478659_il2cpp_TypeInfo_var); bool L_1 = Object_op_Equality_m3964590952(NULL /*static, unused*/, L_0, (Object_t3071478659 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_0066; } } { IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_2 = Type_GetTypeFromHandle_m3806905434(NULL /*static, unused*/, LoadTypeToken(GJCNativeShare_t1694253608_0_0_0_var), /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Object_t3071478659_il2cpp_TypeInfo_var); Object_t3071478659 * L_3 = Object_FindObjectOfType_m3820159265(NULL /*static, unused*/, L_2, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); ((GJCNativeShare_t1694253608_StaticFields*)GJCNativeShare_t1694253608_il2cpp_TypeInfo_var->static_fields)->set__instance_5(((GJCNativeShare_t1694253608 *)IsInstClass(L_3, GJCNativeShare_t1694253608_il2cpp_TypeInfo_var))); GJCNativeShare_t1694253608 * L_4 = ((GJCNativeShare_t1694253608_StaticFields*)GJCNativeShare_t1694253608_il2cpp_TypeInfo_var->static_fields)->get__instance_5(); bool L_5 = Object_op_Equality_m3964590952(NULL /*static, unused*/, L_4, (Object_t3071478659 *)NULL, /*hidden argument*/NULL); if (!L_5) { goto IL_0066; } } { GameObject_t3674682005 * L_6 = (GameObject_t3674682005 *)il2cpp_codegen_object_new(GameObject_t3674682005_il2cpp_TypeInfo_var); GameObject__ctor_m845034556(L_6, /*hidden argument*/NULL); NullCheck(L_6); GJCNativeShare_t1694253608 * L_7 = GameObject_AddComponent_TisGJCNativeShare_t1694253608_m1764644618(L_6, /*hidden argument*/GameObject_AddComponent_TisGJCNativeShare_t1694253608_m1764644618_MethodInfo_var); IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); ((GJCNativeShare_t1694253608_StaticFields*)GJCNativeShare_t1694253608_il2cpp_TypeInfo_var->static_fields)->set__instance_5(L_7); GJCNativeShare_t1694253608 * L_8 = ((GJCNativeShare_t1694253608_StaticFields*)GJCNativeShare_t1694253608_il2cpp_TypeInfo_var->static_fields)->get__instance_5(); NullCheck(L_8); GameObject_t3674682005 * L_9 = Component_get_gameObject_m1170635899(L_8, /*hidden argument*/NULL); GJCNativeShare_t1694253608 * L_10 = ((GJCNativeShare_t1694253608_StaticFields*)GJCNativeShare_t1694253608_il2cpp_TypeInfo_var->static_fields)->get__instance_5(); NullCheck(L_10); Type_t * L_11 = Object_GetType_m2022236990(L_10, /*hidden argument*/NULL); NullCheck(L_11); String_t* L_12 = VirtFuncInvoker0< String_t* >::Invoke(18 /* System.String System.Type::get_FullName() */, L_11); NullCheck(L_9); Object_set_name_m1123518500(L_9, L_12, /*hidden argument*/NULL); } IL_0066: { IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare_t1694253608 * L_13 = ((GJCNativeShare_t1694253608_StaticFields*)GJCNativeShare_t1694253608_il2cpp_TypeInfo_var->static_fields)->get__instance_5(); return L_13; } } // System.Void GJCNativeShare::NativeShare(System.String,UnityEngine.Texture2D) extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppClass* Object_t3071478659_il2cpp_TypeInfo_var; extern Il2CppClass* Convert_t1363677321_il2cpp_TypeInfo_var; extern Il2CppClass* GJCNativeShare_t1694253608_il2cpp_TypeInfo_var; extern Il2CppClass* String_t_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral3407556072; extern Il2CppCodeGenString* _stringLiteral1897080365; extern const uint32_t GJCNativeShare_NativeShare_m4035624863_MetadataUsageId; extern "C" void GJCNativeShare_NativeShare_m4035624863 (GJCNativeShare_t1694253608 * __this, String_t* ___text0, Texture2D_t3884108195 * ___texture1, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (GJCNativeShare_NativeShare_m4035624863_MetadataUsageId); s_Il2CppMethodIntialized = true; } ByteU5BU5D_t4260760469* V_0 = NULL; String_t* V_1 = NULL; { IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, _stringLiteral3407556072, /*hidden argument*/NULL); Texture2D_t3884108195 * L_0 = ___texture1; IL2CPP_RUNTIME_CLASS_INIT(Object_t3071478659_il2cpp_TypeInfo_var); bool L_1 = Object_op_Inequality_m1296218211(NULL /*static, unused*/, L_0, (Object_t3071478659 *)NULL, /*hidden argument*/NULL); if (!L_1) { goto IL_003a; } } { IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, _stringLiteral1897080365, /*hidden argument*/NULL); Texture2D_t3884108195 * L_2 = ___texture1; NullCheck(L_2); ByteU5BU5D_t4260760469* L_3 = Texture2D_EncodeToPNG_m2464495756(L_2, /*hidden argument*/NULL); V_0 = L_3; ByteU5BU5D_t4260760469* L_4 = V_0; IL2CPP_RUNTIME_CLASS_INIT(Convert_t1363677321_il2cpp_TypeInfo_var); String_t* L_5 = Convert_ToBase64String_m1841808901(NULL /*static, unused*/, L_4, /*hidden argument*/NULL); V_1 = L_5; String_t* L_6 = ___text0; String_t* L_7 = V_1; IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare__GJC_NativeShare_m1444674659(NULL /*static, unused*/, L_6, L_7, /*hidden argument*/NULL); goto IL_0045; } IL_003a: { String_t* L_8 = ___text0; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_9 = ((String_t_StaticFields*)String_t_il2cpp_TypeInfo_var->static_fields)->get_Empty_2(); IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare__GJC_NativeShare_m1444674659(NULL /*static, unused*/, L_8, L_9, /*hidden argument*/NULL); } IL_0045: { return; } } // System.Void GJCNativeShare::OpenAppStore(System.String) extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppClass* GJCNativeShare_t1694253608_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral3809390538; extern Il2CppCodeGenString* _stringLiteral922842170; extern const uint32_t GJCNativeShare_OpenAppStore_m403803719_MetadataUsageId; extern "C" void GJCNativeShare_OpenAppStore_m403803719 (GJCNativeShare_t1694253608 * __this, String_t* ___id0, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (GJCNativeShare_OpenAppStore_m403803719_MetadataUsageId); s_Il2CppMethodIntialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, _stringLiteral3809390538, /*hidden argument*/NULL); Debug_Log_m1731103628(NULL /*static, unused*/, _stringLiteral922842170, /*hidden argument*/NULL); String_t* L_0 = ___id0; IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare__GJC_OpenAppStore_m2743546025(NULL /*static, unused*/, L_0, /*hidden argument*/NULL); return; } } // System.Void GJCNativeShare::OnNativeShareSuccess(System.String) extern "C" void GJCNativeShare_OnNativeShareSuccess_m3021546199 (GJCNativeShare_t1694253608 * __this, String_t* ___result0, const MethodInfo* method) { { OnShareSuccess_t2384183690 * L_0 = __this->get_onShareSuccess_2(); if (!L_0) { goto IL_0017; } } { OnShareSuccess_t2384183690 * L_1 = __this->get_onShareSuccess_2(); String_t* L_2 = ___result0; NullCheck(L_1); OnShareSuccess_Invoke_m4182017767(L_1, L_2, /*hidden argument*/NULL); } IL_0017: { return; } } // System.Void GJCNativeShare::OnNativeShareCancel(System.String) extern "C" void GJCNativeShare_OnNativeShareCancel_m2670359854 (GJCNativeShare_t1694253608 * __this, String_t* ___result0, const MethodInfo* method) { { OnShareCancel_t1124720659 * L_0 = __this->get_onShareCancel_3(); if (!L_0) { goto IL_0017; } } { OnShareCancel_t1124720659 * L_1 = __this->get_onShareCancel_3(); String_t* L_2 = ___result0; NullCheck(L_1); OnShareCancel_Invoke_m1971944302(L_1, L_2, /*hidden argument*/NULL); } IL_0017: { return; } } // System.Void GJCNativeShare::OnOpenAppStoreSuccess(System.String) extern Il2CppClass* String_t_il2cpp_TypeInfo_var; extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral2950132297; extern Il2CppCodeGenString* _stringLiteral4092450787; extern const uint32_t GJCNativeShare_OnOpenAppStoreSuccess_m486788663_MetadataUsageId; extern "C" void GJCNativeShare_OnOpenAppStoreSuccess_m486788663 (GJCNativeShare_t1694253608 * __this, String_t* ___result0, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (GJCNativeShare_OnOpenAppStoreSuccess_m486788663_MetadataUsageId); s_Il2CppMethodIntialized = true; } { String_t* L_0 = ___result0; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_1 = String_Concat_m138640077(NULL /*static, unused*/, _stringLiteral2950132297, L_0, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); OnNativeEvent_t3263283613 * L_2 = __this->get_onOpenAppStore_4(); if (!L_2) { goto IL_002b; } } { OnNativeEvent_t3263283613 * L_3 = __this->get_onOpenAppStore_4(); NullCheck(L_3); OnNativeEvent_Invoke_m3080421028(L_3, _stringLiteral4092450787, /*hidden argument*/NULL); } IL_002b: { return; } } // System.Void GJCNativeShare::OnOpenAppStoreFinished(System.String) extern Il2CppClass* String_t_il2cpp_TypeInfo_var; extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral3145486136; extern Il2CppCodeGenString* _stringLiteral3685950610; extern const uint32_t GJCNativeShare_OnOpenAppStoreFinished_m1580580630_MetadataUsageId; extern "C" void GJCNativeShare_OnOpenAppStoreFinished_m1580580630 (GJCNativeShare_t1694253608 * __this, String_t* ___result0, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (GJCNativeShare_OnOpenAppStoreFinished_m1580580630_MetadataUsageId); s_Il2CppMethodIntialized = true; } { String_t* L_0 = ___result0; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_1 = String_Concat_m138640077(NULL /*static, unused*/, _stringLiteral3145486136, L_0, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); OnNativeEvent_t3263283613 * L_2 = __this->get_onOpenAppStore_4(); if (!L_2) { goto IL_002b; } } { OnNativeEvent_t3263283613 * L_3 = __this->get_onOpenAppStore_4(); NullCheck(L_3); OnNativeEvent_Invoke_m3080421028(L_3, _stringLiteral3685950610, /*hidden argument*/NULL); } IL_002b: { return; } } // System.Void GJCNativeShare::OnOpenAppStoreSuccessURL(System.String) extern Il2CppClass* String_t_il2cpp_TypeInfo_var; extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral2950132297; extern Il2CppCodeGenString* _stringLiteral3508327051; extern const uint32_t GJCNativeShare_OnOpenAppStoreSuccessURL_m820656156_MetadataUsageId; extern "C" void GJCNativeShare_OnOpenAppStoreSuccessURL_m820656156 (GJCNativeShare_t1694253608 * __this, String_t* ___result0, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (GJCNativeShare_OnOpenAppStoreSuccessURL_m820656156_MetadataUsageId); s_Il2CppMethodIntialized = true; } { String_t* L_0 = ___result0; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_1 = String_Concat_m138640077(NULL /*static, unused*/, _stringLiteral2950132297, L_0, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); OnNativeEvent_t3263283613 * L_2 = __this->get_onOpenAppStore_4(); if (!L_2) { goto IL_002b; } } { OnNativeEvent_t3263283613 * L_3 = __this->get_onOpenAppStore_4(); NullCheck(L_3); OnNativeEvent_Invoke_m3080421028(L_3, _stringLiteral3508327051, /*hidden argument*/NULL); } IL_002b: { return; } } // System.Void GJCNativeShare::OnOpenAppStoreFailed(System.String) extern Il2CppClass* String_t_il2cpp_TypeInfo_var; extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral740090947; extern Il2CppCodeGenString* _stringLiteral2096857181; extern const uint32_t GJCNativeShare_OnOpenAppStoreFailed_m2694175147_MetadataUsageId; extern "C" void GJCNativeShare_OnOpenAppStoreFailed_m2694175147 (GJCNativeShare_t1694253608 * __this, String_t* ___result0, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (GJCNativeShare_OnOpenAppStoreFailed_m2694175147_MetadataUsageId); s_Il2CppMethodIntialized = true; } { String_t* L_0 = ___result0; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_1 = String_Concat_m138640077(NULL /*static, unused*/, _stringLiteral740090947, L_0, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); OnNativeEvent_t3263283613 * L_2 = __this->get_onOpenAppStore_4(); if (!L_2) { goto IL_002b; } } { OnNativeEvent_t3263283613 * L_3 = __this->get_onOpenAppStore_4(); NullCheck(L_3); OnNativeEvent_Invoke_m3080421028(L_3, _stringLiteral2096857181, /*hidden argument*/NULL); } IL_002b: { return; } } // System.Void GJCNativeShare/OnNativeEvent::.ctor(System.Object,System.IntPtr) extern "C" void OnNativeEvent__ctor_m1397262276 (OnNativeEvent_t3263283613 * __this, Il2CppObject * ___object0, IntPtr_t ___method1, const MethodInfo* method) { __this->set_method_ptr_0((Il2CppMethodPointer)((MethodInfo*)___method1.get_m_value_0())->methodPointer); __this->set_method_3(___method1); __this->set_m_target_2(___object0); } // System.Void GJCNativeShare/OnNativeEvent::Invoke(System.String) extern "C" void OnNativeEvent_Invoke_m3080421028 (OnNativeEvent_t3263283613 * __this, String_t* ___msg0, const MethodInfo* method) { if(__this->get_prev_9() != NULL) { OnNativeEvent_Invoke_m3080421028((OnNativeEvent_t3263283613 *)__this->get_prev_9(),___msg0, method); } il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found((MethodInfo*)(__this->get_method_3().get_m_value_0())); bool ___methodIsStatic = MethodIsStatic((MethodInfo*)(__this->get_method_3().get_m_value_0())); if (__this->get_m_target_2() != NULL && ___methodIsStatic) { typedef void (*FunctionPointerType) (Il2CppObject *, void* __this, String_t* ___msg0, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(NULL,il2cpp_codegen_get_delegate_this(__this),___msg0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } else if (__this->get_m_target_2() != NULL || ___methodIsStatic) { typedef void (*FunctionPointerType) (void* __this, String_t* ___msg0, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(il2cpp_codegen_get_delegate_this(__this),___msg0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } else { typedef void (*FunctionPointerType) (void* __this, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(___msg0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } } extern "C" void DelegatePInvokeWrapper_OnNativeEvent_t3263283613 (OnNativeEvent_t3263283613 * __this, String_t* ___msg0, const MethodInfo* method) { typedef void (STDCALL *PInvokeFunc)(char*); PInvokeFunc il2cppPInvokeFunc = reinterpret_cast<PInvokeFunc>(((Il2CppDelegate*)__this)->method->methodPointer); // Marshaling of parameter '___msg0' to native representation char* ____msg0_marshaled = NULL; ____msg0_marshaled = il2cpp_codegen_marshal_string(___msg0); // Native function invocation il2cppPInvokeFunc(____msg0_marshaled); // Marshaling cleanup of parameter '___msg0' native representation il2cpp_codegen_marshal_free(____msg0_marshaled); ____msg0_marshaled = NULL; } // System.IAsyncResult GJCNativeShare/OnNativeEvent::BeginInvoke(System.String,System.AsyncCallback,System.Object) extern "C" Il2CppObject * OnNativeEvent_BeginInvoke_m3263194409 (OnNativeEvent_t3263283613 * __this, String_t* ___msg0, AsyncCallback_t1369114871 * ___callback1, Il2CppObject * ___object2, const MethodInfo* method) { void *__d_args[2] = {0}; __d_args[0] = ___msg0; return (Il2CppObject *)il2cpp_delegate_begin_invoke((Il2CppDelegate*)__this, __d_args, (Il2CppDelegate*)___callback1, (Il2CppObject*)___object2); } // System.Void GJCNativeShare/OnNativeEvent::EndInvoke(System.IAsyncResult) extern "C" void OnNativeEvent_EndInvoke_m1065253844 (OnNativeEvent_t3263283613 * __this, Il2CppObject * ___result0, const MethodInfo* method) { il2cpp_delegate_end_invoke((Il2CppAsyncResult*) ___result0, 0); } // System.Void GJCNativeShare/OnShareCancel::.ctor(System.Object,System.IntPtr) extern "C" void OnShareCancel__ctor_m3925156666 (OnShareCancel_t1124720659 * __this, Il2CppObject * ___object0, IntPtr_t ___method1, const MethodInfo* method) { __this->set_method_ptr_0((Il2CppMethodPointer)((MethodInfo*)___method1.get_m_value_0())->methodPointer); __this->set_method_3(___method1); __this->set_m_target_2(___object0); } // System.Void GJCNativeShare/OnShareCancel::Invoke(System.String) extern "C" void OnShareCancel_Invoke_m1971944302 (OnShareCancel_t1124720659 * __this, String_t* ___platform0, const MethodInfo* method) { if(__this->get_prev_9() != NULL) { OnShareCancel_Invoke_m1971944302((OnShareCancel_t1124720659 *)__this->get_prev_9(),___platform0, method); } il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found((MethodInfo*)(__this->get_method_3().get_m_value_0())); bool ___methodIsStatic = MethodIsStatic((MethodInfo*)(__this->get_method_3().get_m_value_0())); if (__this->get_m_target_2() != NULL && ___methodIsStatic) { typedef void (*FunctionPointerType) (Il2CppObject *, void* __this, String_t* ___platform0, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(NULL,il2cpp_codegen_get_delegate_this(__this),___platform0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } else if (__this->get_m_target_2() != NULL || ___methodIsStatic) { typedef void (*FunctionPointerType) (void* __this, String_t* ___platform0, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(il2cpp_codegen_get_delegate_this(__this),___platform0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } else { typedef void (*FunctionPointerType) (void* __this, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(___platform0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } } extern "C" void DelegatePInvokeWrapper_OnShareCancel_t1124720659 (OnShareCancel_t1124720659 * __this, String_t* ___platform0, const MethodInfo* method) { typedef void (STDCALL *PInvokeFunc)(char*); PInvokeFunc il2cppPInvokeFunc = reinterpret_cast<PInvokeFunc>(((Il2CppDelegate*)__this)->method->methodPointer); // Marshaling of parameter '___platform0' to native representation char* ____platform0_marshaled = NULL; ____platform0_marshaled = il2cpp_codegen_marshal_string(___platform0); // Native function invocation il2cppPInvokeFunc(____platform0_marshaled); // Marshaling cleanup of parameter '___platform0' native representation il2cpp_codegen_marshal_free(____platform0_marshaled); ____platform0_marshaled = NULL; } // System.IAsyncResult GJCNativeShare/OnShareCancel::BeginInvoke(System.String,System.AsyncCallback,System.Object) extern "C" Il2CppObject * OnShareCancel_BeginInvoke_m4028911603 (OnShareCancel_t1124720659 * __this, String_t* ___platform0, AsyncCallback_t1369114871 * ___callback1, Il2CppObject * ___object2, const MethodInfo* method) { void *__d_args[2] = {0}; __d_args[0] = ___platform0; return (Il2CppObject *)il2cpp_delegate_begin_invoke((Il2CppDelegate*)__this, __d_args, (Il2CppDelegate*)___callback1, (Il2CppObject*)___object2); } // System.Void GJCNativeShare/OnShareCancel::EndInvoke(System.IAsyncResult) extern "C" void OnShareCancel_EndInvoke_m3917431370 (OnShareCancel_t1124720659 * __this, Il2CppObject * ___result0, const MethodInfo* method) { il2cpp_delegate_end_invoke((Il2CppAsyncResult*) ___result0, 0); } // System.Void GJCNativeShare/OnShareSuccess::.ctor(System.Object,System.IntPtr) extern "C" void OnShareSuccess__ctor_m3617080417 (OnShareSuccess_t2384183690 * __this, Il2CppObject * ___object0, IntPtr_t ___method1, const MethodInfo* method) { __this->set_method_ptr_0((Il2CppMethodPointer)((MethodInfo*)___method1.get_m_value_0())->methodPointer); __this->set_method_3(___method1); __this->set_m_target_2(___object0); } // System.Void GJCNativeShare/OnShareSuccess::Invoke(System.String) extern "C" void OnShareSuccess_Invoke_m4182017767 (OnShareSuccess_t2384183690 * __this, String_t* ___platform0, const MethodInfo* method) { if(__this->get_prev_9() != NULL) { OnShareSuccess_Invoke_m4182017767((OnShareSuccess_t2384183690 *)__this->get_prev_9(),___platform0, method); } il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found((MethodInfo*)(__this->get_method_3().get_m_value_0())); bool ___methodIsStatic = MethodIsStatic((MethodInfo*)(__this->get_method_3().get_m_value_0())); if (__this->get_m_target_2() != NULL && ___methodIsStatic) { typedef void (*FunctionPointerType) (Il2CppObject *, void* __this, String_t* ___platform0, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(NULL,il2cpp_codegen_get_delegate_this(__this),___platform0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } else if (__this->get_m_target_2() != NULL || ___methodIsStatic) { typedef void (*FunctionPointerType) (void* __this, String_t* ___platform0, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(il2cpp_codegen_get_delegate_this(__this),___platform0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } else { typedef void (*FunctionPointerType) (void* __this, const MethodInfo* method); ((FunctionPointerType)__this->get_method_ptr_0())(___platform0,(MethodInfo*)(__this->get_method_3().get_m_value_0())); } } extern "C" void DelegatePInvokeWrapper_OnShareSuccess_t2384183690 (OnShareSuccess_t2384183690 * __this, String_t* ___platform0, const MethodInfo* method) { typedef void (STDCALL *PInvokeFunc)(char*); PInvokeFunc il2cppPInvokeFunc = reinterpret_cast<PInvokeFunc>(((Il2CppDelegate*)__this)->method->methodPointer); // Marshaling of parameter '___platform0' to native representation char* ____platform0_marshaled = NULL; ____platform0_marshaled = il2cpp_codegen_marshal_string(___platform0); // Native function invocation il2cppPInvokeFunc(____platform0_marshaled); // Marshaling cleanup of parameter '___platform0' native representation il2cpp_codegen_marshal_free(____platform0_marshaled); ____platform0_marshaled = NULL; } // System.IAsyncResult GJCNativeShare/OnShareSuccess::BeginInvoke(System.String,System.AsyncCallback,System.Object) extern "C" Il2CppObject * OnShareSuccess_BeginInvoke_m1732833780 (OnShareSuccess_t2384183690 * __this, String_t* ___platform0, AsyncCallback_t1369114871 * ___callback1, Il2CppObject * ___object2, const MethodInfo* method) { void *__d_args[2] = {0}; __d_args[0] = ___platform0; return (Il2CppObject *)il2cpp_delegate_begin_invoke((Il2CppDelegate*)__this, __d_args, (Il2CppDelegate*)___callback1, (Il2CppObject*)___object2); } // System.Void GJCNativeShare/OnShareSuccess::EndInvoke(System.IAsyncResult) extern "C" void OnShareSuccess_EndInvoke_m112660209 (OnShareSuccess_t2384183690 * __this, Il2CppObject * ___result0, const MethodInfo* method) { il2cpp_delegate_end_invoke((Il2CppAsyncResult*) ___result0, 0); } // System.Void InitShare::.ctor() extern "C" void InitShare__ctor_m691405244 (InitShare_t1734853775 * __this, const MethodInfo* method) { { MonoBehaviour__ctor_m2022291967(__this, /*hidden argument*/NULL); return; } } // System.Void InitShare::Start() extern "C" void InitShare_Start_m3933510332 (InitShare_t1734853775 * __this, const MethodInfo* method) { { InitShare_Init_m112387352(__this, /*hidden argument*/NULL); return; } } // System.Void InitShare::Init() extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppClass* GJCNativeShare_t1694253608_il2cpp_TypeInfo_var; extern Il2CppClass* OnShareSuccess_t2384183690_il2cpp_TypeInfo_var; extern Il2CppClass* OnShareCancel_t1124720659_il2cpp_TypeInfo_var; extern const MethodInfo* InitShare_OnShareSuccess_m3268265911_MethodInfo_var; extern const MethodInfo* InitShare_OnShareCancel_m2262676558_MethodInfo_var; extern Il2CppCodeGenString* _stringLiteral3558329388; extern const uint32_t InitShare_Init_m112387352_MetadataUsageId; extern "C" void InitShare_Init_m112387352 (InitShare_t1734853775 * __this, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (InitShare_Init_m112387352_MetadataUsageId); s_Il2CppMethodIntialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, _stringLiteral3558329388, /*hidden argument*/NULL); __this->set_blnInitNativeShare_2((bool)1); IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare_t1694253608 * L_0 = GJCNativeShare_get_Instance_m2894719076(NULL /*static, unused*/, /*hidden argument*/NULL); IntPtr_t L_1; L_1.set_m_value_0((void*)(void*)InitShare_OnShareSuccess_m3268265911_MethodInfo_var); OnShareSuccess_t2384183690 * L_2 = (OnShareSuccess_t2384183690 *)il2cpp_codegen_object_new(OnShareSuccess_t2384183690_il2cpp_TypeInfo_var); OnShareSuccess__ctor_m3617080417(L_2, __this, L_1, /*hidden argument*/NULL); NullCheck(L_0); L_0->set_onShareSuccess_2(L_2); GJCNativeShare_t1694253608 * L_3 = GJCNativeShare_get_Instance_m2894719076(NULL /*static, unused*/, /*hidden argument*/NULL); IntPtr_t L_4; L_4.set_m_value_0((void*)(void*)InitShare_OnShareCancel_m2262676558_MethodInfo_var); OnShareCancel_t1124720659 * L_5 = (OnShareCancel_t1124720659 *)il2cpp_codegen_object_new(OnShareCancel_t1124720659_il2cpp_TypeInfo_var); OnShareCancel__ctor_m3925156666(L_5, __this, L_4, /*hidden argument*/NULL); NullCheck(L_3); L_3->set_onShareCancel_3(L_5); return; } } // System.Void InitShare::OnShareSuccess(System.String) extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral645704372; extern const uint32_t InitShare_OnShareSuccess_m3268265911_MetadataUsageId; extern "C" void InitShare_OnShareSuccess_m3268265911 (InitShare_t1734853775 * __this, String_t* ___platform0, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (InitShare_OnShareSuccess_m3268265911_MetadataUsageId); s_Il2CppMethodIntialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, _stringLiteral645704372, /*hidden argument*/NULL); return; } } // System.Void InitShare::OnShareCancel(System.String) extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral645598359; extern const uint32_t InitShare_OnShareCancel_m2262676558_MetadataUsageId; extern "C" void InitShare_OnShareCancel_m2262676558 (InitShare_t1734853775 * __this, String_t* ___platform0, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (InitShare_OnShareCancel_m2262676558_MetadataUsageId); s_Il2CppMethodIntialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, _stringLiteral645598359, /*hidden argument*/NULL); return; } } // System.Void InitShare::ShareWithNative() extern "C" void InitShare_ShareWithNative_m3591573078 (InitShare_t1734853775 * __this, const MethodInfo* method) { { Il2CppObject * L_0 = InitShare_TakeScreenshot_m4209063437(__this, /*hidden argument*/NULL); MonoBehaviour_StartCoroutine_m2135303124(__this, L_0, /*hidden argument*/NULL); return; } } // System.Collections.IEnumerator InitShare::TakeScreenshot() extern Il2CppClass* U3CTakeScreenshotU3Ec__Iterator0_t1360893940_il2cpp_TypeInfo_var; extern const uint32_t InitShare_TakeScreenshot_m4209063437_MetadataUsageId; extern "C" Il2CppObject * InitShare_TakeScreenshot_m4209063437 (InitShare_t1734853775 * __this, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (InitShare_TakeScreenshot_m4209063437_MetadataUsageId); s_Il2CppMethodIntialized = true; } U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * V_0 = NULL; { U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * L_0 = (U3CTakeScreenshotU3Ec__Iterator0_t1360893940 *)il2cpp_codegen_object_new(U3CTakeScreenshotU3Ec__Iterator0_t1360893940_il2cpp_TypeInfo_var); U3CTakeScreenshotU3Ec__Iterator0__ctor_m3578601255(L_0, /*hidden argument*/NULL); V_0 = L_0; U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * L_1 = V_0; return L_1; } } // System.Void InitShare/<TakeScreenshot>c__Iterator0::.ctor() extern "C" void U3CTakeScreenshotU3Ec__Iterator0__ctor_m3578601255 (U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * __this, const MethodInfo* method) { { Object__ctor_m1772956182(__this, /*hidden argument*/NULL); return; } } // System.Object InitShare/<TakeScreenshot>c__Iterator0::System.Collections.Generic.IEnumerator<object>.get_Current() extern "C" Il2CppObject * U3CTakeScreenshotU3Ec__Iterator0_System_Collections_Generic_IEnumeratorU3CobjectU3E_get_Current_m1974376789 (U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * __this, const MethodInfo* method) { { Il2CppObject * L_0 = __this->get_U24current_5(); return L_0; } } // System.Object InitShare/<TakeScreenshot>c__Iterator0::System.Collections.IEnumerator.get_Current() extern "C" Il2CppObject * U3CTakeScreenshotU3Ec__Iterator0_System_Collections_IEnumerator_get_Current_m3835684585 (U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * __this, const MethodInfo* method) { { Il2CppObject * L_0 = __this->get_U24current_5(); return L_0; } } // System.Boolean InitShare/<TakeScreenshot>c__Iterator0::MoveNext() extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppClass* WaitForEndOfFrame_t2372756133_il2cpp_TypeInfo_var; extern Il2CppClass* Texture2D_t3884108195_il2cpp_TypeInfo_var; extern Il2CppClass* GJCNativeShare_t1694253608_il2cpp_TypeInfo_var; extern Il2CppClass* Object_t3071478659_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral2086612646; extern Il2CppCodeGenString* _stringLiteral2516024720; extern const uint32_t U3CTakeScreenshotU3Ec__Iterator0_MoveNext_m1469598293_MetadataUsageId; extern "C" bool U3CTakeScreenshotU3Ec__Iterator0_MoveNext_m1469598293 (U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * __this, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (U3CTakeScreenshotU3Ec__Iterator0_MoveNext_m1469598293_MetadataUsageId); s_Il2CppMethodIntialized = true; } uint32_t V_0 = 0; bool V_1 = false; { int32_t L_0 = __this->get_U24PC_4(); V_0 = L_0; __this->set_U24PC_4((-1)); uint32_t L_1 = V_0; if (L_1 == 0) { goto IL_0021; } if (L_1 == 1) { goto IL_0042; } } { goto IL_00d9; } IL_0021: { IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, _stringLiteral2086612646, /*hidden argument*/NULL); WaitForEndOfFrame_t2372756133 * L_2 = (WaitForEndOfFrame_t2372756133 *)il2cpp_codegen_object_new(WaitForEndOfFrame_t2372756133_il2cpp_TypeInfo_var); WaitForEndOfFrame__ctor_m4124201226(L_2, /*hidden argument*/NULL); __this->set_U24current_5(L_2); __this->set_U24PC_4(1); goto IL_00db; } IL_0042: { int32_t L_3 = Screen_get_width_m3080333084(NULL /*static, unused*/, /*hidden argument*/NULL); __this->set_U3CwidthU3E__0_0(L_3); int32_t L_4 = Screen_get_height_m1504859443(NULL /*static, unused*/, /*hidden argument*/NULL); __this->set_U3CheightU3E__1_1(L_4); int32_t L_5 = __this->get_U3CwidthU3E__0_0(); int32_t L_6 = __this->get_U3CheightU3E__1_1(); Texture2D_t3884108195 * L_7 = (Texture2D_t3884108195 *)il2cpp_codegen_object_new(Texture2D_t3884108195_il2cpp_TypeInfo_var); Texture2D__ctor_m3705883154(L_7, L_5, L_6, 3, (bool)0, /*hidden argument*/NULL); __this->set_U3CtexU3E__2_2(L_7); __this->set_U3CshareDefaultTextU3E__3_3(_stringLiteral2516024720); Texture2D_t3884108195 * L_8 = __this->get_U3CtexU3E__2_2(); int32_t L_9 = __this->get_U3CwidthU3E__0_0(); int32_t L_10 = __this->get_U3CheightU3E__1_1(); Rect_t4241904616 L_11; memset(&L_11, 0, sizeof(L_11)); Rect__ctor_m3291325233(&L_11, (0.0f), (0.0f), (((float)((float)L_9))), (((float)((float)L_10))), /*hidden argument*/NULL); NullCheck(L_8); Texture2D_ReadPixels_m1334301696(L_8, L_11, 0, 0, /*hidden argument*/NULL); Texture2D_t3884108195 * L_12 = __this->get_U3CtexU3E__2_2(); NullCheck(L_12); Texture2D_Apply_m1364130776(L_12, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare_t1694253608 * L_13 = GJCNativeShare_get_Instance_m2894719076(NULL /*static, unused*/, /*hidden argument*/NULL); String_t* L_14 = __this->get_U3CshareDefaultTextU3E__3_3(); Texture2D_t3884108195 * L_15 = __this->get_U3CtexU3E__2_2(); NullCheck(L_13); GJCNativeShare_NativeShare_m4035624863(L_13, L_14, L_15, /*hidden argument*/NULL); Texture2D_t3884108195 * L_16 = __this->get_U3CtexU3E__2_2(); IL2CPP_RUNTIME_CLASS_INIT(Object_t3071478659_il2cpp_TypeInfo_var); Object_Destroy_m176400816(NULL /*static, unused*/, L_16, /*hidden argument*/NULL); __this->set_U24PC_4((-1)); } IL_00d9: { return (bool)0; } IL_00db: { return (bool)1; } // Dead block : IL_00dd: ldloc.1 } // System.Void InitShare/<TakeScreenshot>c__Iterator0::Dispose() extern "C" void U3CTakeScreenshotU3Ec__Iterator0_Dispose_m2960252324 (U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * __this, const MethodInfo* method) { { __this->set_U24PC_4((-1)); return; } } // System.Void InitShare/<TakeScreenshot>c__Iterator0::Reset() extern Il2CppClass* NotSupportedException_t1732551818_il2cpp_TypeInfo_var; extern const uint32_t U3CTakeScreenshotU3Ec__Iterator0_Reset_m1225034196_MetadataUsageId; extern "C" void U3CTakeScreenshotU3Ec__Iterator0_Reset_m1225034196 (U3CTakeScreenshotU3Ec__Iterator0_t1360893940 * __this, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (U3CTakeScreenshotU3Ec__Iterator0_Reset_m1225034196_MetadataUsageId); s_Il2CppMethodIntialized = true; } { NotSupportedException_t1732551818 * L_0 = (NotSupportedException_t1732551818 *)il2cpp_codegen_object_new(NotSupportedException_t1732551818_il2cpp_TypeInfo_var); NotSupportedException__ctor_m149930845(L_0, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_0); } } // System.Void Main::.ctor() extern "C" void Main__ctor_m2928940258 (Main_t2390489 * __this, const MethodInfo* method) { { MonoBehaviour__ctor_m2022291967(__this, /*hidden argument*/NULL); return; } } // System.Void Main::Start() extern Il2CppClass* GJCNativeShare_t1694253608_il2cpp_TypeInfo_var; extern Il2CppClass* OnNativeEvent_t3263283613_il2cpp_TypeInfo_var; extern const MethodInfo* Main_OnNativeEvent_m490655262_MethodInfo_var; extern const uint32_t Main_Start_m1876078050_MetadataUsageId; extern "C" void Main_Start_m1876078050 (Main_t2390489 * __this, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (Main_Start_m1876078050_MetadataUsageId); s_Il2CppMethodIntialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare_t1694253608 * L_0 = GJCNativeShare_get_Instance_m2894719076(NULL /*static, unused*/, /*hidden argument*/NULL); IntPtr_t L_1; L_1.set_m_value_0((void*)(void*)Main_OnNativeEvent_m490655262_MethodInfo_var); OnNativeEvent_t3263283613 * L_2 = (OnNativeEvent_t3263283613 *)il2cpp_codegen_object_new(OnNativeEvent_t3263283613_il2cpp_TypeInfo_var); OnNativeEvent__ctor_m1397262276(L_2, __this, L_1, /*hidden argument*/NULL); NullCheck(L_0); L_0->set_onOpenAppStore_4(L_2); return; } } // System.Void Main::OnOpenAppStore() extern Il2CppClass* GJCNativeShare_t1694253608_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral414627154; extern const uint32_t Main_OnOpenAppStore_m2483781579_MetadataUsageId; extern "C" void Main_OnOpenAppStore_m2483781579 (Main_t2390489 * __this, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (Main_OnOpenAppStore_m2483781579_MetadataUsageId); s_Il2CppMethodIntialized = true; } { IL2CPP_RUNTIME_CLASS_INIT(GJCNativeShare_t1694253608_il2cpp_TypeInfo_var); GJCNativeShare_t1694253608 * L_0 = GJCNativeShare_get_Instance_m2894719076(NULL /*static, unused*/, /*hidden argument*/NULL); NullCheck(L_0); GJCNativeShare_OpenAppStore_m403803719(L_0, _stringLiteral414627154, /*hidden argument*/NULL); return; } } // System.Void Main::OnNativeEvent(System.String) extern Il2CppClass* String_t_il2cpp_TypeInfo_var; extern Il2CppClass* Debug_t4195163081_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral1821189994; extern const uint32_t Main_OnNativeEvent_m490655262_MetadataUsageId; extern "C" void Main_OnNativeEvent_m490655262 (Main_t2390489 * __this, String_t* ___msg0, const MethodInfo* method) { static bool s_Il2CppMethodIntialized; if (!s_Il2CppMethodIntialized) { il2cpp_codegen_initialize_method (Main_OnNativeEvent_m490655262_MetadataUsageId); s_Il2CppMethodIntialized = true; } { String_t* L_0 = ___msg0; IL2CPP_RUNTIME_CLASS_INIT(String_t_il2cpp_TypeInfo_var); String_t* L_1 = String_Concat_m138640077(NULL /*static, unused*/, _stringLiteral1821189994, L_0, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(Debug_t4195163081_il2cpp_TypeInfo_var); Debug_Log_m1731103628(NULL /*static, unused*/, L_1, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif
//intersection of 2 sorted arrays #include<iostream> using namespace std; void intersectionOfSorted(int a[],int b[],int n1,int n2){ int i=0,j=0; while(i<n1 && j<n2){ if(i>0 && a[i]==a[i-1]){ i++; continue; } if(a[i]<b[j]) i++; else if(a[i]>b[j]) j++; else{ std::cout << a[i] << '\n'; i++; j++; } } } int main(int argc, char const *argv[]) { //int a[]={2,5,8,13,15}; //int b[]{1,3,8,15,18,20,25}; int a[]={1,1,3,3,3}; int b[]={1,1,1,1,3,5,7}; int n1=sizeof(a)/sizeof(a[0]); int n2=sizeof(b)/sizeof(b[0]); intersectionOfSorted(a,b,n1,n2); return 0; }
// #include <iostream> #include <Windows.h> #include <ctime> #include <sstream> #include <string> #include <set> /** * Интерфейс Субъекта объявляет общие операции как для Реального Субъекта, так и * для Заместителя. Пока клиент работает с Реальным Субъектом, используя этот * интерфейс, вы сможете передать ему заместителя вместо реального субъекта. */ class Subject { public: virtual void Request() const = 0; }; /** * Реальный Субъект содержит некоторую базовую бизнес-логику. Как правило, * Реальные Субъекты способны выполнять некоторую полезную работу, которая к * тому же может быть очень медленной или точной – например, коррекция входных * данных. Заместитель может решить эти задачи без каких-либо изменений в коде * Реального Субъекта. */ class RealSubject : public Subject { public: void Request() const override { std::cout << "RealSubject: Handling request.\n"; } }; /** * Интерфейс Заместителя идентичен интерфейсу Реального Субъекта. */ class Proxy : public Subject { /** * @var RealSubject */ private: RealSubject *real_subject_; bool CheckAccess() const { // Некоторые реальные проверки должны проходить здесь. std::cout << "Proxy: Checking access prior to firing a real request.\n"; return true; } void LogAccess() const { std::cout << "Proxy: Logging the time of request.\n"; } /** * Заместитель хранит ссылку на объект класса РеальныйСубъект. Клиент может * либо лениво загрузить его, либо передать Заместителю. */ public: Proxy(RealSubject *real_subject) : real_subject_(new RealSubject(*real_subject)) { } ~Proxy() { delete real_subject_; } /** * Наиболее распространёнными областями применения паттерна Заместитель * являются ленивая загрузка, кэширование, контроль доступа, ведение журнала и * т.д. Заместитель может выполнить одну из этих задач, а затем, в зависимости * от результата, передать выполнение одноимённому методу в связанном объекте * класса Реального Субъект. */ void Request() const override { if (this->CheckAccess()) { this->real_subject_->Request(); this->LogAccess(); } } }; /** * Клиентский код должен работать со всеми объектами (как с реальными, так и * заместителями) через интерфейс Субъекта, чтобы поддерживать как реальные * субъекты, так и заместителей. В реальной жизни, однако, клиенты в основном * работают с реальными субъектами напрямую. В этом случае, для более простой * реализации паттерна, можно расширить заместителя из класса реального * субъекта. */ void ClientCode(const Subject &subject) { // ... subject.Request(); // ... } template <typename T> inline std::string ToString(T tX) { std::ostringstream oStream; oStream << tX; return oStream.str(); } // Генерируем рандомное число между значениями min и max. // Предполагается, что функцию srand() уже вызывали int getRandomNumber(int min, int max) { static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0); // Равномерно распределяем рандомное число в нашем диапазоне return static_cast<int>(rand() * fraction * (max - min + 1) + min); } int main() { std::cout << "Client: Executing the client code with a real subject:\n"; RealSubject *real_subject = new RealSubject; ClientCode(*real_subject); std::cout << "\n"; std::cout << "Client: Executing the same client code with a proxy:\n"; Proxy *proxy = new Proxy(real_subject); ClientCode(*proxy); delete real_subject; delete proxy; // https://ravesli.com/praktika-chast-22/ // http://www.papg.com/number-bullcow.html SetConsoleCP(1251);// установка кодовой страницы win-cp 1251 в поток ввода SetConsoleOutputCP(1251); // установка кодовой страницы win-cp 1251 в поток вывода srand(static_cast<unsigned int>(time(0))); // устанавливаем значение системных часов в качестве стартового числа int tryg; std::string try_guess; tryg = getRandomNumber(1000, 9999); // std::cout << " rand " << tryg << "\n"; // try_guess = ToString(tryg); try_guess = std::to_string(tryg); std::string from_user; int cow = 0; int bull = 0; //std::set<char> set_tryg; while (cow != 4) { cow = 0; bull = 0; std::cout << "Введите число "; std::cin >> from_user; //std::cout << "Вы ввели " << from_user << "\n"; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { if (try_guess[i] == from_user[j]) { if (i == j) cow++; else { bull++; } } } } //std::cout << " set is done." << std::endl; //char ch; //for (int i = 0; i < 4; ++i) //{ // ch = from_user[i]; // if (try_guess[i] == ch) // { // cow++; // continue; // } // // //std::cout << *set_tryg.find(ch) << std::endl; // std::cout << " current ch " << std::endl; // std::cout << ch << std::endl; // if (set_tryg.find(ch) == set_tryg.end()) // { // std::cout << " not found " << std::endl; // } // else // { // bull++; // } //if (try_guess.find(ch)) //bull++; //std::cout << std::count(try_guess.begin(), try_guess.end(), ch) << std::endl; //} /*std::cout << " Begin unique set " << std::endl; for (auto item : set_tryg) { std::cout << item << std::endl; } std::cout << " .. end. " << std::endl;*/ if (cow == 1) { std::cout << cow << " корова "; } else if (cow == 0) std::cout << cow << " коров "; else { std::cout << cow << " коровы "; } if (bull == 1) { std::cout << bull << " бык "; } else if (bull == 0) std::cout << bull << " быков "; else if (bull > 4) std::cout << " 4 быка "; else { std::cout << bull << " быка "; } } std::cout << " Поздравляем! Вы угадали число!! " << std::endl; return 0; }
#include <iostream> #include <chrono> #include <thread> void sleep_for() { std::cout << "Hello waiter" << std::endl; std::chrono::milliseconds dura( 200 ); std::this_thread::sleep_for( dura ); std::cout << "Waited 200 ms\n"; } void sleep_until() { auto days = std::chrono::system_clock::now() + std::chrono::seconds(1); std::this_thread::sleep_until(days); } int main() { sleep_for(); sleep_until(); return 0; }
/* * Flute.h * * Created on: Jun 16, 2016 * Author: g33z */ #ifndef FLUTE_H_ #define FLUTE_H_ #include "Woodwind.h" class Flute : public Woodwind { public: Flute(string n,int adj):Woodwind(n,adj){} void play(Enote n); }; #endif /* FLUTE_H_ */
// Hello World! for the TextLCD #include "mbed.h" #include "TextLCD.h" TextLCD lcd(p15, p16, p17, p18, p19, p20); // rs, e, d4-d7 int main() { lcd.printf("Hello World!\n"); }
#include "Intersection2d.h" #include <Eigen/Core> using Eigen::Vector2d; Intersection2d::Intersection2d(double position, double rotation, Vector2d vector) { this->position = position; this->rotation = rotation; this->vector = vector; } double Intersection2d::getPosition() { return position; } double Intersection2d::getRotation() { return rotation; } Vector2d Intersection2d::getVector(){ return vector; }
#include<bits/stdc++.h> using namespace std; int sum(int n){ if (n == 0) return 0; return (n % 10 + sum(n / 10)); } int main(){ int num; cout<<"Enter the digits : "; cin>>num; int add = sum(num); cout << "Sum of digits \""<<num<<"\" is "<<add<<endl; return 0; }
//Enunt: // calculeaza perimetrul, aria si diagonala unui patrat #include <iostream> #include <windows.h> #include <cmath> class Patrat { private: int latura; public: Patrat() {} Patrat(const int &latura) { this->latura = latura; } void setLatura(const int &latura) { this->latura = latura; } void setLatura(std::istream& stream) { stream >> latura; } int perimetrul() { return latura * 4; } int aria() { return latura * latura; } double diagonala() { return latura * sqrt(2); } }; int main() { Patrat patrat; std::cout << "Specifica latura patratului" << std::endl; patrat.setLatura(std::cin); std::cout << "Perimetrul: " << patrat.perimetrul() << std::endl; std::cout << "Diagonala: " << patrat.diagonala() << std::endl; std::cout << "Aria: " << patrat.aria() << std::endl; std::cout << std::endl; system("pause"); //opreste programul pentru a vizualiza rezultatele | merge numai pe windows return 0; }
#include<bits/stdc++.h> using namespace std; int toInt(string s){ stringstream convert(s); int n; convert >> n; return n; } int main(){ freopen("TINHTONG.inp", "r", stdin); freopen("TINHTONG.out", "w", stdout); int acc = 0; int i = 0; string s; getline(cin, s); while(i < s.length()){ if(s[i] >= '0' && s[i] <= '9'){ string n = ""; n.push_back(s[i]); int j = i+1; while(s[j] >= '0' && s[j] <= '9'){ n.push_back(s[j]); j++; } i = j; acc += toInt(n); } i++; } cout << acc; return 0; }
#include <iostream> #include <vector> #include <algorithm> #include <string> void Swap(int &a, int &b, std::vector<int> &elements) { int temp = 0; temp = a; a = b; b = temp; } std::vector<int> Sort(std::vector<int> elements) { // Sorting algorithm. for(int i = 0; i < elements.size(); i++){ for (int j = i; j< elements.size(); j++){ if (elements[i] > elements[j]){ //Swap swap elements Swap(elements[i], elements[j], elements); } } } return elements; } int main() { try { int input = 0, n = 0; std::vector<int> elements; std::cout << "Enter the number of elements: "; std::cin >> n; if (!std::cin){ throw std::runtime_error("Invalid input"); } std::cout << "Enter your numbers to be sorted: "; for(int i = 0; i < n; i++) { std::cin >> input; if (!std::cin) { throw std::runtime_error("invalid input"); } elements.push_back(input); } //Bubble sort algorithm elements = Sort(elements); std::cout<<"The sorted input is: "; for (int i = 0; i < n; i++) { std::cout << elements[i] << " "; } std::cout<<std::endl; } catch(std::runtime_error & e){ std::cout << e.what() << std::endl; } return 0; }
#include <stdio.h> #include <omp.h> #include <iostream> #include <climits> #include <vector> #include <string> #include <sstream> void client(omp_lock_t& read_lock, omp_lock_t& write_lock, std::string& input, const std::vector<std::string>& task); void server(omp_lock_t& read_lock, omp_lock_t& write_lock, std::string& input); int main(int argc, char* argv[]) { std::string input; std::vector<std::string> task = { "5+3", "res/2", "24/res", "res*res", "res-6", "res-2", "res-2", "" }; omp_lock_t read_lock, write_lock; omp_init_lock(&read_lock); omp_set_lock(&read_lock); omp_init_lock(&write_lock); #pragma omp parallel { #pragma omp sections { #pragma omp section { server(read_lock, write_lock, input); } #pragma omp section { client(read_lock, write_lock, input, task); } } } return 0; } void client(omp_lock_t& read_lock, omp_lock_t& write_lock, std::string& input, const std::vector<std::string>& task) { for (const auto& command : task) { omp_set_lock(&write_lock); input = command; omp_unset_lock(&read_lock); } } void server(omp_lock_t& read_lock, omp_lock_t& write_lock, std::string& input) { int res = 0; int term1, term2; char op; while (true) { omp_set_lock(&read_lock); std::stringstream ss; ss << input; if (input.length() == 0) { std::cout << res << std::endl; return; } if (ss.peek() == 'r') { term1 = res; ss.get(); ss.get(); ss.get(); ss >> op; if (input[4] == 'r') { term2 = res; } else { ss >> term2; } } else { ss >> term1; ss >> op; if (ss.peek() == 'r') { term2 = res; } else { ss >> term2; } } if (op == '+') res = term1 + term2; else if (op == '-') res = term1 - term2; else if (op == '/') res = term1 / term2; else if (op == '*') res = term1 * term2; omp_unset_lock(&write_lock); } }
#pragma once class DropEgg; class MonsterDrop : public GameObject { public: MonsterDrop(); ~MonsterDrop(); bool Start() override; void Update() override; void OnDestroy() override; void setDungeonNum(int n) { m_stage = n; } private: void InitUI(); void InitCamera(); void Notifications(); void InitModels(); void SceneTransition(); void ToDungeonSelect(); int m_stage = 0; DropEgg* m_egg = nullptr; SkinModelRender* m_back = nullptr; CVector3 m_backPosition = { 0.f,0.f,-300.f }; //UI //next FontRender* m_nextfont = nullptr; //notify SpriteRender* m_notifySp = nullptr; CVector3 m_notifyLinePos = { 0.f,300.f,0.f }; FontRender* m_notifyFont = nullptr; bool m_isInited = false; //name SpriteRender* m_monsterNameSp = nullptr; //Fade Fade* m_fade = nullptr; bool m_fadeFlag = false; float m_fontFix = 0.f; //other Sound* m_BGM = nullptr; };
/* * LSST Data Management System * Copyright 2014-2015 AURA/LSST. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <https://www.lsstcorp.org/LegalNotices/>. */ /// \file /// \brief This file contains the Vector3d class implementation. #include "UnitVector3d.h" #include <cstdio> #include <ostream> namespace lsst { namespace sg { UnitVector3d UnitVector3d::orthogonalTo(Vector3d const & v) { Vector3d n; // Pick a vector not equal to v that isn't nearly parallel to it. if (std::fabs(v.x()) > std::fabs(v.y())) { n.y() = 1.0; } else { n.x() = 1.0; } return UnitVector3d(v.cross(n)); } UnitVector3d UnitVector3d::orthogonalTo(Vector3d const & v1, Vector3d const & v2) { Vector3d n = (v2 + v1).cross(v2 - v1); if (n.isZero()) { return orthogonalTo(v1); } return UnitVector3d(n); } UnitVector3d UnitVector3d::northFrom(Vector3d const & v) { Vector3d n(-v.x() * v.z(), -v.y() * v.z(), v.x() * v.x() + v.y() * v.y()); if (n.isZero()) { UnitVector3d u; u._v.x() = -::copysign(1.0, v.z()); return u; } return UnitVector3d(n); } UnitVector3d::UnitVector3d(Angle lon, Angle lat) { double sinLon = sin(lon); double cosLon = cos(lon); double sinLat = sin(lat); double cosLat = cos(lat); _v.x() = cosLon * cosLat; _v.y() = sinLon * cosLat; _v.z() = sinLat; } std::ostream & operator<<(std::ostream & os, UnitVector3d const & v) { char buf[128]; std::snprintf(buf, sizeof(buf), "UnitVector3d(%.17g, %.17g, %.17g)", v.x(), v.y(), v.z()); return os << buf; } }} // namespace lsst::sg
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Arjan van Leeuwen (arjanl) */ #include "core/pch.h" #ifdef M2_SUPPORT #include "adjunct/m2/src/backend/imap/imap-uid-manager.h" #include "adjunct/m2/src/include/mailfiles.h" #include "adjunct/m2/src/MessageDatabase/MessageDatabase.h" /*********************************************************************************** ** Constructor ** ** ImapUidManager::ImapUidManager ** ***********************************************************************************/ ImapUidManager::ImapUidManager(MessageDatabase& message_database) : m_message_database(message_database) { // Ideally we want to group this file, but we can't because of backend initialization timing // m_message_database.GroupSearchEngineFile(m_tree.GetGroupMember()); } /*********************************************************************************** ** Destructor ** ** ImapUidManager::~ImapUidManager ** ***********************************************************************************/ ImapUidManager::~ImapUidManager() { OpStatus::Ignore(m_tree.Close()); m_message_database.RemoveCommitListener(this); } /*********************************************************************************** ** Initialization function, run before using any other function ** ** ImapUidManager::Init ** @param account_id Account ID of the account this UID manager will manage ** ***********************************************************************************/ OP_STATUS ImapUidManager::Init(int account_id) { OpString filename; // Construct path of btree file RETURN_IF_ERROR(MailFiles::GetIMAPUIDFilename(account_id,filename)); // Open btree file RETURN_IF_ERROR(m_tree.Open(filename.CStr(), BlockStorage::OpenReadWrite, M2_BS_BLOCKSIZE)); // Add this as a commit listener so that commits are in sync with store return m_message_database.AddCommitListener(this); } /*********************************************************************************** ** Get a message by its UID ** ** ImapUidManager::GetByUID ** @param folder_index_id Index number of the folder this message resides in ** @param server_uid UID of this message on the server ** @return M2 message ID of the message, or 0 if not found ** ***********************************************************************************/ message_gid_t ImapUidManager::GetByUID(index_gid_t folder_index_id, unsigned uid) { OP_ASSERT(folder_index_id != 0); ImapUidKey key(folder_index_id, uid, 0); if (m_tree.Search(key) == OpBoolean::IS_TRUE) return key.GetMessageId(); else return 0; } /*********************************************************************************** ** Add a server UID or replace information ** ** ImapUidManager::AddUID ** @param folder_index_id Index number of the folder this message resides in ** @param uid UID of message to add ** @param m2_message_id M2 message ID of the message ** ***********************************************************************************/ OP_STATUS ImapUidManager::AddUID(index_gid_t folder_index_id, unsigned uid, message_gid_t m2_message_id) { OP_ASSERT(folder_index_id != 0); ImapUidKey key(folder_index_id, uid, m2_message_id); RETURN_IF_ERROR(m_tree.Insert(key, TRUE)); return m_message_database.RequestCommit(); } /*********************************************************************************** ** Remove a server UID ** ** ImapUidManager::RemoveUID ** @param folder_index_id Index number of the folder this message resides in ** @param uid UID of message to remove ** ***********************************************************************************/ OP_STATUS ImapUidManager::RemoveUID(index_gid_t folder_index_id, unsigned uid) { OP_ASSERT(folder_index_id != 0); ImapUidKey key(folder_index_id, uid, 0); RETURN_IF_ERROR(m_tree.Delete(key)); return m_message_database.RequestCommit(); } /*********************************************************************************** ** Remove messages with UID [from .. to) from M2s message store and the UID manager ** ** ImapUidManager::RemoveMessagesByUID ** @param folder_index_id Index number of the folder this message resides in ** @param from Remove messages with a UID at least this value ** @param to Remove messages with a UID less than this value, or 0 for no limit ** ***********************************************************************************/ OP_STATUS ImapUidManager::RemoveMessagesByUID(index_gid_t folder_index_id, unsigned from, unsigned to) { OP_ASSERT(folder_index_id != 0); if (to > 0 && from >= to) return OpStatus::OK; // Empty set // Prepare search ImapUidKey from_key(folder_index_id, from, 0); ImapUidKey to_key (folder_index_id + (to == 0 ? 1 : 0), to, 0); SearchIterator<ImapUidKey> *iterator = m_tree.Search(from_key, operatorGE); if (!iterator) return OpStatus::ERR_NO_MEMORY; // Check if there were any results if (!iterator->Empty() && iterator->Get() < to_key) { // Remove results from store do { OpStatus::Ignore(m_message_database.RemoveMessage(iterator->Get().GetMessageId())); } while (iterator->Next() && iterator->Get() < to_key); // Always close iterator before doing changes OP_DELETE(iterator); // Remove results from UID index RETURN_IF_ERROR(m_tree.Delete(from_key, operatorGE, to_key, operatorLT)); RETURN_IF_ERROR(m_message_database.RequestCommit()); } else OP_DELETE(iterator); return OpStatus::OK; } /*********************************************************************************** ** Gets the highest UID in the database for a certain folder ** ** ImapUidManager::GetHighestUID ** @param folder_index_id Index number of the folder to check ** @return Highest UID in this folder ** ***********************************************************************************/ unsigned ImapUidManager::GetHighestUID(index_gid_t folder_index_id) { OP_ASSERT(folder_index_id != 0); // Prepare search ImapUidKey from_key(folder_index_id, 0, 0); ImapUidKey to_key (folder_index_id + 1, 0, 0); OpAutoPtr< SearchIterator<ImapUidKey> > iterator (m_tree.Search(from_key, operatorGT)); if (!iterator.get()) return 0; // Check if there were any results if (!iterator->Empty() && iterator->Get() < to_key) { // iterate until highest one while (iterator->Next() && iterator->Get() < to_key) {} // Go back one if (iterator->Prev()) return iterator->Get().GetUID(); } // No UIDs for this folder return 0; } void ImapUidManager::OnCommitted() { if (OpStatus::IsError(m_tree.Commit())) m_message_database.RequestCommit(); } #endif //M2_SUPPORT
#include "data.h" void loadZ(double *z){ } double *loadZ(){ double *ret = (double *)malloc(sizeof(double)*N*N); for (int i=0; i<N*N; ++i) ret[i] = rand()%256; return ret; } double *loadX(double **X, int idx){ return X[idx]; } void strToDouble(char *buf, double *x){ int len = strlen(buf); int num = 0; int idx = 0; bool first = true; while (len>0 && buf[len]<20) --len; for (int i=0; i<=len; ++i) if (i == len || buf[i] == ','){ if (first){ first = false; num = 0; continue; } x[idx++] = num; num = 0; } else if (isdigit(buf[i])) num = num * 10 + buf[i] - '0'; } bool readTrain(double ** &X){ const char *fileName = "train.csv"; FILE *fTrain = fopen(fileName, "r"); if (fTrain == NULL){ fprintf(stderr, "open file<%s> failed\n", fileName); return false; } char *buf = (char *) malloc(sizeof(char) * BUF_SIZE); X = (double **) malloc(sizeof(double*) * M); fgets(buf, BUF_SIZE, fTrain); for (int i=0; i<M; ++i){ fgets(buf, BUF_SIZE, fTrain); X[i] = (double *) malloc(sizeof(double) * N * N); strToDouble(buf, X[i]); } return true; } void release(double **X){ for (int i=0; i<M; ++i) if (X[i] != NULL) free(X[i]); if (X!=NULL) free(X); }