text
stringlengths
8
6.88M
#ifndef _TNA_TASKING_BARRIER_H #define _TNA_TASKING_BARRIER_H value #include "atomic_counter.h" #include <furious/furious.h> namespace tna { struct barrier_t : public furious::barrier_t { void wait(int32_t value); void reset(); atomic_counter_t m_counter; }; void barrier_init(barrier_t* barrier); void barrier_release(barrier_t* barrier); void barrier_reset(barrier_t* barrier); } /* tna */ #endif /* ifndef _TNA_TASKING_BARRIER_H */
/* The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), for N > 1. Given N, calculate F(N). Example 1: Input: 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. Note: 0 ≤ N ≤ 30. */ int fib(int N) { if (N == 0) return 0; if (N == 1) return 1; if (N == 2) return 1; int num1 = 1; int num2 = 1; int temp = 0; for (int i = 3; i <= N; ++i) { temp = num2; num2 = num2 + num1; num1 = temp; } return num2; }
#include "customer.h" Customer::Customer(int id, std::string lastName, std::string firstName) { this->customerID = id; this->lastName = lastName; this->firstName = firstName; } int Customer::getCustomerID() const { return customerID; } void Customer::setCustomerID(int newID) { customerID = newID; } std::string Customer::getCustomerFirstName() const { return firstName; } void Customer::setCustomerFirstName(std::string newFirstName) { firstName = newFirstName; } std::string Customer::getCustomerLastName() const { return lastName; } void Customer::setCustomerLastName(std::string newLastName) { lastName = newLastName; } bool Customer::operator==(const Customer& rhs) const { return customerID== rhs.getCustomerID(); } bool Customer::operator!=(const Customer& rhs) const { return customerID != rhs.getCustomerID(); } bool Customer::borrowRentable(int borrowCount, Rentable& rentable) { std::cout << "Customer " << customerID << " borrowing "; std::cout << rentable.getTitle() << " ("; std::cout << rentable.getStockCount() << " left)" << std::endl; //RentalDetails has a reference to a rentable, so this needs to be done //all at the same time. RentalDetails transaction = {&rentable, 0, borrowCount, false, "Borrow"}; currentlyRenting.push_back(transaction); customerHistory.push_back(transaction); return true; } bool Customer::returnRentable(int returnCount, Rentable& rentable) { std::cout << "Customer " << customerID << " returning "; std::cout << rentable.getTitle() << std::endl; for (int i = 0; i < currentlyRenting.size(); i++) { if (*(currentlyRenting[i].rental) == rentable && currentlyRenting[i].count >= returnCount) { RentalDetails transaction = currentlyRenting[i]; transaction.count = returnCount; transaction.returned = true; transaction.action = "Return"; //update to reflect return currentlyRenting[i].count -= returnCount; //need to check if count is reduced to zero //if so, need to remove transaction from currentlyRenting if (currentlyRenting[i].count == 0) { // no more on hand, so remove from vector currentlyRenting.erase(currentlyRenting.begin() + i); } customerHistory.push_back(transaction); return true; } else { std::cerr << "ERROR: Invalid return request." << std::endl; return false; } } std::cerr << "ERROR: Customer not currently renting "; std::cerr << rentable.getTitle() << std::endl; return false; } void Customer::displayHistory() const { std::cout << "Transaction History for: " << getCustomerLastName(); std::cout << ", " << getCustomerFirstName(); std::cout << " Customer ID: "<< customerID << std::endl; if (customerHistory.size() == 0) { std::cout << "No history to display" << std::endl; } for (int i = customerHistory.size() - 1; i >= 0; i--) { RentalDetails transaction = customerHistory[i]; std::cout << transaction.action << " "; std::cout << intToDVDType(transaction.rental->getSubtype()) << " "; // optional: print out subtype here // if subtype printed, need to differentiate between // classic and others. // if (transaction.rental.getType() == classic) // { // do the date thats necessary here // do the actors necessary here // else // { othere types } std::cout << transaction.rental->getTitle() << " "; std::cout << transaction.rental->getReleaseYear() << std::endl; } std::cout << std::endl; }
#include <iostream> #include <algorithm> #include <vector> #include <map> using namespace std; typedef pair<int, int> pii; bool compare(pair<string, int> A, pair<string, int> B) { return A.second > B.second; } bool compare2(pii A, pii B) { return A.first > B.first; } vector<int> solution(vector<string> genres, vector<int> plays) { vector<int> answer; map<string, int> gm; map<string, vector<pii>> pm; for(int i = 0; i < genres.size(); i++) { gm[genres[i]] += plays[i]; pm[genres[i]].push_back({plays[i],i}); } vector<pair<string, int>> v; map<string, int>::iterator it; for(it = gm.begin(); it != gm.end(); it++) { v.push_back({it->first, it->second}); } sort(v.begin(), v.end(), compare); for(int i = 0; i < v.size(); i++) { string genre = v[i].first; sort(pm[genre].begin(), pm[genre].end(), compare2); int size = (int)pm[genre].size(); answer.push_back(pm[genre][0].second); if(size >= 2) answer.push_back(pm[genre][1].second); } return answer; } int main() { ios::sync_with_stdio(0); cin.tie(0); solution({"classic", "pop", "classic", "classic", "pop"}, {500, 600, 150, 800, 2500}); return 0; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TOROIDAL2DMESH_HPP_ #define TOROIDAL2DMESH_HPP_ #include "ChasteSerialization.hpp" #include <boost/serialization/base_object.hpp> #include <cmath> #include <map> #include "MutableMesh.hpp" #include "TrianglesMeshWriter.hpp" /** * A subclass of MutableMesh<2,2> for a rectangular mesh with * periodic left and right boundaries, representing a Toroidal geometry. * * The class works by overriding calls such as ReMesh() and * GetVectorFromAtoB() so that simulation classes can treat this * class in exactly the same way as a MutableMesh<2,2>. */ class Toroidal2dMesh : public MutableMesh<2,2> { friend class TestToroidal2dMesh; private: /** The periodic width of the domina. */ double mWidth; /** The periodic height of the domain. */ double mHeight; /** The left nodes which have been mirrored during the remesh. */ std::vector<unsigned> mLeftOriginals; /** The image nodes corresponding to these left nodes (on right of mesh). */ std::vector<unsigned> mLeftImages; /** A map from image node index (on right of mesh) to original node index (on left of mesh). */ std::map<unsigned, unsigned> mImageToLeftOriginalNodeMap; /** The right nodes which have been mirrored during the remesh. */ std::vector<unsigned> mRightOriginals; /** The image nodes corresponding to these right nodes (on left of mesh). */ std::vector<unsigned> mRightImages; /** A map from image node index (on left of mesh) to original node index (on right of mesh). */ std::map<unsigned, unsigned> mImageToRightOriginalNodeMap; /** The indices of elements which straddle the left periodic boundary. */ std::set<unsigned> mLeftPeriodicBoundaryElementIndices; /** The indices of elements which straddle the right periodic boundary. */ std::set<unsigned> mRightPeriodicBoundaryElementIndices; /** The Bottom nodes which have been mirrored during the remesh. */ std::vector<unsigned> mBottomOriginals; /** The image nodes corresponding to these Bottom nodes (on Top of mesh). */ std::vector<unsigned> mBottomImages; /** A map from image node index (on Top of mesh) to original node index (on Bottom of mesh). */ std::map<unsigned, unsigned> mImageToBottomOriginalNodeMap; /** The Top nodes which have been mirrored during the remesh. */ std::vector<unsigned> mTopOriginals; /** The image nodes corresponding to these Top nodes (on Bottom of mesh). */ std::vector<unsigned> mTopImages; /** A map from image node index (on Bottom of mesh) to original node index (on Top of mesh). */ std::map<unsigned, unsigned> mImageToTopOriginalNodeMap; /** The indices of elements which straddle the Bottom periodic boundary. */ std::set<unsigned> mBottomPeriodicBoundaryElementIndices; /** The indices of elements which straddle the Top periodic boundary. */ std::set<unsigned> mTopPeriodicBoundaryElementIndices; /** Whether the number of left hand boundary nodes does not equal the number of right hand boundary nodes (and top=bottom) */ bool mMismatchedBoundaryElements; /** * Creates a set of mirrored nodes for a Toroidal re-mesh. Updates * mRightImages, mLeftImages, mTopImages and mBottomImages . * All mesh points should be 0 < x < mWidth and 0 < y < mHeight * * This method should only ever be called by the public ReMesh() method. */ void CreateMirrorNodes(); /** * * After any corrections have been made to the boundary elements (see UseTheseElementsToDecideMeshing()) * this method deletes the mirror image nodes, elements and boundary elements created * for a Toroidal remesh by cycling through the elements and changing * elements with partly real and partly imaginary elements to be real with * periodic real nodes instead of mirror image nodes. We end up with very * strangely shaped elements which cross the whole mesh but specify the correct * connections between nodes. * * This method should only ever be called by the public ReMesh() method. */ void ReconstructCylindricalMesh(); /** * * After any corrections have been made to the boundary elements (see UseTheseElementsToDecideMeshing()) * this method deletes the mirror image nodes, elements and boundary elements created * for a Toroidal remesh by cycling through the elements and changing * elements with partly real and partly imaginary elements to be real with * periodic real nodes instead of mirror image nodes. We end up with very * strangely shaped elements which cross the whole mesh but specify the correct * connections between nodes. * * This method should only ever be called by the public ReMesh() method. */ void ReconstructToroidalMesh(); /** * This method should only ever be called by the public ReMesh() method. * * Uses mLeftPeriodicBoundaryElementIndices and mRightPeriodicBoundaryElementIndices * and compares the nodes in each to ensure that both boundaries have been meshed * identically. If they have not it calls UseTheseElementsToDecideMeshing() to * sort out the troublesome elements which have been meshed differently on each * side and uses the meshing of the elements on the right hand boundary to decide * on how to mesh the left hand side. */ void CorrectCylindricalNonPeriodicMesh(); /** * This method should only ever be called by the public ReMesh() method. * * Uses mLeftPeriodicBoundaryElementIndices and mRightPeriodicBoundaryElementIndices * and compares the nodes in each to ensure that both boundaries have been meshed * identically. If they have not it calls UseTheseElementsToDecideMeshing() to * sort out the troublesome elements which have been meshed differently on each * side and uses the meshing of the elements on the right hand boundary to decide * on how to mesh the left hand side. */ void CorrectToroidalNonPeriodicMesh(); /** * This method should only ever be called by the public ReMesh method. * * The elements which straddle the periodic boundaries need to be * identified in order to compare the list on the right with * the list on the left and reconstruct a Toroidal mesh. * * Empties and repopulates the member variables * mLeftPeriodicBoundaryElementIndices and mRightPeriodicBoundaryElementIndices */ void GenerateVectorsOfElementsStraddlingCylindricalPeriodicBoundaries(); /** * This method should only ever be called by the public ReMesh method. * * The elements which straddle the periodic boundaries need to be * identified in order to compare the list on the right with * the list on the left and reconstruct a Toroidal mesh. * * Empties and repopulates the member variables * mLeftPeriodicBoundaryElementIndices and mRightPeriodicBoundaryElementIndices */ void GenerateVectorsOfElementsStraddlingToroidalPeriodicBoundaries(); /** * This method should only ever be called by the public ReMesh() method. * * @param nodeIndex The index of an original/mirrored node * @return the index of the corresponding mirror image of that node * (can be either an original or mirror node) */ unsigned GetCorrespondingCylindricalNodeIndex(unsigned nodeIndex); /** * This method should only ever be called by the public ReMesh() method. * * @param nodeIndex The index of an original/mirrored node * @return the index of the corresponding mirror image of that node * (can be either an original or mirror node) */ unsigned GetCorrespondingToroidalNodeIndex(unsigned nodeIndex); /** Needed for serialization. */ friend class boost::serialization::access; /** * Archives the member variables of the Toroidal2dMesh class which * have to be preserved during the lifetime of the mesh. * * The remaining member variables are re-initialised before being used * by each ReMesh() call so they do not need to be archived. * * @param archive the archive * @param version the current version of this class the current version * of this class */ template<class Archive> void serialize(Archive & archive, const unsigned int version) { archive & boost::serialization::base_object<MutableMesh<2,2> >(*this); archive & mWidth; archive & mHeight; } public: /** * Con+structor. * * @param width the periodic width of the mesh * @param depth the periodic depth of the mesh */ Toroidal2dMesh(double width, double depth); /** * A constructor which reads in a width and collection of nodes, then * calls a ReMesh() command to create the elements of the mesh. * * @param width the periodic width of the mesh * @param depth the periodic depth of the mesh * @param nodes a collection of nodes to construct the mesh with */ Toroidal2dMesh(double width, double depth, std::vector<Node<2>*> nodes); /** * Destructor. */ ~Toroidal2dMesh(); /** * Overridden ReMesh() method. * * Conduct a Toroidal remesh by calling CreateMirrorNodes() to create * mirror image nodes, then calling ReMesh() on the parent class, then * mapping the new node indices and calling ReconstructToroidalMesh() * to remove surplus nodes, leaving a fully periodic mesh. * * @param rMap a reference to a nodemap which should be created with the required number of nodes. */ void ReMesh(NodeMap& rMap); /** * Overridden GetVectorFromAtoB() method. * * Evaluates the (surface) distance between two points in a 2D Toroidal * geometry. * * @param rLocation1 the x and y co-ordinates of point 1 * @param rLocation2 the x and y co-ordinates of point 2 * @return the vector from location1 to location2 */ c_vector<double, 2> GetVectorFromAtoB(const c_vector<double, 2>& rLocation1, const c_vector<double, 2>& rLocation2); /** * Overridden SetNode() method. * * If the location should be set outside a Toroidal boundary, it is moved * back onto the cylinder. * * @param index is the index of the node to be moved * @param point is the new target location of the node * @param concreteMove is set to false if we want to skip the signed area tests */ void SetNode(unsigned index, ChastePoint<2> point, bool concreteMove); /** * Overridden GetWidth() method. * * Calculate the 'width' of any dimension of the mesh, taking periodicity * into account. * * @param rDimension a dimension (0 or 1) * @return The maximum distance between any nodes in this dimension. */ double GetWidth(const unsigned& rDimension) const; /** * Overridden AddNode() method. * * @param pNewNode the node to be added to the mesh * @return the global index of the new node */ unsigned AddNode(Node<2>* pNewNode); /** * @return whether you have mismatched numbers of left and right boundary nodes */ bool GetInstanceOfMismatchedBoundaryNodes(); /** * Overridden RefreshMesh method. This method moves node backinto domain and * calls RefreshJacobianCachedData. */ void RefreshMesh(); }; namespace boost { namespace serialization { /** * Serialize information required to construct a Toroidal2dMesh. */ template<class Archive> inline void save_construct_data( Archive & ar, const Toroidal2dMesh * t, const unsigned int file_version) { // Save data required to construct instance const double width = t->GetWidth(0); ar & width; const double depth = t->GetWidth(1); ar & depth; } /** * De-serialize constructor parameters and initialise a Toroidal2dMesh. */ template<class Archive> inline void load_construct_data( Archive & ar, Toroidal2dMesh * t, const unsigned int file_version) { // Retrieve data from archive required to construct new instance double width; ar & width; double depth; ar & depth; // Invoke inplace constructor to initialise instance ::new(t)Toroidal2dMesh(width,depth); } } } // namespace ... #include "SerializationExportWrapper.hpp" CHASTE_CLASS_EXPORT(Toroidal2dMesh) #endif /*TOROIDAL2DMESH_HPP_*/
#pragma once #include <cstring> #include <initializer_list> #include <tudocomp/util/conststr.hpp> namespace tdc { namespace meta { namespace ast { /// \brief Implements a predicate for accepting certain characters. /// /// This is meant to use by a parser to decide whether a read character belongs /// to a group of expected characters and can be successfully parsed. class Acceptor { private: conststr m_symbols; public: /// \brief Main constructor. /// \param symbols the string of characters to accept inline constexpr Acceptor(conststr symbols) : m_symbols(symbols) { } /// \brief Tests if the given character belongs to the group of accepted /// characters. /// \param c the character in question /// \return \c true if accepted, \c false otherwise inline constexpr bool accept(const char c) const { for(size_t i = 0; i < m_symbols.size(); i++) { if(c == m_symbols[i]) return true; } return false; } }; }}} //ns
#include <iostream> using namespace std; int main() { int a, b, c; char tmp; cin >> a >> tmp >> b >> tmp >> c; cout.fill('0'); cout.width(4); cout << a << "년 "; cout.width(2); cout << b << "월 "; cout.width(2); cout << c << "일" << endl; }
#include <iostream> using namespace std; int main (){ int score {}; cout << "Enter your score on the exam (0 - 100): "; cin >> score; char letterGrade {}; if (score >=0 && score <=100) { if (score >= 90) letterGrade = 'A'; else if (score >= 80) letterGrade = 'B'; else if (score >= 70) letterGrade = 'C'; else if (score >= 60) letterGrade = 'D'; else letterGrade = 'F'; cout << "\nYour grade is " << letterGrade<< endl; }else{ cout<< "Sorry, " << score <<" is not in range"<< endl; } cout << endl; return 0; }
class PqResultImpl; typedef PqResultImpl DbResultImpl;
#ifndef GRAPH_HPP_ #define GRAPH_HPP_ #include <vector> #include <iostream> #include <limits> #include "path.hpp" class Graph { public: void load(const std::vector<std::vector<int>> &matrix); size_t size() { return edges_.size(); } Path& path() { return path_; } int& distance(size_t x, size_t y) { return edges_[x][y]; } void print_path(); private: std::vector<std::vector<int>> edges_; Path path_; }; #endif // GRAPH_HPP_
#include <iostream> #include <string> using namespace std; int main() { string str,prestr="",maxstr; int i=1,max=0; while (cin>>str){ if(str==prestr) { i++; if (i > max) { max = i; maxstr = str; } } else{ i=1; } prestr=str; } if(max>1) cout <<"出现次数最多的是:"<<maxstr<<"次数是:"<<max<<endl; else cout<<"没有重复字符串"<<endl; return 0; }
#include <gtest/gtest.h> #include <string> #include <vector> extern bool DnsExtractAddressesFromAnswer(const std::string answer, std::vector<std::string> &dest); class DnsTest : public ::testing::Test { protected: virtual void SetUp() { } }; std::string JOIN(std::vector<std::string> &a, char delim) { std::string s; for (std::string entry : a) { if (!s.empty()) { s += delim; } s += entry; } return s; } TEST_F(DnsTest, simple) { std::vector<std::string> addrs; std::vector<std::string> answers = { "::1;::ffff:127.0.0.1;", "::ffff:107.20.240.232;::ffff:23.21.193.169;::ffff:184.72.104.138;", "type: 5 wd-prod-ss.trafficmanager.net;type: 5 wd-prod-ss-us-east-2-fe.eastus.cloudapp.azure.com;::ffff:40.117.150.237;", "type: 5 a-0001.a-afdentry.net.trafficmanager.net;type: 5 dual-a-0001.a-msedge.net;::ffff:13.107.21.200;::ffff:204.79.197.200;" }; std::vector<std::string> answer_addrs = { "::1,127.0.0.1", "107.20.240.232,23.21.193.169,184.72.104.138", "40.117.150.237", "13.107.21.200,204.79.197.200" }; for (size_t i = 0; i < answers.size(); i++) { EXPECT_FALSE(DnsExtractAddressesFromAnswer(answers[i],addrs)); EXPECT_EQ(answer_addrs[i], JOIN(addrs,',')); addrs.clear(); } } TEST_F(DnsTest, negatives) { std::vector<std::string> addrs; std::vector<std::string> answers = { "", ";;;;;;;;;;;;;;::ffff;...;", }; for (size_t i = 0; i < answers.size(); i++) { EXPECT_TRUE(DnsExtractAddressesFromAnswer(answers[i], addrs)); addrs.clear(); } }
#pragma once #ifndef TILE_WIDGET_HPP #define TILE_WIDGET_HPP #include <QWidget> class TileWindow; class TileWidget : public QWidget { public: TileWidget ( QWidget* parent ); virtual ~TileWidget(); TileWindow* getCurrentWindow(); TileWindow* setWidget ( QWidget* widget, int x, int y); TileWindow* getWindow ( QWidget* widget ); TileWindow* getWindow ( int x, int y ); void saveStates(); void restoreStates(); private: TileWindow* m_CurrentWindow; QVector<TileWindow*> m_Windows; }; #endif
#include <bits/stdc++.h> using namespace std; bool status[1000006]; int ans[1000004]; vector<int>prime; void siv(){ status[1]=1; status[0]=1; int M=1000000; for(int i=2;i<=M;i++){ if(status[i]==false){ prime.push_back(i); for(int j=2*i;j<=M;j=j+i){ status[j]=true; } } } } void go() { int N=1000000; for(int i=2;i<=N;i++) { int take=i,cnt=0; for(int j=0;prime[j]*prime[j]<=take;j++) { if(take%prime[j]==0) { while(take%prime[j]==0) { cnt++; take=take/prime[j]; } } } if(take>1)cnt++; ans[i]=ans[i-1]+cnt; } } int main() { int n; siv(); go(); while(scanf("%d",&n)!=EOF) { printf("%d\n",ans[n]); } return 0; }
/** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Diseño y Análisis de Algoritmos * * Algoritmos constructivos y búsquedas por entornos * * @author Ángel Tornero Hernández * @date 13 Abr 2021 * @file GRASP.cc * */ #include "../include/GRASP.h" #include <iostream> #include <stdlib.h> #include <time.h> #include <chrono> const int BIG_NUMBER = 999999; GRASP::GRASP() { postprocessingOption_ = 0; } std::vector<Machine*> GRASP::solve(PMSProblem& pmsp) { return generateSolution(pmsp); } std::vector<Machine*> GRASP::solveNonFixedIterations(PMSProblem& pmsp) { std::vector<Machine*> currentSolution = generateSolution(pmsp); std::vector<Machine*> bestSolution = currentSolution; int iterations = 0; int bestZ = calculateZ(bestSolution); do { currentSolution = localSearch(currentSolution, postprocessingOption_); int newZ = calculateZ(currentSolution); if (newZ < bestZ) { bestSolution = currentSolution; bestZ = newZ; iterations = 0; } else { iterations++; } currentSolution = generateSolution(pmsp); } while (iterations < 10); return bestSolution; } std::vector<Machine*> GRASP::solveFixedIterations(PMSProblem& pmsp) { std::vector<Machine*> currentSolution = generateSolution(pmsp); std::vector<Machine*> bestSolution = currentSolution; int iterations = 0; int bestZ = calculateZ(bestSolution); do { currentSolution = localSearch(currentSolution, postprocessingOption_); int newZ = calculateZ(currentSolution); if (newZ < bestZ) { bestSolution = currentSolution; bestZ = newZ; } iterations++; currentSolution = generateSolution(pmsp); } while (iterations < 10); return bestSolution; } std::vector<Machine*> GRASP::generateSolution(PMSProblem& pmsp) { std::vector<Task*> shorterTasks = selectShorterTasks(pmsp); std::vector<Machine*> solution; for (int i = 0; i < shorterTasks.size(); i++) { solution.push_back(new Machine({shorterTasks[i]})); } do { bestInsertion(pmsp, solution); } while (!allTasksAssigned(pmsp)); pmsp.setAllTasksAsUnassigned(); return solution; } std::vector<Machine*> GRASP::localSearch(std::vector<Machine*> initialSolution, int option) { std::vector<Machine*> currentSolution = initialSolution; int bestZ = calculateZ(currentSolution); do { std::vector<Machine*> bestNeighbour; switch (option) { case 0: bestNeighbour = greedyInterReinsertion(currentSolution); break; case 1: bestNeighbour = greedyIntraReinsertion(currentSolution); break; case 2: bestNeighbour = greedyInterSwap(currentSolution); break; case 3: bestNeighbour = greedyIntraSwap(currentSolution); break; case 4: bestNeighbour = anxiousInterReinsertion(currentSolution); break; case 5: bestNeighbour = anxiousIntraReinsertion(currentSolution); break; case 6: bestNeighbour = anxiousInterSwap(currentSolution); break; case 7: bestNeighbour = anxiousIntraSwap(currentSolution); break; } int newZ = calculateZ(bestNeighbour); if (newZ < bestZ) { currentSolution = bestNeighbour; bestZ = newZ; } else { break; } } while (true); return currentSolution; } // greedy std::vector<Machine*> GRASP::greedyIntraReinsertion(std::vector<Machine*> currentSolution) { std::vector<Machine*> bestSolution = currentSolution; int bestZ = calculateZ(bestSolution); for (int i = 0; i < currentSolution.size(); i++) { for (int j = 0; j < currentSolution[i]->assignedTasks(); j++) { for (int k = 0; k < currentSolution[i]->assignedTasks(); k++) { if (k == j) continue; std::vector<Machine*> neighbouringSolution; for (int l = 0; l < currentSolution.size(); l++) { neighbouringSolution.push_back(new Machine(currentSolution[l]->getTaskArray())); } neighbouringSolution[i]->reinsertTask(j, k); int newZ = calculateZ(neighbouringSolution); if (newZ < bestZ) { bestZ = newZ; bestSolution = neighbouringSolution; } } } } return bestSolution; } std::vector<Machine*> GRASP::greedyInterReinsertion(std::vector<Machine*> currentSolution) { std::vector<Machine*> bestSolution = currentSolution; int bestZ = calculateZ(bestSolution); for (int i = 0; i < currentSolution.size(); i++) { for (int j = 0; j < currentSolution.size(); j++) { if (i == j) continue; for (int k = 0; k < currentSolution[i]->assignedTasks(); k++) { for (int l = 0; l < currentSolution[j]->assignedTasks(); l++) { std::vector<Machine*> neighbouringSolution; for (int m = 0; m < currentSolution.size(); m++) { neighbouringSolution.push_back(new Machine(currentSolution[m]->getTaskArray())); } neighbouringSolution[i]->intermachineTaskReinsertion(k, neighbouringSolution[j], l); int newZ = calculateZ(neighbouringSolution); if (newZ < bestZ) { bestZ = newZ; bestSolution = neighbouringSolution; } } } } } return bestSolution; } std::vector<Machine*> GRASP::greedyIntraSwap(std::vector<Machine*> currentSolution) { std::vector<Machine*> bestSolution = currentSolution; int bestZ = calculateZ(bestSolution); for (int i = 0; i < currentSolution.size(); i++) { for (int j = 0; j < currentSolution[i]->assignedTasks(); j++) { for (int k = 0; k < currentSolution[i]->assignedTasks(); k++) { if (k == j) continue; std::vector<Machine*> neighbouringSolution; for (int l = 0; l < currentSolution.size(); l++) { neighbouringSolution.push_back(new Machine(currentSolution[l]->getTaskArray())); } neighbouringSolution[i]->swapTask(j, k); int newZ = calculateZ(neighbouringSolution); if (newZ < bestZ) { bestZ = newZ; bestSolution = neighbouringSolution; } } } } return bestSolution; } std::vector<Machine*> GRASP::greedyInterSwap(std::vector<Machine*> currentSolution) { std::vector<Machine*> bestSolution = currentSolution; int bestZ = calculateZ(bestSolution); for (int i = 0; i < currentSolution.size(); i++) { for (int j = 0; j < currentSolution.size(); j++) { if (i == j) continue; for (int k = 0; k < currentSolution[i]->assignedTasks(); k++) { for (int l = 0; l < currentSolution[j]->assignedTasks(); l++) { std::vector<Machine*> neighbouringSolution; for (int m = 0; m < currentSolution.size(); m++) { neighbouringSolution.push_back(new Machine(currentSolution[m]->getTaskArray())); } neighbouringSolution[i]->intermachineTaskSwap(k, neighbouringSolution[j], l); int newZ = calculateZ(neighbouringSolution); if (newZ < bestZ) { bestZ = newZ; bestSolution = neighbouringSolution; } } } } } return bestSolution; } // anxious std::vector<Machine*> GRASP::anxiousInterReinsertion(std::vector<Machine*> currentSolution) { int bestZ = calculateZ(currentSolution); for (int i = 0; i < currentSolution.size(); i++) { for (int j = 0; j < currentSolution.size(); j++) { if (i == j) continue; for (int k = 0; k < currentSolution[i]->assignedTasks(); k++) { for (int l = 0; l < currentSolution[j]->assignedTasks(); l++) { std::vector<Machine*> neighbouringSolution; for (int m = 0; m < currentSolution.size(); m++) { neighbouringSolution.push_back(new Machine(currentSolution[m]->getTaskArray())); } neighbouringSolution[i]->intermachineTaskReinsertion(k, neighbouringSolution[j], l); int newZ = calculateZ(neighbouringSolution); if (newZ < bestZ) { return neighbouringSolution; } } } } } return currentSolution; } std::vector<Machine*> GRASP::anxiousIntraReinsertion(std::vector<Machine*> currentSolution) { int bestZ = calculateZ(currentSolution); for (int i = 0; i < currentSolution.size(); i++) { for (int j = 0; j < currentSolution[i]->assignedTasks(); j++) { for (int k = 0; k < currentSolution[i]->assignedTasks(); k++) { if (k == j) continue; std::vector<Machine*> neighbouringSolution; for (int l = 0; l < currentSolution.size(); l++) { neighbouringSolution.push_back(new Machine(currentSolution[l]->getTaskArray())); } neighbouringSolution[i]->reinsertTask(j, k); if (calculateZ(neighbouringSolution) < bestZ) { return neighbouringSolution; } } } } return currentSolution; } std::vector<Machine*> GRASP::anxiousInterSwap(std::vector<Machine*> currentSolution) { int bestZ = calculateZ(currentSolution); for (int i = 0; i < currentSolution.size(); i++) { for (int j = 0; j < currentSolution.size(); j++) { if (i == j) continue; for (int k = 0; k < currentSolution[i]->assignedTasks(); k++) { for (int l = 0; l < currentSolution[j]->assignedTasks(); l++) { std::vector<Machine*> neighbouringSolution; for (int m = 0; m < currentSolution.size(); m++) { neighbouringSolution.push_back(new Machine(currentSolution[m]->getTaskArray())); } neighbouringSolution[i]->intermachineTaskSwap(k, neighbouringSolution[j], l); if (calculateZ(neighbouringSolution) < bestZ) { return neighbouringSolution; } } } } } return currentSolution; } std::vector<Machine*> GRASP::anxiousIntraSwap(std::vector<Machine*> currentSolution) { int bestZ = calculateZ(currentSolution); for (int i = 0; i < currentSolution.size(); i++) { for (int j = 0; j < currentSolution[i]->assignedTasks(); j++) { for (int k = 0; k < currentSolution[i]->assignedTasks(); k++) { if (k == j) continue; std::vector<Machine*> neighbouringSolution; for (int l = 0; l < currentSolution.size(); l++) { neighbouringSolution.push_back(new Machine(currentSolution[l]->getTaskArray())); } neighbouringSolution[i]->swapTask(j, k); if (calculateZ(neighbouringSolution) < bestZ) { return neighbouringSolution; } } } } return currentSolution; } void GRASP::assignNextTask(Machine* machine, Task* task) { machine->addTask(task); } std::vector<Task*> GRASP::selectShorterTasks(PMSProblem& pmsp) { Task* auxTask = new Task(-1, BIG_NUMBER, BIG_NUMBER); Task* shortestTask; std::vector<Task*> shorterTasks; for (int i = 0; i < pmsp.getm(); i++) { shortestTask = auxTask; for (int j = 0; j < pmsp.getn(); j++) { if (pmsp.getTask(j)->getProcessTime() + pmsp.getTask(j)->getSetupTimeZero() < shortestTask->getProcessTime() + shortestTask->getSetupTimeZero() && !pmsp.getTask(j)->assigned()) { shortestTask = pmsp.getTask(j); } } shortestTask->setAsAssigned(); shorterTasks.push_back(shortestTask); } delete auxTask; return shorterTasks; } bool GRASP::allTasksAssigned(PMSProblem& pmsp) { for (int i = 0; i < pmsp.getn(); i++) { if (!pmsp.getTask(i)->assigned()) { return false; } } return true; } void GRASP::bestInsertion(PMSProblem& pmsp, std::vector<Machine*>& solution) { int bestTCT = BIG_NUMBER; int bestTask; int bestPosition; int bestMachine; int lastBestTCT = 0; std::vector<int> bestTasksArr; std::vector<int> bestPositionsArr; std::vector<int> bestMachineArr; for (int k = 0; k < pmsp.getk(); k++) { for (int i = 0; i < solution.size(); i++) { for (int j = 0; j < pmsp.getn(); j++) { if (pmsp.getTask(j)->assigned()) { continue; } int newPosition; int newTCT = calculateBestTCT(solution[i], pmsp.getTask(j), newPosition); if (newTCT < bestTCT) { bestTCT = newTCT; bestTask = j; bestPosition = newPosition; bestMachine = i; } } } if (lastBestTCT != bestTCT) { bestTasksArr.push_back(bestTask); bestPositionsArr.push_back(bestPosition); bestMachineArr.push_back(bestMachine); pmsp.getTask(bestTask)->setAsAssigned(); bestTCT = BIG_NUMBER; lastBestTCT = bestTCT; } } for (int i = 0; i < bestTasksArr.size(); i++) { pmsp.getTask(bestTasksArr[i])->setAsUnassigned(); } int randomNumber = rand() % bestTasksArr.size(); solution[bestMachineArr[randomNumber]]->insertTask(pmsp.getTask(bestTasksArr[randomNumber]), bestPositionsArr[randomNumber]); pmsp.getTask(bestTasksArr[randomNumber])->setAsAssigned(); } int GRASP::calculateBestTCT(Machine* machine, Task* task, int& position) { int bestTCT = BIG_NUMBER; int actualTCT = TCT(machine->getTaskArray()); for (int i = 0; i < machine->assignedTasks() + 1; i++) { Machine aux(machine->getTaskArray()); aux.insertTask(task, i); int tct = TCT(aux.getTaskArray()); if (tct - actualTCT < bestTCT) { bestTCT = tct - actualTCT; position = i; } } return bestTCT; } int GRASP::TCT(std::vector<Task*> machine) { int sum = 0; for (int i = 0; i < machine.size(); i++) { sum += C(machine, i); } return sum; } int GRASP::C(std::vector<Task*> machine, int pos) { int sum = machine[0]->getSetupTimeZero() + machine[0]->getProcessTime(); for (int i = 0; i < pos; i++) { sum += machine[i]->getSetupTimeTo(machine[i + 1]->getId()) + machine[i + 1]->getProcessTime(); } return sum; } int GRASP::calculateZ(std::vector<Machine*>& solution) { int z = 0; for (int i = 0; i < solution.size(); i++) { z += TCT(solution[i]->getTaskArray()); } return z; } void GRASP::printSolution(std::vector<Machine*>& solution) { int complexTime = 0; for (int i = 0; i < solution.size(); i++) { std::cout << "\tMáquina " << i + 1 << " (" << TCT(solution[i]->getTaskArray()) << ") : { "; complexTime += TCT(solution[i]->getTaskArray()); for (int j = 0; j < solution[i]->assignedTasks(); j++) { std::cout << solution[i]->getTaskArray()[j]->getId() + 1 << ' '; } std::cout << "}\n"; } std::cout << "\tTiempo total: " << complexTime << '\n'; } void GRASP::setPostprocessingOption(int option) { postprocessingOption_ = option; }
#include <iostream> #include "Heap.h" #include"HeapNode.h" using namespace std; template <typename T> HeapNode<T>::HeapNode(const T& data) { this->data = data; this->left = nullptr; this->right = nullptr; this->parent = nullptr; } template <typename T> Heap<T>::Heap(int capacity) { this->capacity = capacity; this->size = 0; this->root = nullptr; this->last = nullptr; } template <typename T> void Heap<T>::addKey(const T& key) { if (this->size + 1 > this->capacity) { //error } else if (this->root == nullptr) { this->root = new HeapNode<T>(key); this->last = this->root; } else if (this->root == this->last) { this->root->left = new HeapNode<T>(key); this->root->left->parent = this->root; this->last = this->root->left; fixUp(); } else if (this->last->parent->left == this->last) { HeapNode<T> *tmp = new HeapNode<T>(key); tmp->parent = this->last->parent; this->last->parent->right = tmp; this->last = tmp; fixUp(); //this->last->parent->right = new HeapNode<T>(key); } else if (this->last->parent->right == this->last) { HeapNode<T>* tmp = this->last->parent; while (tmp == tmp->parent->right) { tmp = tmp->parent; } tmp = tmp->parent->right; while (tmp->left) { tmp = tmp->left; } tmp->left = new HeapNode<T>(key); tmp->left->parent = tmp; this->last = tmp->left; fixUp(); } this->size++; } template <typename T> void Heap<T>::fixUp() { if (this->last->data > this->lsst->parent->data) { HeapNode<T>* tmp = this->last; while (tmp->data > tmp->parent->data & tmp != this->root) { swap(tmp, tmp->parent); /*T a = tmp->data; tmp->data = tmp->parent->data; tmp->parent->data = a; */ tmp = tmp->parent; } } } template <typename T> void Heap<T>::swap(HeapNode<T>* child, HeapNode<T>* parent) { T a = child->data; child->data = parent->data; parent->data = a; } template <typename T> bool Heap<T>::find(const T& key) { int result = search(this->root, key); if (result > 0) return true; else return false; } template <typename T> int Heap<T>::search(HeapNode<T>* root, const T& key) { if (!root) return 0; if (root->data == key) return 1; return Heap<T>::search(root->left, key) + Heap<T>::search(root->right, key); } template <typename T> void Heap<T>::print() { straight(this->root); } template <typename T> void Heap<T>::straight(HeapNode<T>* root) { if (!root) return; printf("%d. \"%s\"\n", root->info); straight(root->left); straight(root->right); } template <typename T> T Heap<T>::getMax() { return this->root->data; } template <typename T> void Heap<T>::remove(const T& key) { T tmp = this->root->data; } template <typename T> void Heap<T>::fixDown(HeapNode<T>* node) { }
#pragma once #include <string> #include <iostream> using namespace std; /*Summary: Methods: Encryption: Firstly controls special characters for ç, ğ, ı and ü then writes row and columns where is equal char in table. Decryption: Executes decrypted string two by two, finds char in the table according to row and column info.*/ class Polybius { private: char PArray[5][5] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','ö','p','r','s','þ','t','u','v','y','z' }; char UArray[5][5]= { 'A','B','C','D','E','F','G','H','İ','J','K','L','M','N','O','Ö','P','R','S','Þ','T','U','V','Y','Z' }; public: void Encryption(string& str); void Decryption(string& str); };
//$Id$ //------------------------------------------------------------------------------ // GmatTime //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Author: Tuan Dang Nguyen // Created: 2014/07/15 /** * This class is used to define GMAT time with a high precision. It has 2 parts: * The first part stores number of seconds. The second part stores fraction of * seconds. */ //------------------------------------------------------------------------------ #ifndef GmatTime_hpp #define GmatTime_hpp #include "gmatdefs.hpp" class GMAT_API GmatTime { public: GmatTime(); virtual ~GmatTime(); GmatTime(const GmatTime& gt); GmatTime(const GmatEpoch mjd); const GmatTime& operator=(const GmatTime& gt); GmatTime operator+(const GmatTime& gt) const; GmatTime operator-(const GmatTime& gt) const; const GmatTime& operator+=(const GmatTime& gt); const GmatTime& operator-=(const GmatTime& gt); const GmatTime& operator=(const GmatEpoch mjd); GmatTime operator+(const GmatEpoch mjd) const; GmatTime operator-(const GmatEpoch mjd) const; const GmatTime& operator+=(const GmatEpoch mjd); const GmatTime& operator-=(const GmatEpoch mjd); virtual GmatTime* Clone(); virtual void SetTimeInSec(const Real sec); const GmatEpoch GetMjd(); const Real GetTimeInSec(); const Real GetSec(); const Real GetFracSec(); protected: Real Sec; // time in seconds Real FracSec; // time in fraction of seconds }; #endif //GmatTime_hpp
int intersectPoint(Node* first, Node* second) { Node *head1=first,*head2=second; int n=0,m=0,d=0; while(first) { first=first->next; n++; } while(second) { second=second->next; m++; } first=head1; second=head2; d=abs(n-m); if(n>m) { while(d--) first=first->next; } else { while(d--) second=second->next; } while(first && second) { if(first==second) return first->data; first=first->next; second=second->next; } return -1; }
#include<stdio.h> int main() { int arr[5] = { 0 }; for (int i = 0; i < 5; i++) { printf("%d번 학생의 프C 성적 : ", i+1); scanf("%d", &arr[i]); } for (int i = 1; i < 5; i++) { if (arr[0] <= arr[i]) { arr[0] = arr[i]; } } printf("최고 점수 : %d", arr[0]); return 0; }
/* File: curved.cpp * Name: Paulo Lemus * Date: 2/15/2017 */ #include <iostream> #include <fstream> #include <vector> #include <cmath> #include "curved.h" float calcAverage(std::vector<float>& v){ // Take in an array and pass back the average of array float average = 0; for(int i = 0; i < v.size(); i++){ average += v[i]; } average = (float)average / (float)v.size(); return average; } // Function that takes in an array and average and calculated the standard deviation to return float stdDeviation(std::vector<float>& v, float average){ float stdDev = 0; for(int i = 0; i < v.size(); i++){ float temp = v[i] - average; temp = temp * temp; stdDev += temp; } stdDev = stdDev / (float)v.size(); stdDev = sqrt(stdDev); return stdDev; } // Function that prints all grades on curve using stdDeviation and standard void printGrades(std::vector<float>& v, float average, float stdDev){ for(int i = 0; i < v.size(); i++){ char letterGrade; if(v[i] < average - 1.5f * stdDev) letterGrade = 'F'; else if(v[i] >= average - 1.5f * stdDev && v[i] < average - 0.5f * stdDev) letterGrade = 'D'; else if(v[i] >= average - 0.5f * stdDev && v[i] < average + 0.5f * stdDev) letterGrade = 'C'; else if(v[i] >= average + 0.5f * stdDev && v[i] < average + 1.5f * stdDev) letterGrade = 'B'; else if(v[i] >= average + 1.5f * stdDev) letterGrade = 'A'; std::cout << "Index " << i << ": " << "Grade " << v[i] << " = " << letterGrade << std::endl; } }
#include<cstdio> #include<iostream> #include<queue> using namespace std; struct stone { int pi,di; friend bool operator <(stone a, stone b) { if(a.di == b.di) return a.pi > b.pi; return a.di > b.di; } }a; int main() { int T,t; priority_queue<stone>q; cin >> T; while(T--) { cin >> t; while(!q.empty()) q.pop(); for(int i = 0; i < t; i++) { cin >> a.di >> a.pi; q.push(a); } int sum = 0, num = 1; while(!q.empty()) { if(num%2 != 0) { a=q.top(); q.pop(); a.di += a.pi; sum = a.di; q.push(a); } else q.pop(); num++; } cout << q.top().di << endl; } return 0; }
/********************************************************** * License: The MIT License * https://www.github.com/doc97/TxtAdv/blob/master/LICENSE **********************************************************/ #include "catch.hpp" #include "TxtParser.h" #include "LambdaExpression.h" namespace txt { TEST_CASE("TxtParser - no variables", "[TxtParser]") { std::string text1 = "no variables here"; std::string text2 = "or here"; GameState state; TxtParser parser(&state); REQUIRE(parser.ParseText(text1) == text1); REQUIRE(parser.ParseText(text2) == text2); } TEST_CASE("TxtParser - simple variable", "[TxtParser]") { GameState state; state.SetString("first_name", "Foo"); state.SetString("middle_name", "Bar"); state.SetString("last_name", "Foobar"); TxtParser parser(&state); REQUIRE(parser.ParseText("{s_first_name}") == "Foo"); REQUIRE(parser.ParseText("{s_middle_name}") == "Bar"); REQUIRE(parser.ParseText("{s_last_name}") == "Foobar"); } TEST_CASE("TxtParser - string variable", "[TxtParser]") { GameState state; state.SetString("name", "Foo"); TxtParser parser(&state); REQUIRE(parser.ParseText("{s_unknown}") == "<unknown>"); REQUIRE(parser.ParseText("{a_invalid}") == "{a_invalid}"); REQUIRE(parser.ParseText("{name}") == "{name}"); } TEST_CASE("TxtParser - float variable", "[TxtParser]") { GameState state; state.SetFloat("value1", 1.5f); state.SetFloat("value2", 2.256f); TxtParser parser(&state); REQUIRE(parser.ParseText("{value1}") == "{value1}"); REQUIRE(parser.ParseText("{f_value1}") == "1.50"); REQUIRE(parser.ParseText("{f_value2}") == "2.26"); } TEST_CASE("TxtParser - int variable", "[TxtParser]") { GameState state; state.SetInt("value1", -1); state.SetInt("value2", 2); TxtParser parser(&state); REQUIRE(parser.ParseText("{value1}") == "{value1}"); REQUIRE(parser.ParseText("{i_value1}") == "-1"); REQUIRE(parser.ParseText("{i_value2}") == "2"); } TEST_CASE("TxtParser - expression variable", "[TxtParser]") { GameState state; TxtParser parser(&state); parser.AddExpression("expr1", std::make_unique<LambdaExpression>([]() { return "foo"; })); parser.AddExpression("expr2", std::make_unique<LambdaExpression>([]() { return "bar"; })); REQUIRE(parser.ParseText("{expr1}") == "{expr1}"); REQUIRE(parser.ParseText("{x_expr1}") == "foo"); REQUIRE(parser.ParseText("{x_expr2}") == "bar"); REQUIRE(parser.ParseText("{x_expr1}{x_expr2}") == "foobar"); } TEST_CASE("TxtParser - variable type", "[TxtParser]") { GameState state; state.SetInt("value", 1); state.SetFloat("value", 1.5f); state.SetString("value", "Foo"); TxtParser parser(&state); REQUIRE(parser.ParseText("{i_value}") == "1"); REQUIRE(parser.ParseText("{f_value}") == "1.50"); REQUIRE(parser.ParseText("{s_value}") == "Foo"); } TEST_CASE("TxtParser - insert variable", "[TxtParser]") { GameState state; state.SetString("name", "Foo"); TxtParser parser(&state); REQUIRE(parser.ParseText("{s_name} Bar") == "Foo Bar"); REQUIRE(parser.ParseText("Bar {s_name}") == "Bar Foo"); REQUIRE(parser.ParseText("{s_name}Bar") == "FooBar"); REQUIRE(parser.ParseText("Bar{s_name}") == "BarFoo"); } TEST_CASE("TxtParser - recursive variable", "[TxtParser]") { GameState state; state.SetString("rgx", "s_name"); state.SetString("name", "Foo"); TxtParser parser(&state); REQUIRE(parser.ParseText("{s_rgx}") == "s_name"); REQUIRE(parser.ParseText("{{s_rgx}}") == "Foo"); } TEST_CASE("TxtParser - recursive depth", "[TxtParser]") { GameState state; state.SetString("rec1", "{s_rec2}"); state.SetString("rec2", "{s_rec1}"); TxtParser parser(&state); // Max recursive depth is 8 REQUIRE(parser.ParseText("{s_rec1}") == "{s_rec1}"); REQUIRE(parser.ParseText("{s_rec2}") == "{s_rec2}"); } TEST_CASE("TxtParser - dynamic, recursive variable expressions", "[TxtParser]") { GameState state; state.SetString("var_type", "s"); state.SetString("var_animal", "dog"); state.SetString("var_property", "name"); state.SetString("dog_name", "Fido"); state.SetString("expr", "{s_var_type}_{s_var_animal}_{s_var_property}"); TxtParser parser(&state); REQUIRE(parser.ParseText("{{s_var_type}_{s_var_animal}_{s_var_property}}") == "Fido"); REQUIRE(parser.ParseText("{{s_expr}}") == "Fido"); } } // namespace txt
/* SW Expert Academy 2382. [모의 SW 역량테스트] 미생물 격리 군집이 사라질 경우를 vector.erase로 했더니 테스트 케이스가 50개중 49개만 맞는다. 이유는 잘 모르겠다 ㅠㅠ */ #include <iostream> #include <algorithm> #include <vector> #include <math.h> #include <cstring> #define MAP_MAX 51 using namespace std; struct Crowd { int r, c, micro, dir; Crowd() {} Crowd(int _r, int _c, int _micro, int _dir) { r = _r; c = _c; micro = _micro; dir = _dir; } }; vector<Crowd> crowd; int r, c, m, d; int N, M, K, answer = 0; int dr[5] = {0, -1, 1, 0, 0}; // 상 하 좌 우 int dc[5] = {0, 0, 0, -1, 1}; void input() { crowd.clear(); answer = 0; cin >> N >> M >> K; for(int i = 0; i < K; i++) { cin >> r >> c >> m >> d; crowd.push_back(Crowd(r,c,m,d)); } } int reverse_dir(int dir) { switch (dir) { case 1: return 2; case 2: return 1; case 3: return 4; case 4: return 3; default: return 0; } } void check_same() { for(int i = 0; i < crowd.size(); i++) { vector<Crowd> tmp; int r = crowd[i].r; int c = crowd[i].c; for(int j = i+1; j < crowd.size(); j++) { if(r == crowd[j].r && c == crowd[j].c) { tmp.push_back(crowd[j]); crowd.erase(crowd.begin()+j); } } if(!tmp.empty()) { int max = crowd[i].micro; for(int p = 0; p < tmp.size(); p++) { if(tmp[p].micro > max) { max = tmp[p].micro; crowd[i].dir = tmp[p].dir; } crowd[i].micro += tmp[p].micro; } } } } void solve() { for(int t=0; t<M; t++) { for(int i = 0; i < crowd.size(); i++) { int nr = crowd[i].r + dr[crowd[i].dir]; int nc = crowd[i].c + dc[crowd[i].dir]; if(nr == 0 || nr == N-1 || nc == 0 || nc == N-1) { crowd[i].dir = reverse_dir(crowd[i].dir); crowd[i].micro = crowd[i].micro/2; if(crowd[i].micro == 0) { crowd.erase(crowd.begin()+i); i--; continue; } } crowd[i].r = nr; crowd[i].c = nc; } check_same(); } for(int i = 0; i < crowd.size(); i++) { answer += crowd[i].micro; } } int main(int argc, char** argv) { int test_case; int T; cin >> T; for(test_case = 1; test_case <= T; ++test_case) { input(); solve(); cout << "#" << test_case << " " << answer << endl; } return 0; }
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <time.h> #include <glib.h> #include <gtest/gtest.h> #include "multimedia/cowplayer.h" #include "multimedia/mm_debug.h" #include "multimedia/media_meta.h" #include "multimedia/media_attr_str.h" #ifdef __MM_YUNOS_LINUX_BSP_BUILD__ #include <multimedia/mm_amhelper.h> #endif // #include "native_surface_help.h" MM_LOG_DEFINE_MODULE_NAME("smp-cowplayer") #if 0 #undef MMLOGD #undef MMLOGI #undef MMLOGW #undef MMLOGE #undef TERM_PROMPT #define MMLOGD(format, ...) fprintf(stderr, "[D] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__) #define MMLOGI(format, ...) fprintf(stderr, "[I] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__) #define MMLOGW(format, ...) fprintf(stderr, "[W] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__) #define MMLOGE(format, ...) fprintf(stderr, "[E] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__) #define TERM_PROMPT(...) #endif static const char *g_video_file_path = "/usr/bin/ut/res/video/test.mp4"; static uint32_t g_play_time = 5; using namespace YUNOS_MM; static int g_prepared = 0; static int g_started = 0; static int g_stopped = 0; static int g_play_completed = 0; static int g_reset = 0; static int g_error_occured = 0; static int g_report_video_size =0; // static uint32_t g_surface_width = 1280; // static uint32_t g_surface_height = 720; #ifdef __MM_YUNOS_LINUX_BSP_BUILD__ static MMAMHelper * s_g_amHelper = NULL; #endif class MyListener : public CowPlayer::Listener { virtual void onMessage(int msg, int param1, int param2, const MMParamSP param) { if (msg != Component::kEventInfoBufferingUpdate || param1%20 == 0) MMLOGD("msg: %d, param1: %d, param2: %d, param: %p", msg, param1, param2, param.get()); switch ( msg ) { case Component::kEventPrepareResult: g_prepared = 1; break; case Component::kEventStartResult: g_started = 1; INFO("player started"); break; case Component::kEventPaused: g_started = 0; INFO("player paused"); break; case Component::kEventStopped: g_stopped = 1; INFO("player stopped"); break; case Component::kEventEOS: g_play_completed = 1; break; case Component::kEventResetComplete: g_reset = 1; break; case Component::kEventError: g_error_occured = 1; break; case Component::kEventGotVideoFormat: g_report_video_size = 1; break; default: break; } } }; class SimpleCowPlayer : public testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } }; // wait until prepare is done void waitUntilDone(int &done) { int sleepCount = 0; while(!done && sleepCount++<100) usleep(50000); } #define CHECK_PLAYER_RET(status, command_str) do { \ if(status != MM_ERROR_SUCCESS && status != MM_ERROR_ASYNC){ \ MMLOGE("%s failed: %d", command_str, status); \ ret = -1; \ goto error; \ } \ }while (0) TEST_F(SimpleCowPlayer, simpleCowPlayer) { mm_status_t status; int ret = 0; std::map<std::string,std::string> header; MMLOGI("Hello SimpleCowPlayer"); // create cowplayer & listener MyListener * listener = new MyListener(); ASSERT_NE(listener, (void*)NULL); CowPlayer * player = new CowPlayer(); if ( !player ) { MMLOGE("no mem"); ret = -1; goto error; } player->setListener(listener); #if 0 // set rendering surface WindowSurface *ws = createSimpleSurface(800, 600); if (!ws) { PRINTF("init surface fail\n"); exit(-1); } player->setVideoDisplay(ws); #endif MMLOGI("settting datasource ..."); status = player->setDataSource(g_video_file_path, &header); CHECK_PLAYER_RET(status, "setDataSource"); #ifdef __MM_YUNOS_LINUX_BSP_BUILD__ MMLOGI("set connectionId: %s\n", s_g_amHelper->getConnectionId()); player->setAudioConnectionId(s_g_amHelper->getConnectionId()); #endif MMLOGI("prepare ..."); status = player->prepareAsync(); CHECK_PLAYER_RET(status, "prepareAsync"); waitUntilDone(g_prepared); if(!g_prepared){ MMLOGE("prepareAsync failed after wait 5 seconds"); ret = -1; goto error; } MMLOGI("start ..."); status = player->start(); CHECK_PLAYER_RET (status, "start"); while ( !g_play_completed && !g_error_occured ) { // check video resolution if(g_report_video_size){ int width , height; status = player->getVideoSize(width, height); if(status != MM_ERROR_SUCCESS && status != MM_ERROR_ASYNC){ MMLOGE("getVideoSize error: %d", status); } else MMLOGI("get video size : %d x %d",width, height); g_report_video_size = 0; } sleep(1); g_play_time--; if (!g_play_time) break; } MMLOGI("stopping ..."); player->stop(); waitUntilDone(g_stopped); MMLOGI("resetting ..."); player->reset(); waitUntilDone(g_reset); error: MMLOGI("destroying ..."); delete player; delete listener; // destroySimpleSurface(ws); EXPECT_EQ(ret, 0); MMLOGI("exit"); } int parseCommandLine(int argc, char* const argv[]) { GError *error = NULL; GOptionContext *context; const char* file_name = NULL; uint32_t playtime = g_play_time; static GOptionEntry entries[] = { {"add", 'a', 0, G_OPTION_ARG_STRING, &file_name, " set the file name to play", NULL}, {"playtime", 'p', 0, G_OPTION_ARG_INT, &playtime, "quit after play # seconds", NULL}, {NULL} }; context = g_option_context_new(MM_LOG_TAG); g_option_context_add_main_entries(context, entries, NULL); g_option_context_set_help_enabled(context, TRUE); if (!g_option_context_parse(context, &argc, (gchar***)&argv, &error)) { ERROR("option parsing failed: %s\n", error->message); return -1; } g_option_context_free(context); if (file_name) { g_video_file_path = file_name; } DEBUG("g_video_file_name: %s", g_video_file_path); if (playtime >= 0) g_play_time = playtime; return 0; } int main(int argc, char* const argv[]) { int ret = 0; parseCommandLine(argc, argv); #ifdef __MM_YUNOS_LINUX_BSP_BUILD__ try { s_g_amHelper = new MMAMHelper(); if (s_g_amHelper->connect() != MM_ERROR_SUCCESS) { MMLOGE("failed to connect audiomanger\n"); delete s_g_amHelper; return -1; } } catch (...) { MMLOGE("failed to new amhelper\n"); return -1; } MMLOGD("connect am success\n"); #endif try { ::testing::InitGoogleTest(&argc, (char **)argv); ret = RUN_ALL_TESTS(); } catch (...) { ERROR("InitGoogleTest failed!"); #ifdef __MM_YUNOS_LINUX_BSP_BUILD__ s_g_amHelper->disconnect(); #endif return -1; } #ifdef __MM_YUNOS_LINUX_BSP_BUILD__ s_g_amHelper->disconnect(); #endif return ret; }
/* * DepthProfilerProxy.hpp * * Created on: 6 Aug 2018 * Author: Thomas Maters * Email : thomasmaters@hotmail.com (TG.Maters@student.han.nl) */ #ifndef SRC_DEPTHPROFILERPROXY_HPP_ #define SRC_DEPTHPROFILERPROXY_HPP_ #include "../Communication/IOHandler.hpp" #include "../Communication/RequestResponseHandler.hpp" #include "../Communication/UDP/UDPConnection.hpp" #include "../Messages/BottomTransportMessage.hpp" #include "BottomProfile.hpp" #include "Dune.hpp" #include <thread> namespace Profiler { class DepthProfilerProxy : public Communication::ResponseHandler, public std::enable_shared_from_this<DepthProfilerProxy> { public: DepthProfilerProxy() : self_ptr_(weak_from_this()), outgoing_communication_(Communication::IOHandler::getInstance().getIOService(), "localhost", "2000", "2001") { outgoing_communication_.addResponseHandler(self_ptr_.lock()); } virtual ~DepthProfilerProxy() { } /** * Handles incoming response messages, override this function to do things with the response. * @param data Pointer to the data. * @param length Of the data. */ void handleResponse([[maybe_unused]] uint8_t* data, [[maybe_unused]] std::size_t length) { } /** * Sends a bottomprofile over a UDP connection as a BottomTransportMessage. * @param profile To send. */ template <std::size_t H, std::size_t W, typename T> void sendBottomProfile(BottomProfile<H, W, T>& profile) { Messages::BottomTransportMessage message; message.setDunes(profile); message.setAverageTransport(profile.average_transport_); message.setTimeOfPing(profile.time_); outgoing_communication_.sendRequest(message, (std::size_t)0, false); } private: std::weak_ptr<DepthProfilerProxy> self_ptr_; Communication::UDP::UDPServerClient outgoing_communication_; }; } // Namespace Profiler #endif /* SRC_DEPTHPROFILERPROXY_HPP_ */
// // Emulator - Simple C64 emulator // Copyright (C) 2003-2016 Michael Fink // /// \file Machine.cpp C64 machine class // // includes #include "StdAfx.h" #include "Machine.hpp" #include "VICMemoryAdapter.hpp" #include "SIDMemoryAdapter.hpp" #include "CIAMemoryAdapter.hpp" using C64::Machine; Machine::Machine() :m_processor(m_memoryManager), m_vic(m_memoryManager, m_processor), m_sid(m_memoryManager) { m_memoryManager.SetHandler(handlerVIC, std::shared_ptr<IMemory>(new VICMemoryAdapter(m_vic))); m_memoryManager.SetHandler(handlerCIA1, std::shared_ptr<IMemory>(new CIAMemoryAdapter(m_cia1, 0xdc00))); m_memoryManager.SetHandler(handlerCIA2, std::shared_ptr<IMemory>(new CIAMemoryAdapter(m_cia2, 0xdd00))); m_memoryManager.SetHandler(handlerSID, std::shared_ptr<IMemory>(new SIDMemoryAdapter(m_sid))); m_cia1.SetPortListener(&m_keyboard); m_cia2.SetPortListener(&m_vic); } Machine::~Machine() throw() { } void Machine::Run() { for(;;) { m_vic.Step(); m_processor.Step(); } }
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // #ifndef POOMA_DOMAIN_DOMAIN_TRAITS_RANGE_H #define POOMA_DOMAIN_DOMAIN_TRAITS_RANGE_H //----------------------------------------------------------------------------- // Class: // DomainTraits<Range<N>> // DomainChangeDim<Range<N>,Dim> //----------------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////// /** @file * @ingroup Domain * @brief * DomainTraits<Range<N>> is a specialization of the general DomainTraits * class, for the case of Range domain objects. * * It defines the general * behavior of Range, including its typedef and static data * characteristics, how to store data for a Range, etc. It is used by the * Domain base class of Range to implement most of the public interface. * * DomainTraits<Range<Dim>> stores the characteristics and much of the * implementation details for Range domain objects. A Range represents * a sequence of numbers [a, a+s, a+2s, ... b], with a run-time stride s. * * A general version of DomainTraits<Range<Dim>> is defined here, which * only includes the basic information to make Range<Dim> look like an * array of Range<1> objects. DomainTraits<Range<1>> is a more specific * specialization which provides most of the necessary interface information * for items which need to know about Range. Since most of the interface * for a domain object is only available for 1D versions of that domain * object, the Range<1> specialization defines more interface functions than * the Range<Dim> case. */ //----------------------------------------------------------------------------- // Typedefs: //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Includes: //----------------------------------------------------------------------------- #include "Domain/DomainTraits.h" #include "Utilities/UninitializedVector.h" //----------------------------------------------------------------------------- // Forward Declarations: //----------------------------------------------------------------------------- template <int Dim> class Loc; template <> class Loc<1>; template <int Dim> class Interval; template <> class Interval<1>; template <int Dim> class Range; template <> class Range<1>; /** * DomainTraits<Range<Dim>>: * The specialization of DomainTraits for Range, for dimensions greater than * one. */ template<int Dim> struct DomainTraits< Range<Dim> > : public DomainTraitsDomain<Range<Dim>, int, Dim> { // convenience typedef typedef DomainTraitsDomain<Range<Dim>, int, Dim> Base_t; // necessary typedefs typedef typename Base_t::Element_t Element_t; typedef typename Base_t::Domain_t Domain_t; typedef typename Base_t::NewDomain1_t NewDomain1_t; typedef Range<1> OneDomain_t; typedef Range<1> PointDomain_t; typedef Interval<Dim> BlockDomain_t; typedef Loc<Dim> AskDomain_t; typedef Range<Dim> AddResult_t; typedef Range<Dim> MultResult_t; // type for storage of this domain's data typedef UninitializedVector<OneDomain_t,Dim,Element_t> Storage_t; // necessary static data enum { domain = Base_t::domain }; enum { dimensions = Base_t::dimensions, sliceDimensions = Dim }; enum { loopAware = false }; enum { singleValued = false }; enum { unitStride = false }; enum { wildcard = false }; // get the Nth element of the domain, and return a OneDomain_t // object with it (here, as a copy). static OneDomain_t &getDomain(Domain_t &d, int n) { return d[n]; } static const OneDomain_t &getDomain(const Domain_t &d,int n) { return d[n]; } // convert from the Nth element of the domain to a single point, if // possible, and return a PointDomain_t. Here, we just return a OneDomain_t, // since this is not a single-valued domain. static PointDomain_t &getPointDomain(Domain_t &d, int n) { return getDomain(d, n); } static const PointDomain_t &getPointDomain(const Domain_t &d, int n) { return getDomain(d, n); } // Domains get the chance to do special initialization. static void initializeStorage(Storage_t &dom) { dom.initialize(); } }; /** * DomainTraits<Range<1>>: * The specialization of DomainTraits for Range, for dimension == 1. */ template<> struct DomainTraits< Range<1> > : public DomainTraitsDomain<Range<1>, int, 1> { // necessary typedefs typedef Range<1> OneDomain_t; typedef Range<1> PointDomain_t; typedef Interval<1> BlockDomain_t; typedef Loc<1> AskDomain_t; typedef Range<1> AddResult_t; typedef Range<1> MultResult_t; // 1D necessary typedefs. Range requires three pieces of // information, the begin point, the length, and the stride. // If length==0, this is empty. typedef Element_t Storage_t[3]; // necessary static data enum { dimensions = 1, sliceDimensions = 1 }; enum { loopAware = false }; enum { singleValued = false }; enum { unitStride = false }; enum { wildcard = false }; // return size, endpoint, stride, and loop information static Element_t first(const Storage_t &d) { return d[0]; } static Element_t last(const Storage_t &d) { return d[0] + (d[1]-1)*d[2]; } static Element_t stride(const Storage_t &d) { return d[2]; } static Element_t length(const Storage_t &d) { return d[1]; } static Element_t min(const Storage_t &d) { return (d[2] > 0 ? d[0] : d[0] + (d[1]-1)*d[2]); } static Element_t max(const Storage_t &d) { return (d[2] < 0 ? d[0] : d[0] + (d[1]-1)*d[2]); } static bool empty(const Storage_t &d) { return (d[1] < 1); } static int loop(const Storage_t &) { return 0; } // get the Nth value of the domain, where value # 0 is first(), etc. static Element_t elem(const Storage_t &d, int n) { return d[0] + n*d[2]; } // get the Nth element of the domain, and return a OneDomain_t // object with it (here, as a copy). static OneDomain_t &getDomain(Domain_t &d, int) { return d; } static const OneDomain_t &getDomain(const Domain_t &d, int) { return d; } // convert from the Nth element of the domain to a single point, if // possible, and return a PointDomain_t. Here, we just return a OneDomain_t, // since this is not a single-valued domain. static PointDomain_t &getPointDomain(Domain_t &d, int n) { return getDomain(d, n); } static const PointDomain_t &getPointDomain(const Domain_t &d, int n) { return getDomain(d, n); } // Domains get the chance to do special initialization. Range's are // initialized to have length 0 and, just to avoid having a random value, // to start at 0 (although, for a length 0 domain, the endpoints are // actually undefined) and have stride = 1. static void initializeStorage(Storage_t &dom) { dom[0] = 0; // first dom[1] = 0; // length dom[2] = 1; // stride } // change this domain object to the given one. If things do not // match properly, assert a compile-time or run-time error. // For Range, we must have: // 1) the same dimensions==1 template<class T> static void setDomain(Storage_t &dom, const T &newdom) { CTAssert(DomainTraits<T>::dimensions == 1); dom[0] = DomainTraits<T>::getFirst(newdom); dom[1] = DomainTraits<T>::getLength(newdom); dom[2] = DomainTraits<T>::getStride(newdom); } // a specialized version of setDomain which accepts begin & end values. // The stride is set to + or - 1. template<class T1, class T2> static void setDomain(Storage_t &dom, const T1 &begval, const T2 &endval) { CTAssert(DomainTraits<T1>::dimensions == 1); CTAssert(DomainTraits<T2>::dimensions == 1); CTAssert(DomainTraits<T1>::singleValued); CTAssert(DomainTraits<T2>::singleValued); Element_t strideval = (endval < begval ? -1 : 1); dom[0] = begval; dom[1] = (endval - begval)/strideval + 1; dom[2] = strideval; } // a specialized version of setDomain which accepts begin & end values and // a stride. For Range, we must have (endval - begval) % stride == 0, so // that the endpoints are consistent with the stride. // NOTE: The endpoint restriction has been removed; if the endpoint is // not consistent, it will be truncated. To put this back to the // original method, uncomment the PAssert below. template<class T1, class T2, class T3> static void setDomain(Storage_t &dom, const T1 &begval, const T2 &endval, const T3 &strideval) { CTAssert(DomainTraits<T1>::dimensions == 1); CTAssert(DomainTraits<T2>::dimensions == 1); CTAssert(DomainTraits<T3>::dimensions == 1); CTAssert(DomainTraits<T1>::singleValued); CTAssert(DomainTraits<T2>::singleValued); CTAssert(DomainTraits<T3>::singleValued); //PAssert(strideval != 0 && ((endval - begval) % strideval)==0); dom[0] = begval; dom[1] = (endval - begval)/strideval + 1; dom[2] = strideval; } // change the loop variable for this object. For Range, this is a no-op. static void setLoop(Storage_t &, int) { } // change the value of this 1D domain given a user-supplied reference // domain and a wildcard. template<class UT, class T> static void setWildcardDomain(Storage_t &dom, const UT &u, const T &newdom) { CTAssert(DomainTraits<T>::wildcard); CTAssert(DomainTraits<T>::dimensions == 1); CTAssert(DomainTraits<UT>::dimensions == 1); dom[0] = newdom.first(u); // wildcard first method dom[1] = newdom.length(u); // wildcard length method dom[2] = newdom.stride(u); // wildcard stride method } // // compare this domain type to the given domain. For the comparisons // to be meaningful for Range, we must have: // 1) the same dimensions==1 // 2) both must not be empty // // 'isLessThan' returns true if dom < newdom template<class T> static bool isLessThan(const Storage_t &dom, const T &newdom) { CTAssert(DomainTraits<T>::dimensions == 1); PAssert(!(dom[1] < 1 || DomainTraits<T>::getEmpty(newdom))); return (dom[1] < DomainTraits<T>::getLength(newdom) || (dom[1] == DomainTraits<T>::getLength(newdom) && (dom[0] < DomainTraits<T>::getFirst(newdom) || (dom[0] == DomainTraits<T>::getFirst(newdom) && dom[2] < DomainTraits<T>::getStride(newdom))))); } // 'isEqualTo' returns true if dom == newdom template<class T> static bool isEqualTo(const Storage_t &dom, const T &newdom) { CTAssert(DomainTraits<T>::dimensions == 1); return ((dom[1] == 0 && DomainTraits<T>::getLength(newdom) == 0) || (dom[0] == DomainTraits<T>::getFirst(newdom) && dom[1] == DomainTraits<T>::getLength(newdom) && dom[2] == DomainTraits<T>::getStride(newdom))); } // // arithmetic accumulation operators. These only work with // other domain objects with the following characteristics: // 1) they are singleValue'd // 2) they have dimensions == 1 // // addAccum means dom[0] += newdom template<class T> static void addAccum(Storage_t &dom, const T &newdom) { CTAssert(DomainTraits<T>::singleValued && DomainTraits<T>::dimensions == 1); dom[0] += DomainTraits<T>::getFirst(newdom); } // subtractAccum means dom[0] -= newdom template<class T> static void subtractAccum(Storage_t &dom, const T &newdom) { CTAssert(DomainTraits<T>::singleValued && DomainTraits<T>::dimensions == 1); dom[0] -= DomainTraits<T>::getFirst(newdom); } // multiplyAccum means dom[0] *= newdom and dom[2] *= newdom template<class T> static void multiplyAccum(Storage_t &dom, const T &newdom) { CTAssert(DomainTraits<T>::singleValued && DomainTraits<T>::dimensions == 1); dom[0] *= DomainTraits<T>::getFirst(newdom); dom[2] *= DomainTraits<T>::getFirst(newdom); } // divideAccum means dom[0] /= newdom and dom[2] /= newdom template<class T> static void divideAccum(Storage_t &dom, const T &newdom) { CTAssert(DomainTraits<T>::singleValued && DomainTraits<T>::dimensions == 1); dom[0] /= DomainTraits<T>::getFirst(newdom); dom[2] /= DomainTraits<T>::getFirst(newdom); } }; /** * DomainChangeDim<T, int> is used to convert from a domain of one dimension * to another dimension (the second template parameter). * For Range<Dim1>, it changes from Dim1 to Dim2. */ template<int Dim1, int Dim2> struct DomainChangeDim<Range<Dim1>, Dim2> { // the type of the old and new domain typedef Range<Dim1> OldType_t; typedef Range<Dim2> NewType_t; // static data for old and new dimensions enum { oldDim = Dim1, newDim = Dim2 }; }; ////////////////////////////////////////////////////////////////////// #endif // POOMA_DOMAIN_DOMAIN_TRAITS_RANGE_H // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: DomainTraits.Range.h,v $ $Author: richard $ // $Revision: 1.27 $ $Date: 2004/11/01 18:16:32 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#include <iostream> #include <array> using namespace std; bool isFull(int A[], int size) { return false; } void enqueue (int A[], int value) { int front = 0; int rear = 0; int size = A.size(); if(!isFull(A, size)){ if(front != 0 && rear == size - 1){ rear = -1; } } } int main() { int A[7]; }
#ifndef CSTRING_HPP #define CSTRING_HPP char *strcpy(char *dst, const char *src); char *strncpy(char *dst, const char *src, int n); char *strcat(char *s, const char *ct); int strcmp(const char *cs,const char *ct); char *strchr(const char *cs, int c); char *strrchr(const char *cs, int c); int strspn(const char *cs,const char *ct); int strcspn(const char *cs,const char *ct); char *strpbrk(const char *cs,const char *ct); char *strstr(const char *cs,const char *ct); unsigned int strlen(const char *cs); #endif
#ifndef _EXPLICIT_FDM_CONTCPN_H_ #define _EXPLICIT_FDM_CONTCPN_H_ #include "explicit_fdm.h" #include "derivatives.h" #include <vector> class ExplicitFDMContCpn: public ExplicitFDM { public: /* Constructors and destructor */ ExplicitFDMContCpn(); ExplicitFDMContCpn(double spot, double maturity, double barrier, CpnFreq freq, unsigned int imax, unsigned int jmax, double upper, double lower = 0.0); ~ExplicitFDMContCpn(); virtual void calcPrice(); /* set functions */ void setCpnIdx(std::vector<double> cpnSchedule); void setCoupon(double coupon); private: double mBarrier; double mCoupon; CpnFreq mFreq; std::vector<unsigned int> mCpnIdx; // time index in which coupon date int mBarrierIdx; }; #endif
#ifndef MATH_H #define MATH_H #include <algorithm> #include <cmath> extern const double PI; template <class T> inline T clamp(const T& val, const T& min, const T& max){ return std::min(max, std::max(min, val)); } template <class T> inline T saw(const T& value, const T& period, const T& amp){ return (value/period-floor(value/period))*amp; } template <class T> inline T toDeg(const T& radians){ return radians*180/PI; } template <class T> inline T toRad(const T& degrees){ return degrees*PI/180; } #endif
// // Created by Alexey A. Ponomarev on 05.03.19. // #ifndef WEB_SERVER_TIME_H #define WEB_SERVER_TIME_H #include <iostream> class Time { public: static std::string AdvancedFormat(); private: static time_t rawtime_; static struct tm* timeinfo_; static char buffer_[80]; }; #endif //WEB_SERVER_TIME_H
/* * RobDuinoPinout.h * * Created on: 16. feb. 2017 * Author: david */ #ifndef ROBDUINO_H_ #define ROBDUINO_H_ // 0..7 //extern int D[8]; #define pD0 0 #define pD1 1 #define pD2 2 #define pD3 3 #define pD4 4 #define pD5 5 #define pD6 6 #define pD7 7 // 8..13 //extern int B[6]; #define pB0 8 #define pB1 9 #define pB2 10 #define pB3 11 #define pB4 12 #define pB5 13 // 14..19 //extern int C[6]; #define pC0 14 #define pC1 15 #define pC2 16 #define pC3 17 #define pC4 18 #define pC5 19 void initRobDuino(void) __attribute__((constructor)); class Button{ public: Button(char pin); Button(char pin, bool pull_up); Button(char pin, bool pull_up, char debounce_time_ms); bool down(); bool up(); bool on(); bool off(); bool wasPressed(); private: char _pin; bool _pull_up; char _debounce_time_ms; }; class UltraSonic { public: UltraSonic(char trigerPin, char echoPin); int distanceRead(); private: char _trigerPin; char _echoPin; }; #define NAPREJ 1 #define NAZAJ 2 #define STOP 0 #define GOR 1 #define DOL 2 class DOutDir { public: DOutDir(char firstPin, char secondPin); void stop(); void run(char direction); void run(char direction, char power); private: char _firstPin; char _secondPin; char _power; char _direction; }; #endif /* ROBDUINO_H_ */
/* *Polymorsiphm && Object pointer */ #include "iostream" using namespace std; class BC { public: int b; void display() { cout<<"\nBase Display"<<"\nB :- "<<b<<endl; } virtual void show() { cout<<"\nBase show"<<"\nB :- "<<b<<endl; } }; class DC : public BC { public: int d=0; void display() { cout<<"\nDerived Display"<<"\nB :- "<<b<<"\nD :-"<<d<<endl; } void show() { cout<<"\nDerived show"<<"\nB :- "<<b<<"\nD :-"<<d<<endl; } }; int main(int argc, char const *argv[]) { BC *bptr; BC base; DC derived; bptr=&base; cout<<"\nBase pointer Contains Address of Base class Object"; bptr->b=100; bptr->display(); bptr->show(); bptr=&derived; cout<<"\nBase pointer Contains Address of Derived class Object"; bptr->b=200; //bptr->d=500; bptr->display(); bptr->show(); bptr=&derived; system("pause"); return 0; }
#pragma once #include <string> #include <memory> #include <unordered_map> #include "gltools_Math.hpp" #include "gltools_Camera.hpp" namespace imog { class Shader { private: // Get a shared ptr to the shader from the global pool // by the concatenation of shaders paths static std::shared_ptr<Shader> getFromCache(const std::string& paths); public: // Global pool for shaders static std::vector<std::shared_ptr<Shader>> pool; static std::unordered_map<std::string, unsigned int> poolIndices; // Get a shared ptr to the shader from the global pool by name static std::shared_ptr<Shader> getByName(const std::string& name); // Create a new shader if it isn't on the gloabl pool static std::shared_ptr<Shader> create(const std::string& name, const std::string& vertexPath, const std::string& geomPath, const std::string& fragPath); // Create a new shader by a gived name, searching it in default forlder static std::shared_ptr<Shader> createByName(const std::string& name, bool hasGeometry = false, bool hasTesselation = false); // Update all shaders of the pool static void poolUpdate(const std::shared_ptr<Camera>& camera); private: std::string m_name; unsigned int m_program; std::unordered_map<std::string, int> m_uCache; std::unordered_map<std::string, bool> m_alertCache; // Alert only once :D // Return the OpenGL state machine ID for a filePath // shader, if source compilation fails returns 0 unsigned int loadShader(const std::string& filePath, unsigned int type); public: // Param constructor //! DO NOT CALL THIS DIRECTLY, use Create. // // 1. Create new program // 2. Compile shaders: // - required = vertex, fragment. // - optional = geometry. // 3. Apped it to a created program // 4. Link program // 5. Verify that its linked (if not, delete it and prompt an alert) Shader(const std::string& name, const std::string& vertexPath, const std::string& geomPath, const std::string& fragPath); // Destructor ~Shader(); // Bind set this program as active and use it to draw void bind(); // Unbind unset this program as active so won't be used to draw void unbind(); // Update upload to the shader camera data void update(const std::shared_ptr<Camera>& camera); // Returns the ID of the uniform associated to that string, // if its cached, return from cache, else request it to OpenGL // and store it. int uniform(const std::string& uniformName); // Upload a mat4 (view, proj, ...) void uMat4(const std::string& uniformName, const glm::mat4& mat); // Upload a float1 (height, intensity, ...) void uFloat1(const std::string& uniformName, float f); // Upload a vec3 (lightPos, color, ...) void uFloat3(const std::string& uniformName, float f1, float f2, float f3); // Upload a vec3 (lightPos, color, ...) void uFloat3(const std::string& uniformName, const glm::vec3& floats); // Upload a int1 (textures, ...) void uInt1(const std::string& uniformName, int i); }; } // namespace imog
// Copyright ⓒ 2020 Valentyn Bondarenko. All rights reserved. #include <StdAfx.hpp> #include <D3D11Render.hpp> #include <Error.hpp> #include <Log.hpp> namespace be::render { using be::utils::log::info; D3D11Render::D3D11Render() : clear_color{ 0.0f, 0.0f, 0.0f, 1.0f }, hwnd{ nullptr } { name = "Render"s; lib_name = "Diligent"s; api_name = "Direct3D"s; api_version = "11"s; } void D3D11Render::preinitialize(HWND winhandle, const math::int2& resolution, const bool& fullscreen) { hwnd = winhandle; if (!fullscreen) swap_chain_desc_size = resolution; else for (auto& mode : m_DisplayModes) if ((mode.Width == resolution.x) && (mode.Height == resolution.y)) swap_chain_desc_size = resolution; if(!swap_chain_desc_size.has_value() && fullscreen) { // keep trying, in order not to disapoint end-users RECT rc; ::GetWindowRect(::GetDesktopWindow(), &rc); swap_chain_desc_size = { rc.right, rc.bottom }; info("Detect native desktop display mode {}x{}", rc.right, rc.bottom); } } void DiligentMassageCallback(DEBUG_MESSAGE_SEVERITY Severity, const Char* Message, const char* Function, const char* File, int Line) { switch (Severity) { case DEBUG_MESSAGE_SEVERITY::DEBUG_MESSAGE_SEVERITY_INFO: info("DiligentEngine: {}", Message); return; case DEBUG_MESSAGE_SEVERITY::DEBUG_MESSAGE_SEVERITY_WARNING: be::utils::log::warn("DiligentEngine: {}", Message); return; case DEBUG_MESSAGE_SEVERITY::DEBUG_MESSAGE_SEVERITY_ERROR: be::utils::log::error("DiligentEngine: {}", Message); return; case DEBUG_MESSAGE_SEVERITY::DEBUG_MESSAGE_SEVERITY_FATAL_ERROR: be::utils::log::critical("DiligentEngine: {}", Message); return; default: return; }; } void D3D11Render::initialize() { info("{} initialization is started"s, name); info("{} : {} {}"s, lib_name, api_name, api_version); if (hwnd == nullptr) { // Forget to call preinitialize (HWND, math::float2)? core::FatalError fe("D3D11Render.cpp", 62, be::core::Error::Type::GRAPHICS, "Window handle is invalid"); fe.finalize(); } auto GetEngineFactoryD3D11 = LoadGraphicsEngineD3D11(); pFactoryD3D11 = GetEngineFactoryD3D11(); // SetDebugMessageCallback(DebugMessageCallback); #ifdef BE_DEBUG EngineCI.DebugMessageCallback = DiligentMassageCallback; EngineCI.DebugFlags |= D3D11_DEBUG_FLAG_CREATE_DEBUG_DEVICE; #endif pFactoryD3D11->CreateDeviceAndContextsD3D11(EngineCI, &device, &immediate_context); SwapChainDesc SCDesc; SCDesc.BufferCount = 2; SCDesc.Width = swap_chain_desc_size.value().x; SCDesc.Height = swap_chain_desc_size.value().y; SCDesc.ColorBufferFormat = texture_format; SCDesc.DepthBufferFormat = TEX_FORMAT_D32_FLOAT; SCDesc.Usage = SWAP_CHAIN_USAGE_RENDER_TARGET; SCDesc.PreTransform = SURFACE_TRANSFORM_OPTIMAL; SCDesc.DefaultDepthValue = 1.0f; SCDesc.DefaultStencilValue = 0; SCDesc.IsPrimary = True; pFactoryD3D11->CreateSwapChainD3D11(device, immediate_context, SCDesc, { }, Win32NativeWindow{ hwnd }, &swap_chain); getCaps(); getDeviceCaps(); state = State::INITIALIZED; info("{} is initialized"s, name); } void D3D11Render::finalize() { if (state == State::INITIALIZED) { if (pRTV) { pRTV = nullptr; } if (pDSV) { pDSV = nullptr; } if (pipeline_state) { pipeline_state->Release(); pipeline_state = nullptr; } if (immediate_context) { immediate_context = nullptr; } if (device) { device->Release(); device = nullptr; } swap_chain->SetWindowedMode(); if (swap_chain) { swap_chain->Release(); swap_chain = nullptr; } info("{} is finalized"s, name); } } D3D11Render::~D3D11Render() { // In order to reset render and keep D3D11 loaded. if (pFactoryD3D11) { pFactoryD3D11->Release(); pFactoryD3D11 = nullptr; } } void D3D11Render::present(const bool& vsync) { swap_chain->Present(vsync ? 1u : 0u); } void D3D11Render::render(ITextureView* ms_color_rtv, ITextureView* ms_depth_dsv) { if ((ms_color_rtv != nullptr) && (ms_depth_dsv != nullptr)) { // Set off-screen multi-sampled render target and depth-stencil buffer pRTV = ms_color_rtv; pDSV = ms_depth_dsv; } else { // Render directly to the current swap chain back buffer. pRTV = swap_chain->GetCurrentBackBufferRTV(); pDSV = swap_chain->GetDepthBufferDSV(); } immediate_context->SetRenderTargets(1u, &pRTV, pDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); immediate_context->ClearRenderTarget(pRTV, clear_color, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); immediate_context->ClearDepthStencil(pDSV, CLEAR_DEPTH_FLAG, 1.f, 0u, RESOURCE_STATE_TRANSITION_MODE_TRANSITION); } void D3D11Render::reset() { this->finalize(); this->initialize(); info("{} {} {} is reset"s, lib_name, api_name, api_version); } void D3D11Render::setPipelineState() { immediate_context->SetPipelineState(pipeline_state); } void D3D11Render::resize(const math::int2& resolution) { if (swap_chain) swap_chain->Resize(static_cast<Diligent::Uint32>(resolution.x), static_cast<Diligent::Uint32>(resolution.y)); } void D3D11Render::setWindowed() { swap_chain->SetWindowedMode(); } void D3D11Render::setFullScreen(const math::int2& resolution) { DisplayModeAttribs dma; memset(&dma, 0, sizeof(DisplayModeAttribs)); dma.Width = resolution.x; dma.Height = resolution.y; dma.RefreshRateNumerator = 60; dma.RefreshRateDenominator = 1; dma.Format = swap_chain->GetDesc().ColorBufferFormat; dma.Scaling = SCALING_MODE::SCALING_MODE_UNSPECIFIED; dma.ScanlineOrder = SCANLINE_ORDER::SCANLINE_ORDER_UNSPECIFIED; assert(m_DisplayModes.size() != 0); for (auto& mode : m_DisplayModes) { if ((mode.Width == dma.Width) && (mode.Height == dma.Height) && (mode.Format == dma.Format)) { current_dma = mode; swap_chain->SetFullscreenMode(current_dma); uint x = current_dma.Scaling; be::utils::log::debug("Apply display mode {}x{}", current_dma.Width, current_dma.Height, x); return; } } be::utils::log::warn("Can't apply display mode {}x{}", static_cast<uint>(dma.Width), static_cast<uint>(dma.Height)); RECT rc; ::GetWindowRect(::GetDesktopWindow(), &rc); dma.Width = rc.right; dma.Height = rc.bottom; info("Detect native desktop display mode {}x{}", dma.Width, dma.Height); current_dma = dma; swap_chain->SetFullscreenMode(current_dma); } void D3D11Render::createUniBuffer(IBuffer** uniform_buffer, const Diligent::Uint32& buffer_size) { CreateUniformBuffer(device, buffer_size, "Constants CB", uniform_buffer); } void D3D11Render::createSRB(IShaderResourceBinding** srb) { pipeline_state->CreateShaderResourceBinding(srb, true); } void D3D11Render::createPipelineState() { device->CreatePipelineState(PSOCreateInfo, &pipeline_state); } void D3D11Render::getStaVarByName(SHADER_TYPE shader_type, IBuffer* cbuffer, const char* buffer_name) { pipeline_state->GetStaticVariableByName(shader_type, buffer_name)->Set(cbuffer); } void D3D11Render::loadTexture(ITexture** Tex, const fs::path& file_name) { TextureLoadInfo loadInfo; loadInfo.IsSRGB = (texture_format == TEX_FORMAT_RGBA8_UNORM_SRGB ? True : False); CreateTextureFromFile(file_name.string().c_str(), loadInfo, device, Tex); } void D3D11Render::getCaps() { Uint32 NumAdapters = 0; pFactoryD3D11->EnumerateAdapters(EngineCI.MinimumFeatureLevel, NumAdapters, 0); vector<AdapterAttribs> Adapters(NumAdapters); if (NumAdapters > 0) pFactoryD3D11->EnumerateAdapters(EngineCI.MinimumFeatureLevel, NumAdapters, Adapters.data()); if (adapter_type == ADAPTER_TYPE_SOFTWARE) for (auto& adapter : Adapters) if (adapter.AdapterType == adapter_type) { info("Found software adapter: {}", adapter.Description); break; } m_AdapterAttribs = Adapters[m_AdapterId]; if (adapter_type != ADAPTER_TYPE_SOFTWARE) { Uint32 NumDisplayModes = 0; pFactoryD3D11->EnumerateDisplayModes(EngineCI.MinimumFeatureLevel, m_AdapterId, 0, texture_format, NumDisplayModes, nullptr); m_DisplayModes.resize(NumDisplayModes); pFactoryD3D11->EnumerateDisplayModes(EngineCI.MinimumFeatureLevel, m_AdapterId, 0, texture_format, NumDisplayModes, m_DisplayModes.data()); } EngineCI.AdapterId = m_AdapterId; assert(Adapters.size()); } void D3D11Render::getDeviceCaps() { adapter_type = device->GetDeviceCaps().AdaterType; if (adapter_type == ADAPTER_TYPE::ADAPTER_TYPE_HARDWARE) info("Hardware rendering is supported"s); auto aniso_supported = device->GetDeviceCaps().SamCaps.AnisotropicFilteringSupported; info("Anisotropic Filtering is {}supported"s, aniso_supported ? "" : "not "); auto tesselation_supported = device->GetDeviceCaps().Features.Tessellation; info("Tesselation is {}supported"s, tesselation_supported ? "" : "not "); for (auto& attr : Adapters) { info("Device ID: {}", attr.DeviceId); info("Device Outputs: {}", attr.NumOutputs); string vendor = ""s; if (attr.VendorId & 0x1002) vendor = "AMD"s; else if (attr.VendorId & 0x10DE) vendor = "Nvidia"s; else if ((attr.VendorId & 0x8086) || (attr.VendorId & 0x8087) || (attr.VendorId & 0x163C)) vendor = "Intel"s; else vendor = "Unknown"s; info("Device Vendor: {}", vendor); info("Device Brand: {}", attr.Description); auto shared_sys_mem = attr.SharedSystemMemory / 1024 / 1024; if (shared_sys_mem != 0) info("Device Shared System Memory: {} MB", shared_sys_mem); auto dedicated_sys_mem = attr.DedicatedSystemMemory / 1024 / 1024; if (dedicated_sys_mem != 0) info("Device Dedicated System Memory: {} MB", dedicated_sys_mem); auto dedicated_vid_mem = attr.DedicatedVideoMemory / 1024 / 1024; if (dedicated_vid_mem != 0) info("Device Dedicated Video Memory: {} MB", dedicated_vid_mem); } } }
#include <iostream> using namespace std; int main() { char num; cout << "문자형 입력(%%c) : "; cin >> num; cout << "문자로 출력(%%c) : " << num << endl; cout << "정수로 출력(%%c) : " << (int)(num - '0') << endl; return 0; }
#include<bits/stdc++.h> using namespace std; //https://www.geeksforgeeks.org/flatten-bst-to-sorted-list-increasing-order/ //Flatten BST to sorted list | Increasing order //Given a binary search tree, the task is to flatten it to a sorted list. Precisely, the value of each node must be lesser than the values of all the nodes at its right, and its left node must be NULL after flattening. We must do it in O(H) extra space where ‘H’ is the height of BST. // Approach: A simple approach will be to recreate the BST from its in-order traversal. This will take O(N) extra space were N is the number of node in BST. // To improve upon that, we will simulate in order traversal of a binary tree as follows: // Create a dummy node. // Create a variable called ‘prev’ and make it point to the dummy node. // Perform in-order traversal and at each step. // Set prev -> right = curr // Set prev -> left = NULL // Set prev = curr // This will improve the space complexity to O(H) in worst case as in-order traversal takes O(H) extra space. struct node { int data; struct node* left; struct node* right; }; typedef struct node Node; Node* newNode(int item) { Node* temp = new Node(); temp->data = item; temp->left = NULL; temp->right = NULL; return temp; } Node* insert(Node* root,int key) { Node* temp = newNode(key); if(root==NULL) { root=temp; return root; } Node* cur = root; Node* prev = NULL; while(cur!=NULL) { prev = cur; if(key <= cur->data) { cur=cur->left; } else { cur=cur->right; } } if(key <= prev->data) { prev->left = temp; } else { prev->right = temp; } return root; } void inorder(Node* root,Node*& prev) { if(root!=NULL) { inorder(root->left,prev); prev->left = NULL; prev->right = root; prev = root; inorder(root->right,prev); } } void printlist(Node* root) { Node* cur = root; while(cur!=NULL) { cout << cur->data << " "; cur = cur->right; } cout << endl; return ; } Node* flatten(Node* root) { Node* temp = newNode(-1);//dummy node Node* prev = temp; // we need sorted list so we will call inorder inorder(root,prev); //last node prev->left = NULL; prev->right = NULL; root = temp->right; // deleting dummy node at the start delete(temp); return root; } int main() { Node* root = newNode(5); root->left = newNode(3); root->right = newNode(7); root->left->left = newNode(2); root->left->right = newNode(4); root->right->left = newNode(6); root->right->right = newNode(8); printlist(flatten(root)); return 0; }
#include "ResourcesSystem.h" #include "PhysicsSystem.h" ResourcesSystem::ResourcesSystem(PhysicsSystem* physicsSystem) { this->ModelShader=new Shader("Game Resources/Shaders/ModelsVertexShader.glsl", "Game Resources/Shaders/ModelsFragmentShader.glsl"); this->lightingShader=new Shader("Game Resources/Shaders/LightVertexShader.glsl", "Game Resources/Shaders/LightFragmentShader.glsl"); models=new Model*[numOfModels]; models[0]=new Model("Game Resources/Models/Others/Space/2dSpace.obj"); models[1]=new Model("Game Resources/Models/SpaceShips/MRX22 Recon Flyer/ModifiedReconFlyer.obj"); models[1]->setRigidBody(physicsSystem->addBox(15,5,5,5,0,0,1.0)); for (int i = 2; i <=6; i++) { models[i]=new Model("Game Resources/Models/Obstacles/Asteroid/ModifiedAstroid2.obj"); models[i]->setRigidBody(physicsSystem->addBox(5,5,5,0,0,0,1.0)); } for (int i = 7; i <=11; i++) { models[i]=new Model("Game Resources/Models/UFOs/ufo/ModifiedUfo.obj"); models[i]->setRigidBody(physicsSystem->addBox(5,5,5,0,0,0,1.0)); } /*Rest of models models[0]=new Model("Game Resources/Models/Others/Ocean/Ocean.obj"); models[5]=new Model("Game Resources/Models/SpaceShips/starcruiser military/Starcruiser military.obj"); models[4]=new Model("Game Resources/Models/SpaceShips/SpaceTrident/SpaceTrident.obj"); models[11]=new Model("Game Resources/Models/Obstacles/Missile/missile.obj"); models[12]=new Model("Game Resources/Models/Obstacles/Rock/rock.obj"); models[1]=new Model("Game Resources/Models/SpaceShips/Arc-170/obj 2/Arc170.obj"); models[2]=new Model("Game Resources/Models/SpaceShips/CombatShip/CombatShip.obj"); models[7]=new Model("Game Resources/Models/SpaceShips/X-17 Viper/X-17 Viper flying.obj"); models[8]=new Model("Game Resources/Models/UFOs/Flying Disk/flying Disk flying.obj"); models[13]=new Model("Game Resources/Models/Others/Moon/moon.obj"); */ } ResourcesSystem::~ResourcesSystem() { for(int i=0;i<numOfModels-1;i++) { delete models[i]; } delete models; delete ModelShader; delete lightingShader; }
// github.com/andy489 // https://leetcode.com/problems/kth-largest-element-in-an-array/ // Time: O(n) in expectation class Solution { public: int partition(vector<int> &nums, int l, int r) { int pivot = l + rand() % (r - l + 1); swap(nums[pivot], nums[r]); int i = l, j = l; for (; j <= r - 1; ++j) if (nums[j] > nums[r]) swap(nums[i++], nums[j]); swap(nums[i], nums[r]); return i; } int findKthLargest(vector<int>& nums, int k) { int l = 0, r = nums.size() - 1; while (l <= r) { int pos = partition(nums, l, r); if (pos == k-1) return nums[pos]; pos < k-1 ? l = pos + 1 : r = pos - 1; } return INT_MAX; } };
#include "FS.h" #include "SD.h" #include "SPI.h" #include <Update.h> #include <BLEDevice.h> #include <BLEServer.h> #include <BLEUtils.h> #include <BLE2902.h> BLEServer *pServer = NULL; BLECharacteristic * pTxCharacteristic; BLECharacteristic * pOtaControlCharacteristic; bool deviceConnected = false; bool oldDeviceConnected = false; uint8_t txValue = 0; #define SERVICE_UUID "0000FF00-0000-1000-8000-00805f9b34fb" // UART service UUID #define CHARACTERISTIC_UUID_RX "0000FF01-0000-1000-8000-00805f9b34fb" // 데이터 쓰는것 #define CHARACTERISTIC_UUID_TX "0000FF02-0000-1000-8000-00805f9b34fb" #define CHARACTERISTIC_UUID_OTA_CONTROL "0000FF03-0000-1000-8000-00805f9b34fb" // 총 버퍼 컨트롤용 uint8_t bleFileBuff[1024] = {0x00,}; bool isReceived = false; int received_counter = 0; bool receivedIndicator = false; bool isPsramSetting = false; int n_elements = 0; int n_chunk_length = 0; uint8_t *int_array ; int buff_counter = 0; int chunk_counter = 0; // perform the actual update from a given stream void performUpdateV2(uint8_t * datas, size_t updateSize) { Serial.print(">>> performUpdate updateSize: "); Serial.println(updateSize); if (Update.begin(updateSize)) { size_t written = Update.write(datas, updateSize ); Serial.print(">>> performUpdate written: "); Serial.println(written); if (written == updateSize) { Serial.println("Written : " + String(written) + " successfully"); } else { Serial.println("Written only : " + String(written) + "/" + String(updateSize) + ". Retry?"); } if (Update.end()) { Serial.println("OTA done!"); if (Update.isFinished()) { Serial.println("Update successfully completed. Rebooting."); } else { Serial.println("Update not finished? Something went wrong!"); } } else { Serial.println("Error Occurred. Error #: " + String(Update.getError())); } } else { Serial.println("Not enough space to begin OTA"); } } void listDir(fs::FS &fs, const char * dirname, uint8_t levels) { Serial.printf("Listing directory: %s\n", dirname); File root = fs.open(dirname); if (!root) { Serial.println("Failed to open directory"); return; } if (!root.isDirectory()) { Serial.println("Not a directory"); return; } File file = root.openNextFile(); while (file) { if (file.isDirectory()) { Serial.print(" DIR : "); Serial.println(file.name()); if (levels) { listDir(fs, file.path(), levels - 1); } } else { Serial.print(" FILE: "); Serial.print(file.name()); Serial.print(" SIZE: "); Serial.println(file.size()); } file = root.openNextFile(); } } void deleteFile(fs::FS &fs, const char * path) { Serial.printf("Deleting file: %s\n", path); if (fs.exists(path)) { Serial.printf("Deleting exists file: %s\n", path); if (fs.remove(path)) { Serial.println("File deleted"); } else { Serial.println("Delete failed"); } } } void appendFile(fs::FS &fs, const char * path, const char * message) { Serial.printf("Appending to file: %s\n", path); File file = fs.open(path, FILE_APPEND); if (!file) { Serial.println("Failed to open file for appending"); return; } if (file.print(message)) { Serial.println("Message appended"); } else { Serial.println("Append failed"); } file.close(); } void appendFileV2(fs::FS &fs, const char * path) { Serial.printf("Appending to file: %s\n", path); File file = fs.open(path, FILE_APPEND); if (!file) { Serial.println("Failed to open file for appending"); return; } file.write(int_array, n_elements); Serial.printf("Done Append to file: %s\n", path); // for (int i = 0; i < n_elements; i++) { // Serial.print("index: "); // Serial.print(i); // Serial.print("->"); // Serial.print(int_array[i]); // Serial.print(" "); // // Serial.println(file.write(int_array[i])); // // } file.close(); } class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { deviceConnected = false; } }; class MyCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { std::string rxValue = pCharacteristic->getValue(); if (rxValue.length() > 0) { Serial.println(rxValue.length()); // Serial.println("*********"); // Serial.print("Received Value: "); for (int i = 0; i < rxValue.length(); i++) { bleFileBuff[i] = (uint8_t)rxValue[i]; // Serial.print(rxValue[i]); received_counter = received_counter + 1; } Serial.print(">>> received_counter: "); Serial.println(received_counter); if (received_counter == 512) { Serial.println("received_counter is 512"); isReceived = true; } else { Serial.print(">>> chunk_counter: "); Serial.println(chunk_counter); if (chunk_counter == n_chunk_length - 1) { isReceived = true; } } // Serial.println(); // Serial.println("*********"); } } }; class OtaControlCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { std::string rxValue = pCharacteristic->getValue(); if (rxValue.length() > 0) { Serial.println("OtaControlCallbacks *********"); for (int i = 0; i < rxValue.length(); i++) { Serial.print(rxValue[i]); } n_elements = ((uint8_t)rxValue[0] << 24) & 0xFF000000 | ((uint8_t)rxValue[1] << 16) & 0x00FF0000 | ((uint8_t)rxValue[2] << 8) & 0x0000FF00 | ((uint8_t)rxValue[3]) & 0x000000FF; n_chunk_length = ((uint8_t)rxValue[4] << 24) & 0xFF000000 | ((uint8_t)rxValue[5] << 16) & 0x00FF0000 | ((uint8_t)rxValue[6] << 8) & 0x0000FF00 | ((uint8_t)rxValue[7]) & 0x000000FF; Serial.print(">>> n_chunk_length:: "); Serial.println(n_chunk_length); Serial.println(); isPsramSetting = true; } } }; void setup() { Serial.begin(115200); pinMode(5, OUTPUT); if (!SD.begin(4)) { Serial.println("Card Mount Failed"); return; } uint8_t cardType = SD.cardType(); if (cardType == CARD_NONE) { Serial.println("No SD card attached"); return; } Serial.print("SD Card Type: "); if (cardType == CARD_MMC) { Serial.println("MMC"); } else if (cardType == CARD_SD) { Serial.println("SDSC"); } else if (cardType == CARD_SDHC) { Serial.println("SDHC"); } else { Serial.println("UNKNOWN"); } uint64_t cardSize = SD.cardSize() / (1024 * 1024); Serial.printf("SD Card Size: %lluMB\n", cardSize); listDir(SD, "/", 0); deleteFile(SD, "/update.bin"); // Create the BLE Device BLEDevice::init("UART Service"); // Create the BLE Server pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); // Create the BLE Service BLEService *pService = pServer->createService(SERVICE_UUID); // Create a BLE Characteristic pTxCharacteristic = pService->createCharacteristic( CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY ); pTxCharacteristic->addDescriptor(new BLE2902()); BLECharacteristic * pRxCharacteristic = pService->createCharacteristic( CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE ); pRxCharacteristic->setCallbacks(new MyCallbacks()); pOtaControlCharacteristic = pService->createCharacteristic( CHARACTERISTIC_UUID_OTA_CONTROL, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ ); pOtaControlCharacteristic->setCallbacks(new OtaControlCallbacks()); // Start the service pService->start(); // Start advertising pServer->getAdvertising()->start(); Serial.println("Waiting a client connection to notify..."); } void loop() { if (deviceConnected) { // pTxCharacteristic->setValue(&txValue, 1); // pTxCharacteristic->notify(); // txValue++; if (isReceived) { Serial.println("*********"); Serial.print("Received Value: "); if (received_counter == 512) { for (int i = 0; i < 512; i++) { Serial.print(bleFileBuff[i], HEX); Serial.print(" "); int_array[buff_counter] = bleFileBuff[i]; buff_counter++; } Serial.println(); Serial.print("buff_counter: "); Serial.print(buff_counter); Serial.println(" *********"); receivedIndicator = !receivedIndicator; digitalWrite(5, receivedIndicator); chunk_counter++; pTxCharacteristic->setValue(chunk_counter); pTxCharacteristic->notify(); if (buff_counter == n_elements) { Serial.println(">>>>>>>>>>>>> Same? >>>>>>>>>>>>>>>>>>>>"); } received_counter = 0; } else { if (chunk_counter == n_chunk_length - 1) { Serial.println(">>>>>>>>>>>>>>> is Last Packet"); for (int i = 0; i < received_counter; i++) { Serial.print(bleFileBuff[i], HEX); Serial.print(" "); int_array[buff_counter] = bleFileBuff[i]; buff_counter++; } Serial.println(); Serial.print("buff_counter: "); Serial.print(buff_counter); chunk_counter++; pTxCharacteristic->setValue(chunk_counter); pTxCharacteristic->notify(); appendFileV2(SD, "/update.bin"); performUpdateV2(int_array, n_elements); free(int_array); delay(1000); ESP.restart(); } } isReceived = false; } if (isPsramSetting) { Serial.print("n_elements: "); Serial.println(n_elements); int temp = n_elements + 1024; if (n_elements != 0) { //psram setting int_array = (uint8_t *) ps_malloc(temp * sizeof(uint8_t)); Serial.println("Set PSRAM ps_malloc"); } else { //psram free free(int_array); Serial.println("free PSRAM "); } isPsramSetting = false; } delay(10); // bluetooth stack will go into congestion, if too many packets are sent } // disconnecting if (!deviceConnected && oldDeviceConnected) { delay(500); // give the bluetooth stack the chance to get things ready pServer->startAdvertising(); // restart advertising Serial.println("start advertising"); oldDeviceConnected = deviceConnected; free(int_array); n_elements = 0; for (int i = 0; i < 1024; i++) { bleFileBuff[i] = 0x00; } isReceived = false; receivedIndicator = false; isPsramSetting = false; n_elements = 0; n_chunk_length = 0; buff_counter = 0; chunk_counter = 0; } // connecting if (deviceConnected && !oldDeviceConnected) { // do stuff here on connecting oldDeviceConnected = deviceConnected; } }
/* This file is part of the Razor AHRS Firmware */ void output_sensors_text(char raw_or_calibrated) { // Serial.print("#A-"); Serial.print(raw_or_calibrated); Serial.print('='); // Serial.print(accel[0]); Serial.print(","); // Serial.print(accel[1]); Serial.print(","); // Serial.print(accel[2]); Serial.println(); // // Serial.print("#M-"); Serial.print(raw_or_calibrated); Serial.print('='); // Serial.print(magnetom[0]); Serial.print(","); // Serial.print(magnetom[1]); Serial.print(","); // Serial.print(magnetom[2]); Serial.println(); // // Serial.print("#G-"); Serial.print(raw_or_calibrated); Serial.print('='); // Serial.print(gyro[0]); Serial.print(","); // Serial.print(gyro[1]); Serial.print(","); // Serial.print(gyro[2]); Serial.println(); if (dataFile) { dataFile.print(accel[0]*0.04205); dataFile.print(","); dataFile.print(accel[1]*0.04205); dataFile.print(","); dataFile.print(accel[2]*0.04205); dataFile.print(","); dataFile.print(magnetom[0]); dataFile.print(","); dataFile.print(magnetom[1]); dataFile.print(","); dataFile.print(magnetom[2]); dataFile.print(","); dataFile.print(gyro[0]); dataFile.print(","); dataFile.print(gyro[1]); dataFile.print(","); dataFile.print(gyro[2]); dataFile.print(","); } } void output_sensors() { compensate_sensor_errors(); output_sensors_text('C'); }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.Data.Html.3.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::Data::Html::IHtmlUtilities> : produce_base<D, Windows::Data::Html::IHtmlUtilities> { HRESULT __stdcall abi_ConvertToText(impl::abi_arg_in<hstring> html, impl::abi_arg_out<hstring> text) noexcept override { try { typename D::abi_guard guard(this->shim()); *text = detach_abi(this->shim().ConvertToText(*reinterpret_cast<const hstring *>(&html))); return S_OK; } catch (...) { *text = nullptr; return impl::to_hresult(); } } }; } namespace Windows::Data::Html { template <typename D> hstring impl_IHtmlUtilities<D>::ConvertToText(hstring_view html) const { hstring text; check_hresult(WINRT_SHIM(IHtmlUtilities)->abi_ConvertToText(get_abi(html), put_abi(text))); return text; } inline hstring HtmlUtilities::ConvertToText(hstring_view html) { return get_activation_factory<HtmlUtilities, IHtmlUtilities>().ConvertToText(html); } } } template<> struct std::hash<winrt::Windows::Data::Html::IHtmlUtilities> { size_t operator()(const winrt::Windows::Data::Html::IHtmlUtilities & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
//TabCtrlMouseLButtonDown.cpp //#include "Form.h" #include "TabCtrlMouseLButtonDown.h" #include "TabCtrl.h" #include "Note.h" #include "OtherNoteForm.h" #include "PageForm.h" #include "Page.h" #include "MemoForm.h" #include "Memo.h" #include "Caret.h" #include "SelectedBuffer.h" #include "Line.h" #include "HorizontalScroll.h" #include "VerticalScroll.h" TabCtrlMouseLButtonDown::TabCtrlMouseLButtonDown(TabCtrl *form) :MouseAction(form) { } TabCtrlMouseLButtonDown::TabCtrlMouseLButtonDown(const TabCtrlMouseLButtonDown& source) : MouseAction(source) { } TabCtrlMouseLButtonDown::~TabCtrlMouseLButtonDown() { } TabCtrlMouseLButtonDown& TabCtrlMouseLButtonDown::operator=(const TabCtrlMouseLButtonDown& source) { MouseAction::operator=(source); return *this; } #include "FindingForm.h" void TabCtrlMouseLButtonDown::OnMouseAction(UINT nFlags, CPoint point) { OtherNoteForm *otherNoteForm = (OtherNoteForm*)(CFrameWnd::FindWindow("OtherNote", NULL)); //1. 현재 페이지를 hide한다. PageForm *pageForm = otherNoteForm->GetPageForm(static_cast<Note*>(otherNoteForm->GetContents())->GetCurrent()); pageForm->ShowWindow(SW_HIDE); //2. 현재 클릭된 tab 위치를 구한다. Long index = static_cast<TabCtrl*>(this->form)->GetCurSel(); //3. 선택된 tab으로 변경한다. otherNoteForm->SelectTabItem(index); //4. 마지막 메모폼에 포커스 주기 pageForm = otherNoteForm->GetPageForm(index); if (pageForm->GetLength() > 0) { pageForm->GetMemoForm(pageForm->GetLength() - 1)->SetFocus(); } //4. 스크롤을 해당 페이지로 갱신한다. otherNoteForm->GetHorizontalScroll()->SetCurrent(index); otherNoteForm->GetVerticalScroll()->SetCurrent(index); //5. 선택된 tab에 표시하기 static_cast<TabCtrl*>(this->form)->DrawTabItem(); //6. 찾기 tab에 표시하기 1116 FindingForm *findingForm = otherNoteForm->GetFindingForm(); if (findingForm != NULL) { findingForm->CheckFindingTabItem(); } //7. note의 current를 변경 1121 static_cast<Note*>(otherNoteForm->GetContents())->SetCurrent(index); } void TabCtrlMouseLButtonDown::OnMouseAction(int x, int y) { } void TabCtrlMouseLButtonDown::OnMouseAction(UINT nSide, LPRECT lpRect) { }
#ifndef SPACEGENERATIONTEST_WRAPPER_H #define SPACEGENERATIONTEST_WRAPPER_H #define BOOST_BIND_NO_PLACEHOLDERS #include "Utilities/Definitions.h" #include "Utilities/DataSpaceConversion.h" #include "Utilities/CodeTimer.h" namespace UnitTesting { typedef typename CoordinateComponents::CartesianVolume<float> _type; typedef typename CoordinateComponents::CartesianVolume<float>::index _index ; using range = boost::multi_array_types::extent_range; class SpaceGenerationTest_Wrapper { public: SpaceGenerationTest_Wrapper(); virtual ~SpaceGenerationTest_Wrapper(); void operator()(); protected: private: size_t _dim = 512; Utilities::CodeTimer<boost::chrono::microseconds> _timer; std::shared_ptr<_type> _volume; void GenerateQuadrant(); void TestVolumeGeneration(); void TestVolumeGeneration_MultiThread(); void _CheckVolumeGeneration(std::shared_ptr<_type> &result); }; } #endif // SPACEGENERATIONTEST_WRAPPER_H
#include <stdlib.h> #include "stack.h" typedef struct NodeImplementation* Node; struct NodeImplementation { Node next; void* data; }; struct StackImplementation { Node head; int count; }; /** * Used to create a stack structure. * @return The newly created stack. */ Stack create_stack() { Stack new_stack = (Stack)smalloc(sizeof(struct StackImplementation)); new_stack->count = 0; new_stack->head = 0; return new_stack; } /** * Used to free all memory the supplied stack allocated. * @param stack The stack to be deleted. * @note delete structure, including the struct itself, but not the data! */ void delete_stack(Stack stack) { Node current = stack->head; while (current != 0) { Node to_delate = current; current = current->next; sfree(to_delate); } sfree(stack); } /** * Adds a new node with the supplied data to the top of the stack. * @param stack The stack onto which data has to be pushed. * @param data The data to be pushed. */ void push_stack(Stack stack, void *data) { Node new_node = (Node)smalloc(sizeof(struct NodeImplementation)); new_node->data = data; new_node->next = stack->head; stack->head = new_node; stack->count++; } /** * @param stack The stack which number of elements to be retrieved. * @return The number of items currently on the stack. */ int get_count(Stack stack) { return stack->count; } /** * Removes and returns the topmost item of the stack. * @param stack The stack from which to take. * @return The element returned from the stack. */ void* pop_stack(Stack stack) { if (get_count(stack) == 0) { return 0; } Node tmp = stack->head; stack->head = stack->head->next; stack->count--; void* data = tmp->data; sfree(tmp); return data; } /** * Returns the topmost item of the stack without removing it. * @param stack The stack from which to take. * @return The element returned from the stack.z */ void* peek_stack(Stack stack) { if (stack == 0) { return 0; } return stack->head->data; }
// // Compiler/AST/Type.h // // Brian T. Kelley <brian@briantkelley.com> // Copyright (c) 2007, 2008, 2011, 2012, 2014 Brian T. Kelley // // Chris Leahy <leahycm@gmail.com> // Copyright (c) 2007 Chris Leahy // // This software is licensed as described in the file LICENSE, which you should have received as part of this distribution. // #ifndef COMPILER_AST_TYPE_H #define COMPILER_AST_TYPE_H #include <cassert> #include <string> namespace Compiler { namespace AST { class Type { public: enum class Kind : std::uint8_t { Boolean, Integer32, Void, Derived }; static const std::string UndefinedName; public: Type() : Type(Type::Kind::Void) { } Type(Kind kind) : m_name(), m_kind(kind) { assert(kind != Kind::Derived); } Type(std::string name) : m_name(name), m_kind(Kind::Derived) { } Type(const Type& other) : m_name(other.m_name), m_kind(other.m_kind) { } Type(const Type&& other) : m_name(other.m_name), m_kind(other.m_kind) { } void operator=(const Type& rhs) { m_name = rhs.m_name; m_kind = rhs.m_kind; } void operator=(const Type&& rhs) { m_name = rhs.m_name; m_kind = rhs.m_kind; } public: // MARK: -- Source Information -- Kind GetKind() const { return m_kind; } std::string GetName() const { assert(m_kind == Kind::Derived); return m_name; } public: // MARK: -- Convenience Functions -- bool operator== (const Type& other) const { bool isEqual = other.GetKind() == GetKind(); if (isEqual && GetKind() == Type::Kind::Derived) { isEqual = other.GetName() == GetName(); } return isEqual; } bool operator!= (const Type& other) const { return !(*this == other); } private: std::string m_name; Kind m_kind; }; } /*namespace AST*/ } /*namespace Compiler*/ #endif // COMPILER_AST_TYPE_H
#pragma once #ifndef _BAKA_VECTOR_ #define _BAKA_VECTOR_ #include <cmath> #ifndef M_PI #define M_PI (3.14159265358979323846264f) #endif class Vector2D { public: float x, y; Vector2D() { x = y = 0; } Vector2D(const float _x, const float _y) : x(_x), y(_y) { } ~Vector2D() { } float Length() const { return sqrt(x * x + y * y); } float SqLength() const { return (x * x + y * y); } void operator =(const Vector2D & v) { x = v.x; y = v.y; } Vector2D operator -() const { return Vector2D(-x, -y); } Vector2D Normalise() const { const float len = Length(); return Vector2D(x / len, y / len); } Vector2D Perp() const { return Vector2D(-y, x); } Vector2D RePerp() const { return Vector2D(y, -x); } }; static const Vector2D ZERO(0.0f, 0.0f); static inline bool operator ==(const Vector2D & v1, const Vector2D & v2) { return (v1.x == v2.x && v1.y == v2.y); } static inline bool operator !=(const Vector2D & v1, const Vector2D & v2) { return (v1.x != v2.x || v1.y != v2.y); } static inline Vector2D operator +(const Vector2D & v1, const Vector2D & v2) { return Vector2D(v1.x + v2.x, v1.y + v2.y); } static inline Vector2D operator -(const Vector2D & v1, const Vector2D & v2) { return Vector2D(v1.x - v2.x, v1.y - v2.y); } static inline Vector2D operator *(const Vector2D & v, float d) { return Vector2D(v.x * d, v.y * d); } /** perp| 1 2 | = | -2 1 | */ static inline Vector2D perp(const Vector2D & v) { return Vector2D(-v.y, v.x); } /** perp| 1 2 | = | 2 -1 | */ static inline Vector2D rperp(const Vector2D & v) { return Vector2D(v.y, -v.x); } static inline float Dot(const Vector2D & v1, const Vector2D & v2) { return (v1.x * v2.x + v1.y * v2.y); } /** * This technique (ie rotate one vector anti-clockwise * by 90 degrees and take the dot product between both vectors) * is known as the 2D cross product. * Этот метод (т.е. повернуть один вектор против часовой * стрелки на 90 градусов и взять скалярное произведение между * двумя векторами) известен как 2D cross product. */ static inline float Cross(const Vector2D & v1, const Vector2D & v2) { return Dot(v1, rperp(v2)); } /** * проэкция вектора v1 на v2 */ static inline Vector2D Projection(const Vector2D & v1, const Vector2D & v2) { return v2 * (Dot(v1, v2) / Dot(v2, v2)); } /** * p'x = cos(a) * (px) - sin(a) * (py) * p'y = sin(a) * (px) + cos(a) * (py) */ static inline Vector2D RotateOnAngle(const Vector2D & v1, float a) { return Vector2D( v1.x * cos(a) - v1.y * sin(a), v1.x * sin(a) + v1.y * cos(a) ); } #endif
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<bool> vb; typedef vector<vb> vvb; typedef set<int> si; typedef map<string, int> msi; typedef greater<int> gt; typedef priority_queue<int, vector<int>, gt> minq; typedef long long ll; const ll INF = 1e18L + 1; //clang++ -std=c++11 -stdlib=libc++ ll d(ll n) { return 1 + floor(log10(n)); } int main() { int a,b; ll x; cin>>a>>b>>x; ll ans=0; ll h=1e9+1, l=0; while (h-l>1) { ans = (l+h) /2; if ((a*ans+b*d(ans)) <= x) l=ans; else h=ans; } ans = min(ans, (ll)1e9); cout << l << endl; return 0; }
/** * \file linebufistream.hpp * \date Feb 13, 2016 */ #ifndef PCSH_LINEBUFISTREAM_HPP #define PCSH_LINEBUFISTREAM_HPP #include <cstdlib> #include <string> #if defined(_WIN32) # define EOT_CHAR_DEF '\x26' # define EOT_CHAR_UNIX_DEF '\x04' #else # define EOT_CHAR_DEF '\x04' #endif namespace pcsh { namespace detail { class linebuff : public std::streambuf { private: std::istream& istrm_; std::string buffer_; bool eos_; bool check_eot_; using traits = std::char_traits<char>; static const int EOT_CHAR = EOT_CHAR_DEF; public: linebuff(std::istream& strm, bool checkeot) : istrm_(strm), buffer_(), eos_(false), check_eot_(checkeot) { istrm_.rdbuf()->pubsetbuf(0, 0); buffer_.reserve(120); } int underflow() { auto gp = gptr(); auto ep = egptr(); if (gp < ep) { return traits::to_int_type(*gp); } if (gp == ep) { int c = EOF; if (eos_ || ((c = istrm_.peek()) == EOF)) { eos_ = true; setg(nullptr, nullptr, nullptr); return traits::eof(); } buffer_.resize(0); while (c != EOF) { if (c == '\r' || c == '\n') { istrm_.get(); if ((c == '\r') && (istrm_.peek() == '\n')) { istrm_.get(); } buffer_.push_back('\n'); break; } if (check_eot_ && ((c == EOT_CHAR) #if defined(_WIN32) || (c == EOT_CHAR_UNIX_DEF) #endif//defined(_WIN32) ) ) { eos_ = true; break; } buffer_.push_back(c); istrm_.get(); c = istrm_.peek(); } setg(&buffer_[0], &buffer_[0], &buffer_[buffer_.size()]); } return ((gp = gptr()) == egptr()) ? traits::eof() : traits::to_int_type(*gp); } }; }// namespace detail class linebuff_istream : public std::istream { private: detail::linebuff buff_; public: linebuff_istream(std::istream& parent, bool checkEOT = true) : std::istream(&buff_), buff_(parent, checkEOT) { } }; }//namespace pcsh #endif/*PCSH_LINEBUFISTREAM_HPP*/
#include "CommonHeader.h" using namespace std; LivingObject::LivingObject(int aMaxHealth, Scene * apScene, std::string aName, Vector3 aPos, Vector3 aRot, Vector3 aScale, Mesh * apMesh, ShaderProgram * apShader, GLuint aTexture, vec2 aUVScale, vec2 aUVOffset, const char * aCameraName, unsigned int aDrawRenderOrder) : GameObject(aCameraName, aDrawRenderOrder), m_alive(true), m_collisionDamage(0), m_immortal(false), m_destroyOnCollision(false), m_destroyOnCollisionWithNotLivingObjects(false) { Init(aMaxHealth, apScene, aName, aPos, aRot, aScale, apMesh, apShader, aTexture, aUVScale, aUVOffset); } LivingObject::LivingObject(int aCollisionDamage, int aMaxHealth, Scene * apScene, std::string aName, Vector3 aPos, Vector3 aRot, Vector3 aScale, Mesh * apMesh, ShaderProgram * apShader, GLuint aTexture, vec2 aUVScale, vec2 aUVOffset, bool aImmortality, const char * aCameraName, unsigned int aDrawRenderOrder) : GameObject(aCameraName, aDrawRenderOrder), m_alive(true), m_collisionDamage(aCollisionDamage), m_immortal(aImmortality), m_destroyOnCollisionWithNotLivingObjects(false) { Init(aMaxHealth, apScene, aName, aPos, aRot, aScale, apMesh, apShader, aTexture, aUVScale, aUVOffset); } LivingObject::LivingObject(const char* aCameraName, unsigned int aDrawRenderOrder) : GameObject(aCameraName, aDrawRenderOrder), m_maxHealth(100), m_health(100), m_alive(true), m_collisionDamage(0), m_immortal(false), m_destroyOnCollisionWithNotLivingObjects(false) { } void LivingObject::Init(int aMaxHealth, Scene * apScene, std::string aName, Vector3 aPos, Vector3 aRot, Vector3 aScale, Mesh * apMesh, ShaderProgram * apShader, GLuint aTexture, vec2 aUVScale, vec2 aUVOffset) { GameObject::Init(apScene, aName, aPos, aRot, aScale, apMesh, apShader, aTexture, aUVScale, aUVOffset); m_maxHealth = aMaxHealth; m_health = aMaxHealth; } LivingObject::~LivingObject() { } void LivingObject::Update(double aDelta) { SetEnabled(m_alive); //if (m_alive == false) //{ // SetEnabled(false); // /* if (m_pPhysicsBody != nullptr) // { // m_pPhysicsBody->SetActive(false); // }*/ //} GameObject::Update(aDelta); } void LivingObject::ApplyDamage(int aDamage) { if (aDamage > 0)//If there is damage being applied { if (m_immortal == false)//If object can be damaged { m_health -= aDamage; } } else if (aDamage < 0)//If the damage is negative, heal the object { AddHealth(abs(aDamage));//Heal the object by the negative amount, converted to positive } if (m_health <= 0 && m_immortal==false)//If the health is 0 or less, AND the object is not immortal { OnDeath();//Set that the user died } } //Function to enable all the stats of an object, and set him at full health. void LivingObject::SpawnObject(vec3 aLocation) { ReplenishFullHealth();//This function will also set object as alive SetEnabled(true); SetPhysicsAndGameObjectPosition(aLocation); ResetPhysicsBody(); } void LivingObject::OnDeath() { m_alive = false; } //Helper function to simply add an amount to the current object health. It uses the function SetHealth in order to actually increase the value of the health. void LivingObject::AddHealth(int aHealth) { int currentHealth = GetHealth();//Get the object current Health SetHealth(currentHealth + aHealth);//Add to the current health the amount desired } //Function to set the total health of the object, it DOESN'T add to the current health. void LivingObject::SetHealth(int aHealth) { //Check that the health being set is less than the maximum health possible if (aHealth <= m_maxHealth) { m_health = aHealth;//Set health normally } else if (aHealth > m_maxHealth)//If the health is bigger than the maximum, set the health to be the maximum { m_health = m_maxHealth; } else if (aHealth <= 0)//if the health is 0 or less { m_health = 0;//Set the health to 0 OnDeath();//Call the onDeath function } //If the health is bigger than 0, ensure the object is alive if (m_health > 0) { m_alive = true; } } void LivingObject::ReplenishFullHealth() { m_health = m_maxHealth;//Set health back to maximum health m_alive = true;//Set object as alive } void LivingObject::Reset() { ReplenishFullHealth();//Replenish the object health completely GameObject::Reset(); } void LivingObject::BeginCollision(b2Fixture * aFixtureCollided, b2Fixture * aFixtureCollidedAgainst, GameObject * aObjectCollidedagainst, b2Vec2 aCollisionNormal, b2Vec2 aContactPoint, bool aTouching) { if (aTouching == true && aObjectCollidedagainst!=nullptr) { vec3 objectCollidedPosition = aObjectCollidedagainst->GetPosition(); float objectCollidedSizeDepth = aObjectCollidedagainst->GetZLength() / 2.0f; //Check if the objects are colliding, in the z depth. Done in here and presolve to account for sensors that don't call for presolve. if (DepthCollisionCheck(objectCollidedPosition.z + objectCollidedSizeDepth, objectCollidedPosition.z - objectCollidedSizeDepth)) { LivingObject* pLivingObject = dynamic_cast<LivingObject*>(aObjectCollidedagainst);//Check if the object collided with is a living object //Don't check if they are alive, otherwise the order in which begin collision is called may affect the object if (aObjectCollidedagainst->GetPhysicsBody()->IsActive() == true && m_pPhysicsBody->IsActive()==true)//Check that the other object is enabled { //if (GetAlive() == true)//Don't check if they are alive, otherwise the order in which begin collision is called may affect the object. if (pLivingObject != nullptr)//If it is a living object { pLivingObject->ApplyDamage(m_collisionDamage); } else//If it is NOT a living object { if (m_destroyOnCollisionWithNotLivingObjects == true) { OnDeath();//Kill this, living object. } } //If we are to destroy after a collision if (m_destroyOnCollision == true) { OnDeath(); } } } } }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "Windows.Devices.Gpio.2.h" WINRT_EXPORT namespace winrt { namespace Windows::Devices::Gpio { struct WINRT_EBO GpioChangeCounter : Windows::Devices::Gpio::IGpioChangeCounter { GpioChangeCounter(std::nullptr_t) noexcept {} GpioChangeCounter(const Windows::Devices::Gpio::GpioPin & pin); }; struct WINRT_EBO GpioChangeReader : Windows::Devices::Gpio::IGpioChangeReader { GpioChangeReader(std::nullptr_t) noexcept {} GpioChangeReader(const Windows::Devices::Gpio::GpioPin & pin); GpioChangeReader(const Windows::Devices::Gpio::GpioPin & pin, int32_t minCapacity); }; struct WINRT_EBO GpioController : Windows::Devices::Gpio::IGpioController { GpioController(std::nullptr_t) noexcept {} static Windows::Devices::Gpio::GpioController GetDefault(); static Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Gpio::GpioController>> GetControllersAsync(const Windows::Devices::Gpio::Provider::IGpioProvider & provider); static Windows::Foundation::IAsyncOperation<Windows::Devices::Gpio::GpioController> GetDefaultAsync(); }; struct WINRT_EBO GpioPin : Windows::Devices::Gpio::IGpioPin { GpioPin(std::nullptr_t) noexcept {} }; struct WINRT_EBO GpioPinValueChangedEventArgs : Windows::Devices::Gpio::IGpioPinValueChangedEventArgs { GpioPinValueChangedEventArgs(std::nullptr_t) noexcept {} }; } }
#ifndef TINYXML_INCLUDED #define TINYXML_INCLUDED #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4530) #pragma warning(disable:4786) #endif #include<ctype.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<assert.h> #if defined(_DEBUG)&&!defined(DEBUG) #define DEBUG #endif #ifdef TIXML_USE_STL #include<string> #include<iostream> #include<sstream> #define TIXML_STRING std::string #else #include "tinystr.h" #define TIXML_STRING TiXmlString #endif #define TIXML_SAFE #ifdef TIXML_SAFE #if defined(_MSC_VER)&&(_MSC_VER>=1400) #define TIXML_SNPRINTF _snprintf_s #define TIXML_SNSCANF _snscanf_s #elif defined(_MSC_VER)&&(_MSC_VER>=1200) #define TIXML_SNPRINTF _snprintf #define TIXML_SNSCANF _snscanf #elif defined(__GNUC__)&&(__GNUC__>=3) #define TIXML_SNPRINTF snprintf #define TIXML_SNSCANF snscanf #endif #endif class TiXmlDocument; class TiXmlElement; class TiXmlComment; class TiXmlUnknown; class TiXmlAttribute; class TiXmlText; class TiXmlDeclaration; class TiXmlParsingData; const int TIXML_MAJOR_VERSION=2; const int TIXML_MINOR_VERSION=5; const int TIXML_PATCH_VERSION=2; struct TiXmlCursor { TiXmlCursor(){Clear();} void Clear(){row=col=-1;} int row; int col; }; class TiXmlVisitor { public: virtual~TiXmlVisitor(){} virtual bool VisitEnter(const TiXmlDocument&){return true;} virtual bool VisitExit(const TiXmlDocument&){return true;} virtual bool VisitEnter(const TiXmlElement&,const TiXmlAttribute*){return true;} virtual bool VisitExit(const TiXmlElement&){return true;} virtual bool Visit(const TiXmlDeclaration&){return true;} virtual bool Visit(const TiXmlText&){return true;} virtual bool Visit(const TiXmlComment&){return true;} virtual bool Visit(const TiXmlUnknown&){return true;} }; enum { TIXML_SUCCESS, TIXML_NO_ATTRIBUTE, TIXML_WRONG_TYPE }; enum TiXmlEncoding { TIXML_ENCODING_UNKNOWN, TIXML_ENCODING_UTF8, TIXML_ENCODING_LEGACY }; const TiXmlEncoding TIXML_DEFAULT_ENCODING=TIXML_ENCODING_UNKNOWN; class TiXmlBase { friend class TiXmlNode; friend class TiXmlElement; friend class TiXmlDocument; public: TiXmlBase():userData(0){} virtual~TiXmlBase(){} virtual void Print(FILE*cfile,int depth)const=0; static void SetCondenseWhiteSpace(bool condense){condenseWhiteSpace=condense;} static bool IsWhiteSpaceCondensed(){return condenseWhiteSpace;} int Row()const{return location.row+1;} int Column()const{return location.col+1;} void SetUserData(void*user){userData=user;} void*GetUserData(){return userData;} const void*GetUserData()const{return userData;} static const int utf8ByteTable[256]; virtual const char*Parse(const char*p, TiXmlParsingData*data, TiXmlEncoding encoding)=0; enum { TIXML_NO_ERROR=0, TIXML_ERROR, TIXML_ERROR_OPENING_FILE, TIXML_ERROR_OUT_OF_MEMORY, TIXML_ERROR_PARSING_ELEMENT, TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, TIXML_ERROR_READING_ELEMENT_VALUE, TIXML_ERROR_READING_ATTRIBUTES, TIXML_ERROR_PARSING_EMPTY, TIXML_ERROR_READING_END_TAG, TIXML_ERROR_PARSING_UNKNOWN, TIXML_ERROR_PARSING_COMMENT, TIXML_ERROR_PARSING_DECLARATION, TIXML_ERROR_DOCUMENT_EMPTY, TIXML_ERROR_EMBEDDED_NULL, TIXML_ERROR_PARSING_CDATA, TIXML_ERROR_DOCUMENT_TOP_ONLY, TIXML_ERROR_STRING_COUNT }; protected: static const char*SkipWhiteSpace(const char*,TiXmlEncoding encoding); inline static bool IsWhiteSpace(char c) { return(isspace((unsigned char)c)||c=='\n'||c=='\r'); } inline static bool IsWhiteSpace(int c) { if(c<256) return IsWhiteSpace((char)c); return false; } #ifdef TIXML_USE_STL static bool StreamWhiteSpace(std::istream*in,TIXML_STRING*tag); static bool StreamTo(std::istream*in,int character,TIXML_STRING*tag); #endif static const char*ReadName(const char*p,TIXML_STRING*name,TiXmlEncoding encoding); static const char*ReadText(const char*in, TIXML_STRING*text, bool ignoreWhiteSpace, const char*endTag, bool ignoreCase, TiXmlEncoding encoding); static const char*GetEntity(const char*in,char*value,int*length,TiXmlEncoding encoding); inline static const char*GetChar(const char*p,char*_value,int*length,TiXmlEncoding encoding) { assert(p); if(encoding==TIXML_ENCODING_UTF8) { *length=utf8ByteTable[*((const unsigned char*)p)]; assert(*length>=0&&*length<5); } else { *length=1; } if(*length==1) { if(*p=='&') return GetEntity(p,_value,length,encoding); *_value=*p; return p+1; } else if(*length) { for(int i=0;p[i]&&i<*length;++i){ _value[i]=p[i]; } return p+(*length); } else { return 0; } } static void PutString(const TIXML_STRING&str,TIXML_STRING*out); static bool StringEqual(const char*p, const char*endTag, bool ignoreCase, TiXmlEncoding encoding); static const char*errorString[TIXML_ERROR_STRING_COUNT]; TiXmlCursor location; void*userData; static int IsAlpha(unsigned char anyByte,TiXmlEncoding encoding); static int IsAlphaNum(unsigned char anyByte,TiXmlEncoding encoding); inline static int ToLower(int v,TiXmlEncoding encoding) { if(encoding==TIXML_ENCODING_UTF8) { if(v<128)return tolower(v); return v; } else { return tolower(v); } } static void ConvertUTF32ToUTF8(unsigned long input,char*output,int*length); private: TiXmlBase(const TiXmlBase&); void operator=(const TiXmlBase&base); struct Entity { const char*str; unsigned int strLength; char chr; }; enum { NUM_ENTITY=5, MAX_ENTITY_LENGTH=6 }; static Entity entity[NUM_ENTITY]; static bool condenseWhiteSpace; }; class TiXmlNode:public TiXmlBase { friend class TiXmlDocument; friend class TiXmlElement; public: #ifdef TIXML_USE_STL friend std::istream&operator>>(std::istream&in,TiXmlNode&base); friend std::ostream&operator<<(std::ostream&out,const TiXmlNode&base); friend std::string&operator<<(std::string&out,const TiXmlNode&base); #endif enum NodeType { DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, DECLARATION, TYPECOUNT }; virtual~TiXmlNode(); const char*Value()const{return value.c_str();} #ifdef TIXML_USE_STL const std::string&ValueStr()const{return value;} #endif void SetValue(const char*_value){value=_value;} #ifdef TIXML_USE_STL void SetValue(const std::string&_value){value=_value;} #endif void Clear(); TiXmlNode*Parent(){return parent;} const TiXmlNode*Parent()const{return parent;} const TiXmlNode*FirstChild()const{return firstChild;} TiXmlNode*FirstChild(){return firstChild;} const TiXmlNode*FirstChild(const char*value)const; TiXmlNode*FirstChild(const char*_value){ return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->FirstChild(_value)); } const TiXmlNode*LastChild()const{return lastChild;} TiXmlNode*LastChild(){return lastChild;} const TiXmlNode*LastChild(const char*value)const; TiXmlNode*LastChild(const char*_value){ return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->LastChild(_value)); } #ifdef TIXML_USE_STL const TiXmlNode*FirstChild(const std::string&_value)const{return FirstChild(_value.c_str());} TiXmlNode*FirstChild(const std::string&_value){return FirstChild(_value.c_str());} const TiXmlNode*LastChild(const std::string&_value)const{return LastChild(_value.c_str());} TiXmlNode*LastChild(const std::string&_value){return LastChild(_value.c_str());} #endif const TiXmlNode*IterateChildren(const TiXmlNode*previous)const; TiXmlNode*IterateChildren(const TiXmlNode*previous){ return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->IterateChildren(previous)); } const TiXmlNode*IterateChildren(const char*value,const TiXmlNode*previous)const; TiXmlNode*IterateChildren(const char*_value,const TiXmlNode*previous){ return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->IterateChildren(_value,previous)); } #ifdef TIXML_USE_STL const TiXmlNode*IterateChildren(const std::string&_value,const TiXmlNode*previous)const{return IterateChildren(_value.c_str(),previous);} TiXmlNode*IterateChildren(const std::string&_value,const TiXmlNode*previous){return IterateChildren(_value.c_str(),previous);} #endif TiXmlNode*InsertEndChild(const TiXmlNode&addThis); TiXmlNode*LinkEndChild(TiXmlNode*addThis); TiXmlNode*InsertBeforeChild(TiXmlNode*beforeThis,const TiXmlNode&addThis); TiXmlNode*InsertAfterChild(TiXmlNode*afterThis,const TiXmlNode&addThis); TiXmlNode*ReplaceChild(TiXmlNode*replaceThis,const TiXmlNode&withThis); bool RemoveChild(TiXmlNode*removeThis); const TiXmlNode*PreviousSibling()const{return prev;} TiXmlNode*PreviousSibling(){return prev;} const TiXmlNode*PreviousSibling(const char*)const; TiXmlNode*PreviousSibling(const char*_prev){ return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->PreviousSibling(_prev)); } #ifdef TIXML_USE_STL const TiXmlNode*PreviousSibling(const std::string&_value)const{return PreviousSibling(_value.c_str());} TiXmlNode*PreviousSibling(const std::string&_value){return PreviousSibling(_value.c_str());} const TiXmlNode*NextSibling(const std::string&_value)const{return NextSibling(_value.c_str());} TiXmlNode*NextSibling(const std::string&_value){return NextSibling(_value.c_str());} #endif const TiXmlNode*NextSibling()const{return next;} TiXmlNode*NextSibling(){return next;} const TiXmlNode*NextSibling(const char*)const; TiXmlNode*NextSibling(const char*_next){ return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->NextSibling(_next)); } const TiXmlElement*NextSiblingElement()const; TiXmlElement*NextSiblingElement(){ return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->NextSiblingElement()); } const TiXmlElement*NextSiblingElement(const char*)const; TiXmlElement*NextSiblingElement(const char*_next){ return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->NextSiblingElement(_next)); } #ifdef TIXML_USE_STL const TiXmlElement*NextSiblingElement(const std::string&_value)const{return NextSiblingElement(_value.c_str());} TiXmlElement*NextSiblingElement(const std::string&_value){return NextSiblingElement(_value.c_str());} #endif const TiXmlElement*FirstChildElement()const; TiXmlElement*FirstChildElement(){ return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->FirstChildElement()); } const TiXmlElement*FirstChildElement(const char*_value)const; TiXmlElement*FirstChildElement(const char*_value){ return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->FirstChildElement(_value)); } #ifdef TIXML_USE_STL const TiXmlElement*FirstChildElement(const std::string&_value)const{return FirstChildElement(_value.c_str());} TiXmlElement*FirstChildElement(const std::string&_value){return FirstChildElement(_value.c_str());} #endif int Type()const{return type;} const TiXmlDocument*GetDocument()const; TiXmlDocument*GetDocument(){ return const_cast<TiXmlDocument*>((const_cast<const TiXmlNode*>(this))->GetDocument()); } bool NoChildren()const{return!firstChild;} virtual const TiXmlDocument*ToDocument()const{return 0;} virtual const TiXmlElement*ToElement()const{return 0;} virtual const TiXmlComment*ToComment()const{return 0;} virtual const TiXmlUnknown*ToUnknown()const{return 0;} virtual const TiXmlText*ToText()const{return 0;} virtual const TiXmlDeclaration*ToDeclaration()const{return 0;} virtual TiXmlDocument*ToDocument(){return 0;} virtual TiXmlElement*ToElement(){return 0;} virtual TiXmlComment*ToComment(){return 0;} virtual TiXmlUnknown*ToUnknown(){return 0;} virtual TiXmlText*ToText(){return 0;} virtual TiXmlDeclaration*ToDeclaration(){return 0;} virtual TiXmlNode*Clone()const=0; virtual bool Accept(TiXmlVisitor*visitor)const=0; protected: TiXmlNode(NodeType _type); void CopyTo(TiXmlNode*target)const; #ifdef TIXML_USE_STL virtual void StreamIn(std::istream*in,TIXML_STRING*tag)=0; #endif TiXmlNode*Identify(const char*start,TiXmlEncoding encoding); TiXmlNode*parent; NodeType type; TiXmlNode*firstChild; TiXmlNode*lastChild; TIXML_STRING value; TiXmlNode*prev; TiXmlNode*next; private: TiXmlNode(const TiXmlNode&); void operator=(const TiXmlNode&base); }; class TiXmlAttribute:public TiXmlBase { friend class TiXmlAttributeSet; public: TiXmlAttribute():TiXmlBase() { document=0; prev=next=0; } #ifdef TIXML_USE_STL TiXmlAttribute(const std::string&_name,const std::string&_value) { name=_name; value=_value; document=0; prev=next=0; } #endif TiXmlAttribute(const char*_name,const char*_value) { name=_name; value=_value; document=0; prev=next=0; } const char*Name()const{return name.c_str();} const char*Value()const{return value.c_str();} #ifdef TIXML_USE_STL const std::string&ValueStr()const{return value;} #endif int IntValue()const; double DoubleValue()const; const TIXML_STRING&NameTStr()const{return name;} int QueryIntValue(int*_value)const; int QueryDoubleValue(double*_value)const; void SetName(const char*_name){name=_name;} void SetValue(const char*_value){value=_value;} void SetIntValue(int _value); void SetDoubleValue(double _value); #ifdef TIXML_USE_STL void SetName(const std::string&_name){name=_name;} void SetValue(const std::string&_value){value=_value;} #endif const TiXmlAttribute*Next()const; TiXmlAttribute*Next(){ return const_cast<TiXmlAttribute*>((const_cast<const TiXmlAttribute*>(this))->Next()); } const TiXmlAttribute*Previous()const; TiXmlAttribute*Previous(){ return const_cast<TiXmlAttribute*>((const_cast<const TiXmlAttribute*>(this))->Previous()); } bool operator==(const TiXmlAttribute&rhs)const{return rhs.name==name;} bool operator<(const TiXmlAttribute&rhs)const{return name<rhs.name;} bool operator>(const TiXmlAttribute&rhs)const{return name>rhs.name;} virtual const char*Parse(const char*p,TiXmlParsingData*data,TiXmlEncoding encoding); virtual void Print(FILE*cfile,int depth)const{ Print(cfile,depth,0); } void Print(FILE*cfile,int depth,TIXML_STRING*str)const; void SetDocument(TiXmlDocument*doc){document=doc;} private: TiXmlAttribute(const TiXmlAttribute&); void operator=(const TiXmlAttribute&base); TiXmlDocument*document; TIXML_STRING name; TIXML_STRING value; TiXmlAttribute*prev; TiXmlAttribute*next; }; class TiXmlAttributeSet { public: TiXmlAttributeSet(); ~TiXmlAttributeSet(); void Add(TiXmlAttribute*attribute); void Remove(TiXmlAttribute*attribute); const TiXmlAttribute*First()const{return(sentinel.next==&sentinel)?0:sentinel.next;} TiXmlAttribute*First(){return(sentinel.next==&sentinel)?0:sentinel.next;} const TiXmlAttribute*Last()const{return(sentinel.prev==&sentinel)?0:sentinel.prev;} TiXmlAttribute*Last(){return(sentinel.prev==&sentinel)?0:sentinel.prev;} const TiXmlAttribute*Find(const char*_name)const; TiXmlAttribute*Find(const char*_name){ return const_cast<TiXmlAttribute*>((const_cast<const TiXmlAttributeSet*>(this))->Find(_name)); } #ifdef TIXML_USE_STL const TiXmlAttribute*Find(const std::string&_name)const; TiXmlAttribute*Find(const std::string&_name){ return const_cast<TiXmlAttribute*>((const_cast<const TiXmlAttributeSet*>(this))->Find(_name)); } #endif private: TiXmlAttributeSet(const TiXmlAttributeSet&); void operator=(const TiXmlAttributeSet&); TiXmlAttribute sentinel; }; class TiXmlElement:public TiXmlNode { public: TiXmlElement(const char*in_value); #ifdef TIXML_USE_STL TiXmlElement(const std::string&_value); #endif TiXmlElement(const TiXmlElement&); void operator=(const TiXmlElement&base); virtual~TiXmlElement(); const char*Attribute(const char*name)const; const char*Attribute(const char*name,int*i)const; const char*Attribute(const char*name,double*d)const; int QueryIntAttribute(const char*name,int*_value)const; int QueryDoubleAttribute(const char*name,double*_value)const; int QueryFloatAttribute(const char*name,float*_value)const{ double d; int result=QueryDoubleAttribute(name,&d); if(result==TIXML_SUCCESS){ *_value=(float)d; } return result; } #ifdef TIXML_USE_STL template<typename T>int QueryValueAttribute(const std::string&name,T*outValue)const { const TiXmlAttribute*node=attributeSet.Find(name); if(!node) return TIXML_NO_ATTRIBUTE; std::stringstream sstream(node->ValueStr()); sstream>>*outValue; if(!sstream.fail()) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } #endif void SetAttribute(const char*name,const char*_value); #ifdef TIXML_USE_STL const std::string*Attribute(const std::string&name)const; const std::string*Attribute(const std::string&name,int*i)const; const std::string*Attribute(const std::string&name,double*d)const; int QueryIntAttribute(const std::string&name,int*_value)const; int QueryDoubleAttribute(const std::string&name,double*_value)const; void SetAttribute(const std::string&name,const std::string&_value); void SetAttribute(const std::string&name,int _value); #endif void SetAttribute(const char*name,int value); void SetDoubleAttribute(const char*name,double value); void RemoveAttribute(const char*name); #ifdef TIXML_USE_STL void RemoveAttribute(const std::string&name){RemoveAttribute(name.c_str());} #endif const TiXmlAttribute*FirstAttribute()const{return attributeSet.First();} TiXmlAttribute*FirstAttribute(){return attributeSet.First();} const TiXmlAttribute*LastAttribute()const{return attributeSet.Last();} TiXmlAttribute*LastAttribute(){return attributeSet.Last();} const char*GetText()const; virtual TiXmlNode*Clone()const; virtual void Print(FILE*cfile,int depth)const; virtual const char*Parse(const char*p,TiXmlParsingData*data,TiXmlEncoding encoding); virtual const TiXmlElement*ToElement()const{return this;} virtual TiXmlElement*ToElement(){return this;} virtual bool Accept(TiXmlVisitor*visitor)const; protected: void CopyTo(TiXmlElement*target)const; void ClearThis(); #ifdef TIXML_USE_STL virtual void StreamIn(std::istream*in,TIXML_STRING*tag); #endif const char*ReadValue(const char*in,TiXmlParsingData*prevData,TiXmlEncoding encoding); private: TiXmlAttributeSet attributeSet; }; class TiXmlComment:public TiXmlNode { public: TiXmlComment():TiXmlNode(TiXmlNode::COMMENT){} TiXmlComment(const char*_value):TiXmlNode(TiXmlNode::COMMENT){ SetValue(_value); } TiXmlComment(const TiXmlComment&); void operator=(const TiXmlComment&base); virtual~TiXmlComment(){} virtual TiXmlNode*Clone()const; virtual void Print(FILE*cfile,int depth)const; virtual const char*Parse(const char*p,TiXmlParsingData*data,TiXmlEncoding encoding); virtual const TiXmlComment*ToComment()const{return this;} virtual TiXmlComment*ToComment(){return this;} virtual bool Accept(TiXmlVisitor*visitor)const; protected: void CopyTo(TiXmlComment*target)const; #ifdef TIXML_USE_STL virtual void StreamIn(std::istream*in,TIXML_STRING*tag); #endif private: }; class TiXmlText:public TiXmlNode { friend class TiXmlElement; public: TiXmlText(const char*initValue):TiXmlNode(TiXmlNode::TEXT) { SetValue(initValue); cdata=false; } virtual~TiXmlText(){} #ifdef TIXML_USE_STL TiXmlText(const std::string&initValue):TiXmlNode(TiXmlNode::TEXT) { SetValue(initValue); cdata=false; } #endif TiXmlText(const TiXmlText&copy):TiXmlNode(TiXmlNode::TEXT){copy.CopyTo(this);} void operator=(const TiXmlText&base){base.CopyTo(this);} virtual void Print(FILE*cfile,int depth)const; bool CDATA()const{return cdata;} void SetCDATA(bool _cdata){cdata=_cdata;} virtual const char*Parse(const char*p,TiXmlParsingData*data,TiXmlEncoding encoding); virtual const TiXmlText*ToText()const{return this;} virtual TiXmlText*ToText(){return this;} virtual bool Accept(TiXmlVisitor*content)const; protected: virtual TiXmlNode*Clone()const; void CopyTo(TiXmlText*target)const; bool Blank()const; #ifdef TIXML_USE_STL virtual void StreamIn(std::istream*in,TIXML_STRING*tag); #endif private: bool cdata; }; class TiXmlDeclaration:public TiXmlNode { public: TiXmlDeclaration():TiXmlNode(TiXmlNode::DECLARATION){} #ifdef TIXML_USE_STL TiXmlDeclaration(const std::string&_version, const std::string&_encoding, const std::string&_standalone); #endif TiXmlDeclaration(const char*_version, const char*_encoding, const char*_standalone); TiXmlDeclaration(const TiXmlDeclaration&copy); void operator=(const TiXmlDeclaration&copy); virtual~TiXmlDeclaration(){} const char*Version()const{return version.c_str();} const char*Encoding()const{return encoding.c_str();} const char*Standalone()const{return standalone.c_str();} virtual TiXmlNode*Clone()const; virtual void Print(FILE*cfile,int depth,TIXML_STRING*str)const; virtual void Print(FILE*cfile,int depth)const{ Print(cfile,depth,0); } virtual const char*Parse(const char*p,TiXmlParsingData*data,TiXmlEncoding encoding); virtual const TiXmlDeclaration*ToDeclaration()const{return this;} virtual TiXmlDeclaration*ToDeclaration(){return this;} virtual bool Accept(TiXmlVisitor*visitor)const; protected: void CopyTo(TiXmlDeclaration*target)const; #ifdef TIXML_USE_STL virtual void StreamIn(std::istream*in,TIXML_STRING*tag); #endif private: TIXML_STRING version; TIXML_STRING encoding; TIXML_STRING standalone; }; class TiXmlUnknown:public TiXmlNode { public: TiXmlUnknown():TiXmlNode(TiXmlNode::UNKNOWN){} virtual~TiXmlUnknown(){} TiXmlUnknown(const TiXmlUnknown&copy):TiXmlNode(TiXmlNode::UNKNOWN){copy.CopyTo(this);} void operator=(const TiXmlUnknown&copy){copy.CopyTo(this);} virtual TiXmlNode*Clone()const; virtual void Print(FILE*cfile,int depth)const; virtual const char*Parse(const char*p,TiXmlParsingData*data,TiXmlEncoding encoding); virtual const TiXmlUnknown*ToUnknown()const{return this;} virtual TiXmlUnknown*ToUnknown(){return this;} virtual bool Accept(TiXmlVisitor*content)const; protected: void CopyTo(TiXmlUnknown*target)const; #ifdef TIXML_USE_STL virtual void StreamIn(std::istream*in,TIXML_STRING*tag); #endif private: }; class TiXmlDocument:public TiXmlNode { public: TiXmlDocument(); TiXmlDocument(const char*documentName); #ifdef TIXML_USE_STL TiXmlDocument(const std::string&documentName); #endif TiXmlDocument(const TiXmlDocument&copy); void operator=(const TiXmlDocument&copy); virtual~TiXmlDocument(){} bool LoadFile(TiXmlEncoding encoding=TIXML_DEFAULT_ENCODING); bool SaveFile()const; bool LoadFile(const char*filename,TiXmlEncoding encoding=TIXML_DEFAULT_ENCODING); bool SaveFile(const char*filename)const; bool LoadFile(FILE*,TiXmlEncoding encoding=TIXML_DEFAULT_ENCODING); bool SaveFile(FILE*)const; #ifdef TIXML_USE_STL bool LoadFile(const std::string&filename,TiXmlEncoding encoding=TIXML_DEFAULT_ENCODING) { return LoadFile(filename.c_str(),encoding); } bool SaveFile(const std::string&filename)const { return SaveFile(filename.c_str()); } #endif virtual const char*Parse(const char*p,TiXmlParsingData*data=0,TiXmlEncoding encoding=TIXML_DEFAULT_ENCODING); const TiXmlElement*RootElement()const{return FirstChildElement();} TiXmlElement*RootElement(){return FirstChildElement();} bool Error()const{return error;} const char*ErrorDesc()const{return errorDesc.c_str();} int ErrorId()const{return errorId;} int ErrorRow()const{return errorLocation.row+1;} int ErrorCol()const{return errorLocation.col+1;} void SetTabSize(int _tabsize){tabsize=_tabsize;} int TabSize()const{return tabsize;} void ClearError(){error=false; errorId=0; errorDesc=""; errorLocation.row=errorLocation.col=0; } void Print()const{Print(stdout,0);} virtual void Print(FILE*cfile,int depth=0)const; void SetError(int err,const char*errorLocation,TiXmlParsingData*prevData,TiXmlEncoding encoding); virtual const TiXmlDocument*ToDocument()const{return this;} virtual TiXmlDocument*ToDocument(){return this;} virtual bool Accept(TiXmlVisitor*content)const; protected: virtual TiXmlNode*Clone()const; #ifdef TIXML_USE_STL virtual void StreamIn(std::istream*in,TIXML_STRING*tag); #endif private: void CopyTo(TiXmlDocument*target)const; bool error; int errorId; TIXML_STRING errorDesc; int tabsize; TiXmlCursor errorLocation; bool useMicrosoftBOM; }; class TiXmlHandle { public: TiXmlHandle(TiXmlNode*_node){this->node=_node;} TiXmlHandle(const TiXmlHandle&ref){this->node=ref.node;} TiXmlHandle operator=(const TiXmlHandle&ref){this->node=ref.node;return*this;} TiXmlHandle FirstChild()const; TiXmlHandle FirstChild(const char*value)const; TiXmlHandle FirstChildElement()const; TiXmlHandle FirstChildElement(const char*value)const; TiXmlHandle Child(const char*value,int index)const; TiXmlHandle Child(int index)const; TiXmlHandle ChildElement(const char*value,int index)const; TiXmlHandle ChildElement(int index)const; #ifdef TIXML_USE_STL TiXmlHandle FirstChild(const std::string&_value)const{return FirstChild(_value.c_str());} TiXmlHandle FirstChildElement(const std::string&_value)const{return FirstChildElement(_value.c_str());} TiXmlHandle Child(const std::string&_value,int index)const{return Child(_value.c_str(),index);} TiXmlHandle ChildElement(const std::string&_value,int index)const{return ChildElement(_value.c_str(),index);} #endif TiXmlNode*ToNode()const{return node;} TiXmlElement*ToElement()const{return((node&&node->ToElement())?node->ToElement():0);} TiXmlText*ToText()const{return((node&&node->ToText())?node->ToText():0);} TiXmlUnknown*ToUnknown()const{return((node&&node->ToUnknown())?node->ToUnknown():0);} TiXmlNode*Node()const{return ToNode();} TiXmlElement*Element()const{return ToElement();} TiXmlText*Text()const{return ToText();} TiXmlUnknown*Unknown()const{return ToUnknown();} private: TiXmlNode*node; }; class TiXmlPrinter:public TiXmlVisitor { public: TiXmlPrinter():depth(0),simpleTextPrint(false), buffer(),indent(" "),lineBreak("\n"){} virtual bool VisitEnter(const TiXmlDocument&doc); virtual bool VisitExit(const TiXmlDocument&doc); virtual bool VisitEnter(const TiXmlElement&element,const TiXmlAttribute*firstAttribute); virtual bool VisitExit(const TiXmlElement&element); virtual bool Visit(const TiXmlDeclaration&declaration); virtual bool Visit(const TiXmlText&text); virtual bool Visit(const TiXmlComment&comment); virtual bool Visit(const TiXmlUnknown&unknown); void SetIndent(const char*_indent){indent=_indent?_indent:"";} const char*Indent(){return indent.c_str();} void SetLineBreak(const char*_lineBreak){lineBreak=_lineBreak?_lineBreak:"";} const char*LineBreak(){return lineBreak.c_str();} void SetStreamPrinting(){indent=""; lineBreak=""; } const char*CStr(){return buffer.c_str();} size_t Size(){return buffer.size();} #ifdef TIXML_USE_STL const std::string&Str(){return buffer;} #endif private: void DoIndent(){ for(int i=0;i<depth;++i) buffer+=indent; } void DoLineBreak(){ buffer+=lineBreak; } int depth; bool simpleTextPrint; TIXML_STRING buffer; TIXML_STRING indent; TIXML_STRING lineBreak; }; #ifdef _MSC_VER #pragma warning(pop) #endif #endif
// SingleList.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" int main() { SingleList<int> link; for (int i = 0; i < 10; i++) { link.insert(i, i); } cout << link.size() << endl; link.insert_head(1111); link.insert_last(2222); SingleList<int>::pointer ptr = link.getHead(); while (ptr != nullptr) { cout << ptr->value << endl; ptr = ptr->next; } getchar(); return 0; }
/* * Copyright (C) 2012-2016 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * Author: Jennifer Buehler */ #ifndef COLLISION_BENCHMARK_GAZEBOMODELLOADER_H #define COLLISION_BENCHMARK_GAZEBOMODELLOADER_H #include <gazebo/common/CommonIface.hh> #include <sdf/sdf_config.h> #include <boost/filesystem.hpp> #include <tinyxml.h> #include <string> namespace collision_benchmark { /** * \brief Helper to load a model of a given name from the gazebo model paths. * * \author Jennifer Buehler * \date May 2017 */ class GazeboModelLoader { // public: static std::string GetModelSdfFilename(const std::string &modelNameOrFile) { // first, check if \e modelNameOrFile is a file boost::filesystem::path modelNamePath(modelNameOrFile); if (boost::filesystem::exists(modelNamePath) && boost::filesystem::is_regular_file(modelNamePath)) { // XXX TODO: Check that it is a SDF file too return modelNameOrFile; } // this must be a model name, so try to find it in the gazebo paths std::string modelPath = gazebo::common::find_file("model://" + modelNameOrFile); std::string sdfFilename; // find the manifest.config (or .xml) to read the SDF file from boost::filesystem::path manifestPath = modelPath; if (boost::filesystem::exists(manifestPath / "model.config")) { manifestPath /= "model.config"; } else if (boost::filesystem::exists(manifestPath / "model.xml")) { std::cerr << "The manifest.xml for a model is deprecated. " << "Please rename manifest.xml to " << "model.config" << std::endl; manifestPath /= "manifest.xml"; } else { std::cerr << "Cannot find model files for '" << modelNameOrFile << "'" << std::endl; } TiXmlDocument manifestDoc; if (manifestDoc.LoadFile(manifestPath.string())) { TiXmlElement *modelXML = manifestDoc.FirstChildElement("model"); if (!modelXML) std::cerr << "No <model> element in manifest " << manifestPath << std::endl; else { TiXmlElement *sdfXML = modelXML->FirstChildElement("sdf"); TiXmlElement *sdfSearch = sdfXML; // Find the SDF element that matches the current SDF version. while (sdfSearch) { if (sdfSearch->Attribute("version") && std::string(sdfSearch->Attribute("version")) == SDF_VERSION) { sdfXML = sdfSearch; break; } sdfSearch = sdfSearch->NextSiblingElement("sdf"); } sdfFilename = modelPath + "/" + sdfXML->GetText(); } } else { std::cerr << "Error parsing XML in file '" << manifestPath.string() << "': " << manifestDoc.ErrorDesc() << std::endl; } return sdfFilename; } }; // class GazeboModelLoader } // namespace #endif // COLLISION_BENCHMARK_GAZEBOMODELLOADER_H
/* 1949. 등산로 조정 다시풀기 처음에 꼭대기를 찾기 위해 top 리스트를 queue로 구현했었는데, 각 테스트 케이스 마다 없애줄 때 한 번에 clear할 수 없다는 것을 깜빡했었다. 그래서 vector로 다시 바꿔주었는데, 이 부분을 까먹지 말도록 유의하자! */ #include <iostream> #include <vector> #include <queue> #include <algorithm> #include <cstring> using namespace std; typedef pair<int, int> pii; int T, N, K, answer = 0; int mountain[8][8]; bool visited[8][8]; vector<pair<int, pii>> top; int dr[4] = {0,0,-1,1}; int dc[4] = {-1,1,0,0}; void dfs(int cnt, int h, pii pos, bool used) { if(cnt > answer) answer = cnt; for(int i = 0; i < 4; i++) { int nr = pos.first + dr[i]; int nc = pos.second + dc[i]; if(nr < 0 || nr > N-1 || nc < 0 || nc > N-1 || visited[nr][nc]) continue; visited[nr][nc] = true; if(mountain[nr][nc] < h) { dfs(cnt + 1, mountain[nr][nc], make_pair(nr, nc), used); } else if(used == false && mountain[nr][nc] - K < h) { dfs(cnt + 1, h - 1, make_pair(nr, nc), true); } visited[nr][nc] = false; } } bool comp(pair<int, pii> a, pair<int, pii> b) { return a.first > b.first; } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> T; for(int t=1; t<=T; t++) { top.clear(); answer = 0; cin >> N >> K; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { cin >> mountain[i][j]; top.push_back(make_pair(mountain[i][j], make_pair(i, j))); } } sort(top.begin(), top.end(), comp); int h = 0; for(int i = 0; i < top.size(); i++) { if(top[i].first >= h) { h = top[i].first; memset(visited, false, sizeof(visited)); visited[top[i].second.first][top[i].second.second] = true; dfs(1, top[i].first, top[i].second, false); } else break; } printf("#%d %d\n", t, answer); } return 0; }
#include <cstdio> #include <cstring> void reverse(char str[], int len); int main() { char dict[13] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K'}; char str1[101], str2[101], str[202]; scanf("%s %s", str1, str2); int len1 = strlen(str1), len2 = strlen(str2); int n = 0; // reverse string reverse(str1, len1); reverse(str2, len2); int i, a, b; for(i = 0; i < len1 || i < len2; i++) { a = i < len1 ? str1[i] - '0' : 0; b = i < len2 ? str2[i] - '0' : 0; if((i+1) % 2 == 1) { // Odd str[n++] = dict[(a+b)%13]; } else { str[n++] = (b-a+10)%10 + '0'; } } /* WARNING: 比较奇怪, 单独写出来之后测试点5没有通过 if(i == len1) { // B more while(i < len2) str[n++] = str2[i++]; } else { // A more while(i < len1) { if((i+1) % 2 == 1) { str[n++] = str1[i++]; } else { str[n++] = 10-(str1[i++]-'0') + '0'; } } } */ str[n] = '\0'; reverse(str, strlen(str)); printf("%s", str); return 0; } void reverse(char str[], int len) { char tmp; for(int i = 0; i < len / 2; i++) { tmp = str[i]; str[i] = str[len-1-i]; str[len-1-i] = tmp; } // printf("%s\n", str); }
/* --------------------------------------------------------------------------------- */ /* Esse programa foi usado para ler os canais e capturar a duração exata dos pulsos */ /* de ambos canais. Sendo o canal 01 para direção e o canal 02 para aceleração. */ /* Podendo ser implementado no código principal, porém tomar cuidado com o delay que */ /* irá interferir no tempo de resposta da aceleração e da direção. */ /* Se for usado no código principal o ideal é deixar as funções e o delay como */ /* comentário e usar somente quando for necessário. */ /* --------------------------------------------------------------------------------- */ /* --- DECLARAÇÃO DE PINOS --- */ #define ch1 5 #define ch2 3 /* --- DECLARAÇÃO DE VARIÁVEIS DOS CANAIS --- */ int canal_01, canal_02; void setup() { pinMode(ch1, INPUT); //Entrada para o canal 3 do rádio pinMode(ch2, INPUT); //Entrada para o canal 5 do rádio } void loop() { LeitorDeCanais(); TesteDeCanais(); delay (500); } void LeitorDeCanais() { // Faz a leitura dos canais ativos do rádio. canal_01 = pulseIn (ch1, HIGH, 25000); //MAXIMO DE TEMPO QUE ELE ESPERA PRO EVENTO OCORRER 25000 microsegundos. canal_02 = pulseIn (ch2, HIGH, 25000); //25000 microsegundos -> 25 milisegundos, 0,0025s; vem 1 segundo por padrão. } void TesteDeCanais() { // Testa os canais via serial monitor Serial.println("================="); Serial.print("Canal 01: "); Serial.println(canal_01); Serial.print("Canal 02: "); Serial.println(canal_02); }
#include <TESTS/test_assertions.h> #include <TESTS/testcase.h> #include <CORE/MEMORY/memory.h> #include <CORE/types.h> using core::memory::allocAligned; using core::memory::freeAligned; using core::memory::isPow2; using core::memory::nextPow2; REGISTER_TEST_CASE(testPow2) { TEST(testing::assertTrue(isPow2((intptr_t) 1))); TEST(testing::assertTrue(isPow2((intptr_t) 2))); TEST(testing::assertFalse(isPow2((intptr_t) 3))); TEST(testing::assertTrue(isPow2((intptr_t) 4))); TEST(testing::assertFalse(isPow2((intptr_t) 5))); TEST(testing::assertFalse(isPow2((intptr_t) 6))); TEST(testing::assertFalse(isPow2((intptr_t) 7))); TEST(testing::assertTrue(isPow2((intptr_t) 8))); TEST(testing::assertTrue(isPow2((intptr_t) 16))); TEST(testing::assertTrue(isPow2((intptr_t) 32))); TEST(testing::assertTrue(isPow2((intptr_t) 64))); } REGISTER_TEST_CASE(testNextPow2) { TEST(testing::assertEquals(nextPow2(0), 1)); TEST(testing::assertEquals(nextPow2(1), 1)); TEST(testing::assertEquals(nextPow2(2), 2)); TEST(testing::assertEquals(nextPow2(3), 4)); TEST(testing::assertEquals(nextPow2(5), 8)); TEST(testing::assertEquals(nextPow2(15), 16)); TEST(testing::assertEquals(nextPow2(120), 128)); } REGISTER_TEST_CASE(testAllocFree) { u8 *testPtr = (u8 *) allocAligned(16, 16); TEST(testing::assertEquals(int((intptr_t) testPtr & 15), 0)); freeAligned(testPtr); } REGISTER_TEST_CASE(testReFree) { freeAligned(nullptr); }
#include "Multiplex_Labeling_TMT_iTRAQ.h" #include "../EngineLayer/GlobalVariables.h" #include "../EngineLayer/CommonParameters.h" using namespace Chemistry; using namespace EngineLayer; using namespace MassSpectrometry; using namespace NUnit::Framework; using namespace Proteomics; using namespace Proteomics::Fragmentation; using namespace Proteomics::ProteolyticDigestion; namespace Test { void Multiplex_Labeling_TMT_iTRAQ::TestChemicalFormulaWithIsotopesTMT(const std::wstring &formula, double mass) { ChemicalFormula *cf = ChemicalFormula::ParseFormula(formula); Assert::AreEqual(mass, ClassExtensions::RoundedDouble(cf->MonoisotopicMass)); } void Multiplex_Labeling_TMT_iTRAQ::TestPeptideLabelledWithTMT(const std::wstring &peptide, double totalMass) { std::vector<Modification*> gptmdModifications; gptmdModifications.insert(gptmdModifications.end(), GlobalVariables::getAllModsKnown().begin(), GlobalVariables::getAllModsKnown().end()); std::vector<Modification*> tmt10Mods = gptmdModifications.Where([&] (std::any m) { return m->ModificationType == L"Multiplex Label" && m::IdWithMotif->Contains(L"TMT10"); }).ToList(); Protein *P = new Protein(peptide, L"", L"", nullptr, nullptr, nullptr, nullptr, nullptr, false, false, nullptr, nullptr, nullptr, nullptr); DigestionParams tempVar(minPeptideLength: 1); CommonParameters *CommonParameters = new CommonParameters(digestionParams: &tempVar); auto p = P->Digest(CommonParameters->getDigestionParams(), tmt10Mods, std::vector<Modification*>()).First(); auto f = p->Fragment(DissociationType::HCD, FragmentationTerminus::Both); std::vector<double> productMasses = f->Select([&] (std::any m) { m::NeutralMass::ToMz(1); }).ToList(); productMasses.Distinct(); std::sort(productMasses.begin(), productMasses.end()); Assert::AreEqual(totalMass, ClassExtensions::RoundedDouble(p->MonoisotopicMass.ToMz(1), 4)); delete CommonParameters; delete P; } void Multiplex_Labeling_TMT_iTRAQ::TestPeptideLabelledWith_iTRAQ_4plex(const std::wstring &peptide, double totalMass) { std::vector<Modification*> gptmdModifications; gptmdModifications.insert(gptmdModifications.end(), GlobalVariables::getAllModsKnown().begin(), GlobalVariables::getAllModsKnown().end()); std::vector<Modification*> itraq4plex = gptmdModifications.Where([&] (std::any m) { return m->ModificationType == L"Multiplex Label" && m::IdWithMotif->Contains(L"iTRAQ-4plex"); }).ToList(); Protein *P = new Protein(peptide, L"", L"", nullptr, nullptr, nullptr, nullptr, nullptr, false, false, nullptr, nullptr, nullptr, nullptr); DigestionParams tempVar(minPeptideLength: 1); CommonParameters *CommonParameters = new CommonParameters(digestionParams: &tempVar); auto p = P->Digest(CommonParameters->getDigestionParams(), itraq4plex, std::vector<Modification*>()).First(); auto f = p->Fragment(DissociationType::HCD, FragmentationTerminus::Both); std::vector<double> productMasses = f->Select([&] (std::any m) { m::NeutralMass::ToMz(1); }).ToList(); productMasses.Distinct(); std::sort(productMasses.begin(), productMasses.end()); Assert::AreEqual(totalMass, ClassExtensions::RoundedDouble(p->MonoisotopicMass.ToMz(1), 4)); delete CommonParameters; delete P; } void Multiplex_Labeling_TMT_iTRAQ::TestPeptideLabelledWith_DiLeu_4plex(const std::wstring &peptide, double totalMass) { std::vector<Modification*> gptmdModifications; gptmdModifications.insert(gptmdModifications.end(), GlobalVariables::getAllModsKnown().begin(), GlobalVariables::getAllModsKnown().end()); std::vector<Modification*> itraq4plex = gptmdModifications.Where([&] (std::any m) { return m->ModificationType == L"Multiplex Label" && m::IdWithMotif->Contains(L"DiLeu-4plex"); }).ToList(); Protein *P = new Protein(peptide, L"", L"", nullptr, nullptr, nullptr, nullptr, nullptr, false, false, nullptr, nullptr, nullptr, nullptr); DigestionParams tempVar(minPeptideLength: 1); CommonParameters *CommonParameters = new CommonParameters(digestionParams: &tempVar); auto p = P->Digest(CommonParameters->getDigestionParams(), itraq4plex, std::vector<Modification*>()).First(); auto f = p->Fragment(DissociationType::HCD, FragmentationTerminus::Both); std::vector<double> productMasses = f->Select([&] (std::any m) { m::NeutralMass::ToMz(1); }).ToList(); productMasses.Distinct(); std::sort(productMasses.begin(), productMasses.end()); Assert::AreEqual(totalMass, ClassExtensions::RoundedDouble(p->MonoisotopicMass.ToMz(1), 4)); delete CommonParameters; delete P; } void Multiplex_Labeling_TMT_iTRAQ::TestPeptideLabelledWith_iTRAQ_8plex(const std::wstring &peptide, double totalMass) { std::vector<Modification*> gptmdModifications; gptmdModifications.insert(gptmdModifications.end(), GlobalVariables::getAllModsKnown().begin(), GlobalVariables::getAllModsKnown().end()); std::vector<Modification*> itraq8plex = gptmdModifications.Where([&] (std::any m) { return m->ModificationType == L"Multiplex Label" && m::IdWithMotif->Contains(L"iTRAQ-8plex"); }).ToList(); Protein *P = new Protein(peptide, L"", L"", nullptr, nullptr, nullptr, nullptr, nullptr, false, false, nullptr, nullptr, nullptr, nullptr); DigestionParams tempVar(minPeptideLength: 1); CommonParameters *CommonParameters = new CommonParameters(digestionParams: &tempVar); auto p = P->Digest(CommonParameters->getDigestionParams(), itraq8plex, std::vector<Modification*>()).First(); auto f = p->Fragment(DissociationType::HCD, FragmentationTerminus::Both); std::vector<double> productMasses = f->Select([&] (std::any m) { m::NeutralMass::ToMz(1); }).ToList(); productMasses.Distinct(); std::sort(productMasses.begin(), productMasses.end()); Assert::AreEqual(totalMass, ClassExtensions::RoundedDouble(p->MonoisotopicMass.ToMz(1), 4)); delete CommonParameters; delete P; } void Multiplex_Labeling_TMT_iTRAQ::TestChemicalFormulaWithIsotopes_iTRAQ(const std::wstring &formula, double mass, bool mz) { ChemicalFormula *cf = ChemicalFormula::ParseFormula(formula); if (mz) { Assert::AreEqual(mass, ClassExtensions::RoundedDouble(cf->MonoisotopicMass.ToMz(1))); } else { Assert::AreEqual(mass, ClassExtensions::RoundedDouble(cf->MonoisotopicMass)); } } void Multiplex_Labeling_TMT_iTRAQ::TestChemicalFormulaWithIsotopes_DiLeu4plex(const std::wstring &formula, double mass, bool mz) { ChemicalFormula *cf = ChemicalFormula::ParseFormula(formula); if (mz) { Assert::AreEqual(mass, ClassExtensions::RoundedDouble(cf->MonoisotopicMass.ToMz(1))); } else { Assert::AreEqual(mass, ClassExtensions::RoundedDouble(cf->MonoisotopicMass)); } } void Multiplex_Labeling_TMT_iTRAQ::TestChemicalFormulaWithIsotopes_DiLeu12plex(const std::wstring &formula, double mass, bool mz) { ChemicalFormula *cf = ChemicalFormula::ParseFormula(formula); if (mz) { Assert::AreEqual(mass, ClassExtensions::RoundedDouble(cf->MonoisotopicMass.ToMz(1),5)); } else { Assert::AreEqual(mass, ClassExtensions::RoundedDouble(cf->MonoisotopicMass)); } } }
#include <vector> #include <map> using namespace std; // decision if n is prime or not // O(n^1/2) bool is_prime(int n){ for (int i=2; i*i<=n; i++){ if(n % i == 0) return false; } return n != 1; } // enumerate prime numbers // O(n^1/2) vector<int> divisor (int n){ vector<int> res; for (int i=1; i*i<=n; i++){ if(n % i == 0) { res.push_back(i); if (i != n / i) res.push_back(n / i); } } return res; } // prime factoring // O(n^1/2) map<int, int> prime_factor(int n){ map<int, int> res; for (int i=2; i*i<n; i++){ while (n % i == 0){ ++res[i]; n /= i; } } if (n != 1) res[n] = 1; return res; }
#include <ros/ros.h> #include <sensor_msgs/LaserScan.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/point_cloud2_iterator.h> #include <math.h> class LaserChooser { public: LaserChooser() { //Topic you want to publish msg_pub_ = nh_.advertise<sensor_msgs::LaserScan>("scan", 1000); //Topic you want to subscribe msg_sub_ = nh_.subscribe("velodyne_points", 1000, &LaserChooser::ChooserCb, this); } void ChooserCb(const sensor_msgs::PointCloud2ConstPtr &msg) { sensor_msgs::LaserScan output; double minangle=M_PI; double maxangle=-M_PI; output.header = msg->header; //output.angle_min = -M_PI; //output.angle_max = M_PI; double angle_increment_=M_PI / 900; output.angle_increment = M_PI / 2700; output.time_increment = 0.0; output.scan_time = 1.0/30.0; output.range_min = 0.5; output.range_max = 100.0; output.ranges.resize(5400); output.intensities.resize(5400); int k=0; for (sensor_msgs::PointCloud2ConstIterator<float> iter_x(*msg, "x"), iter_y(*msg, "y"), iter_z(*msg, "z"); iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z) { if (msg->data[k+20] == 7){ double range = hypot(*iter_x, *iter_y); if (range >= output.range_min && range <= output.range_max){ //overwrite range at laserscan ray if new range is smaller double angle = atan2(*iter_y, *iter_x); if (angle < minangle){ minangle = angle; } if (angle > maxangle){ maxangle = angle; } int index = (angle + M_PI) / angle_increment_; if (range < output.ranges[index] || output.ranges[index]==0 ) { output.ranges[index] = range; unsigned char b[4]={msg->data[k+16],msg->data[k+17],msg->data[k+18],msg->data[k+19]}; output.intensities[index] = *((float *)b); } } } if (msg->data[k+20] == 10){ double range = hypot(*iter_x, *iter_y); if (range >= output.range_min && range <= output.range_max){ //overwrite range at laserscan ray if new range is smaller double angle = atan2(*iter_y, *iter_x); if (angle < minangle){ minangle = angle; } if (angle > maxangle){ maxangle = angle; } int index = (angle + M_PI) / angle_increment_; if (range < output.ranges[index] || output.ranges[index]==0 ) { output.ranges[index+1] = range; unsigned char b[4]={msg->data[k+16],msg->data[k+17],msg->data[k+18],msg->data[k+19]}; output.intensities[index+1] = *((float *)b); } } } if (msg->data[k+20] == 8){ double range = hypot(*iter_x, *iter_y); if (range >= output.range_min && range <= output.range_max){ //overwrite range at laserscan ray if new range is smaller double angle = atan2(*iter_y, *iter_x); if (angle < minangle){ minangle = angle; } if (angle > maxangle){ maxangle = angle; } int index = (angle + M_PI) / angle_increment_; if (range < output.ranges[index] || output.ranges[index]==0 ) { output.ranges[index+2] = range; unsigned char b[4]={msg->data[k+16],msg->data[k+17],msg->data[k+18],msg->data[k+19]}; output.intensities[index+2] = *((float *)b); } } } /*if (msg->data[k+20] == 15){ double range = hypot(*iter_x, *iter_y); if (range >= output.range_min && range <= output.range_max){ //overwrite range at laserscan ray if new range is smaller double angle = atan2(*iter_y, *iter_x); if (angle < minangle){ minangle = angle; } if (angle > maxangle){ maxangle = angle; } int index = (angle + M_PI) / angle_increment_; if (range < output.ranges[index] || output.ranges[index]==0 ) { output.ranges[index+3] = range; unsigned char b[4]={msg->data[k+16],msg->data[k+17],msg->data[k+18],msg->data[k+19]}; output.intensities[index+3] = *((float *)b); } } }*/ k=k+32; } output.angle_min = minangle; output.angle_max = maxangle; msg_pub_.publish(output); } private: ros::NodeHandle nh_; ros::Publisher msg_pub_; ros::Subscriber msg_sub_; }; int main(int argc, char **argv) { //Initiate ROS ros::init(argc, argv, "LaserChooser"); //Create an object of class that will take care of everything LaserChooser LCObject; ros::spin(); return 0; }
#include "NCK.h" #include "MCU.h" #include "..\MyLog.h" namespace Shim { namespace CNC { namespace NCK { namespace ADCAI { static double LoopTime_sec = (double)DEFAULT_LOOPTIME_MICROS / 1000000.0f; static unsigned __int32 numAxis = DEFAULT_NUM_AXIS; static double Acc_Time_sec = (double)DEFAULT_ACC_TIME_MICROS / 1000000.0f; static double Max_Acc_mmpsec2 = (double)DEFAULT_MAX_ACC_MMPSEC2; static Position Position_Prev = 0; static Pulse<Vector> Pulse_Acc_Prev; /*******************************************************************************/ void ADCAI (Interpolated_Data* pData, Pulse<Vector>* pRes); void ADCAI_BlockOverlap (Interpolated_Data* pData, unsigned __int32 Acc_N, Pulse<Vector>* pRes); void ADCAI_ExactStop (Interpolated_Data* pData, unsigned __int32 Acc_N, Pulse<Vector>* pRes); void ADCAI_Lcal (Interpolated_Data* pData, unsigned __int32 Acc_N, Pulse<Vector>* pRes); } namespace ADCAI { void Init(double LoopTime_sec, unsigned __int32 numAxis, double Acc_Time_sec, double Max_Acc_mmpsec2) { ADCAI::LoopTime_sec = LoopTime_sec; ADCAI::numAxis = numAxis; ADCAI::Acc_Time_sec = Acc_Time_sec; ADCAI::Max_Acc_mmpsec2 = Max_Acc_mmpsec2; } void ADCAI(Interpolated_Data* pData, Pulse<Vector>* pRes) { Pulse<Vector>& Pulse_Velocity_Profile_Res = *pRes; Pulse<Vector>& Pulse_Position_Profile_Res = *pRes; //가감속 제한 계산 double Acc = pData->FeedRate_mmpsec / Acc_Time_sec; //가속도 계산 double tau1 = Acc_Time_sec; unsigned __int32 Acc_N; //n1은 뭐고 temp_n1은 뭡니까 unsigned __int32 i; if (Acc>Max_Acc_mmpsec2) { tau1 = pData->FeedRate_mmpsec / Max_Acc_mmpsec2; // 가속도가 허용가속도보다 클 경우 가감속 시정수 변환 } Acc_N = (unsigned __int32)(tau1 / LoopTime_sec)+1; // 가감속에 필요한 샘플링 주기 수 계산 // temp_n1 = pData->N + n1 -1; // N1 = pData->N // n1 = Acc_N ADCAI_BlockOverlap(pData, Acc_N, pRes); // ADCAI_ExactStop(pData ,Acc_N, pRes); for(i=0; i<Pulse_Velocity_Profile_Res.size(); ++i) { if(i==0) Pulse_Position_Profile_Res[0] += Position_Prev; else Pulse_Position_Profile_Res[i] += Pulse_Velocity_Profile_Res[i-1]; } if(pData->IsFinal) Position_Prev = pData->EndPos; else Position_Prev = Pulse_Position_Profile_Res[ Pulse_Position_Profile_Res.size()-1 ]; } ////////////////////////////////////// void ADCAI_BlockOverlap(Interpolated_Data* pData, unsigned __int32 Acc_N, Pulse<Vector>* pRes) { Pulse<Vector>& Pulse_Acc_New = *pRes; Pulse<Vector> Pulse_Acc_Sum; Pulse<Vector> Pulse_Acc; unsigned __int32 length_pulse_prev, length_pulse_sum; unsigned __int32 i; ADCAI_Lcal(pData, Acc_N, &Pulse_Acc); // for(i=0; i<Pulse_Acc.size(); ++i) // printf("%.3f %.3f\n", (double)Pulse_Acc[i].x, (double)Pulse_Acc[i].y); length_pulse_prev = Pulse_Acc_Prev.size(); length_pulse_sum = max(Pulse_Acc_Prev.size(),Pulse_Acc.size()); Pulse_Acc_Sum.resize( length_pulse_sum ); // for(i=0; i<length_pulse_sum; ++i) // Pulse_Acc_Sum[i].SetDimension(numAxis); for(i=1; i <= Pulse_Acc_Sum.size(); ++i) { if( (i<=length_pulse_prev) && (i<=Pulse_Acc.size()) ) { Pulse_Acc_Sum[i-1] = Pulse_Acc[i-1] + Pulse_Acc_Prev[i-1]; }else if( Pulse_Acc.size() > length_pulse_prev ) { Pulse_Acc_Sum[i-1] = Pulse_Acc[i-1]; }else if( Pulse_Acc.size() < length_pulse_prev ) { Pulse_Acc_Sum[i-1] = Pulse_Acc_Prev[i-1]; } } if( pData->IsFinal ) { Pulse_Acc_New = Pulse_Acc_Sum; Pulse_Acc_Prev.resize(0); }else { Pulse_Acc_New.resize(pData->N); // for(i=0; i<pData->N; ++i) // Pulse_Acc_New[i].SetDimension(numAxis); for(i=0; i<pData->N; ++i) Pulse_Acc_New[i] = Pulse_Acc_Sum[i]; Pulse_Acc_Prev.resize(Pulse_Acc_Sum.size() - pData->N); // for(i=0; i<Pulse_Acc_Sum.size() - pData->N; ++i) // Pulse_Acc_New[i].SetDimension(numAxis); for(i=i; i<Pulse_Acc_Sum.size(); ++i) Pulse_Acc_Prev[ i - pData->N ] = Pulse_Acc_Sum[i]; } // for(i=0; i<Pulse_Acc_New.size(); ++i) // printf("%7.3f %7.3f\n", (double)Pulse_Acc_New[i].x, (double)Pulse_Acc_New[i].y); /* m_Logging.StartLogging(); for(i=0; i<Pulse_Acc_New.size(); ++i) m_Logging.AddLog("%7.3f %7.3f\n", Pulse_Acc_New[i].x, Pulse_Acc_New[i].y); m_Logging.StopLogging(); */ } ////////////////////////// void ADCAI_ExactStop(Interpolated_Data* pData, unsigned __int32 Acc_N, Pulse<Vector>* pRes) { ADCAI_Lcal(pData, Acc_N, pRes); } void ADCAI_Lcal(Interpolated_Data* pData, unsigned __int32 Acc_N, Pulse<Vector>* pRes) { Pulse<Vector>& Pulse_Velocity_Profile_Res = *pRes; unsigned __int32 i,j,k; unsigned __int32 temp_n1; temp_n1 = pData->N + Acc_N -1; if( pData->N >= Acc_N) { Pulse_Velocity_Profile_Res.resize(temp_n1); // for(i=0; i<temp_n1; ++i) // Pulse_Velocity_Profile_Res[i].SetDimension(numAxis); for(j=1; j<=temp_n1; ++j) { Pulse_Velocity_Profile_Res[j-1] = 0; if(j <= Acc_N) { for(k=1; k<=j; ++k) Pulse_Velocity_Profile_Res[j-1] += pData->Pulse_Velocity_Profile[k-1]; }else if( j < pData->N ) { for(k=j-Acc_N+1; k<=j; ++k) Pulse_Velocity_Profile_Res[j-1] += pData->Pulse_Velocity_Profile[k-1]; }else { for(k=j-Acc_N+1; k<=pData->N; ++k) Pulse_Velocity_Profile_Res[j-1] += pData->Pulse_Velocity_Profile[k-1]; } } for(i=0; i < Pulse_Velocity_Profile_Res.size(); ++i) Pulse_Velocity_Profile_Res[i] /= Acc_N; }else { //이러면 작은구간은 전부 동일한데요 Pulse_Velocity_Profile_Res.resize(2*pData->N-1); // for(i=0; i<2*pData->N-1; ++i) // Pulse_Velocity_Profile_Res[i].SetDimension(numAxis); for(j=1; j<=2*pData->N-1; ++j) { Pulse_Velocity_Profile_Res[j-1] = 0; if( j<=pData->N ) { for(k=1; k<=j; ++k) Pulse_Velocity_Profile_Res[j-1] += pData->Pulse_Velocity_Profile[k-1]; }else { for(k=j-pData->N+1; k<=pData->N; ++k) Pulse_Velocity_Profile_Res[j-1] += pData->Pulse_Velocity_Profile[k-1]; } } for(i=0; i < Pulse_Velocity_Profile_Res.size(); ++i) Pulse_Velocity_Profile_Res[i] /= pData->N; } } void Clear2() { Position_Prev = 0; Pulse_Acc_Prev.resize(0); } }//ADCAI }//NCK }//CNC }//Shim
#include "Header.h" void mergeSortStudents(Student* persons, int arraySize) { bool isAlright = false; while (isAlright != true) { isAlright = true; for (int i = 1; i < arraySize; ++i) { if (persons[i - 1].Grade < persons[i].Grade) { Student temp = persons[i]; persons[i] = persons[i - 1]; persons[i - 1] = temp; //std::swap(array[i - 1], array[i]); isAlright = false; } } } } std::string getStudentData(const Student* student) { return student->Name + " got a grade of " + std::to_string(student->Grade); }
#include "../include/Tester.h" Tester::Tester(std::string testFilePath, std::string verificationFilePath, Classificator* classificators[10]) : testFilePath(testFilePath), verificationFilePath(verificationFilePath), classificators(classificators) { //constructor a = new Matrix(testFilePath, 784); } Tester::~Tester(){ delete a; delete mostProbableDigits; } void Tester::test(unsigned n_test, unsigned p){ this->n_test = n_test; mostProbableDigits = new std::vector<int>(n_test); errors = new std::vector<double>(n_test); Matrix* h = new Matrix(p, n_test); Matrix* c = new Matrix(784, n_test); Matrix* a_test = new Matrix(784, n_test); //Cópia de A contendo apenas as n_test colunas necessárias Matrix* Wd_test = new Matrix (784, p); //Copia a_test da a for(unsigned i = 1; i <= 784; i++){ for(unsigned j = 1 ; j <= n_test; j++){ a_test->setValue(i,j, a->at(i,j)); } } double c_norm; for(unsigned k = 0; k < 10; k++){ for(unsigned i = 1; i <= 784; i++){ for(unsigned j = 1 ; j <= p; j++){ Wd_test->setValue(i,j, classificators[k]->getWd()->at(i,j)); } } c_norm = 0; //Esse processo modifica h e a h = solveLinearSystems(Wd_test, a_test); //Recopia a matriz a_teste for(unsigned i = 1; i <= 784; i++){ for(unsigned j = 1 ; j <= n_test; j++){ a_test->setValue(i,j, a->at(i,j)); } } Matrix* Wdh = (*(classificators[k]->getWd())) * h; c = (*a_test) - Wdh; delete Wdh; for(unsigned j = 1; j <= n_test; j++ ){ for(unsigned i = 1; i <= 784; i++){ c_norm += (c->at(i, j)) * (c->at(i, j)); } c_norm = sqrt(c_norm); if(k == 0){ errors->at(j-1) = c_norm; }else if(c_norm < errors->at(j-1)){ errors->at(j-1) = c_norm; mostProbableDigits->at(j-1) = (int)k; } } } delete h; delete c; delete a_test; } void Tester::results() { std::ifstream input; input.open(verificationFilePath); double hits[10]; double quantity[10]; for (unsigned i = 0; i < 10; i++) { hits[i] = 0; quantity[i] = 0; } int din; double totalHits = 0; for (unsigned i = 0; i < n_test; i++) { input >> din; quantity[din]++; if ((*mostProbableDigits)[i] == din) { hits[din]++; totalHits++; } } input.close(); std::cout << "Taxa de acertos total: " << 100 * totalHits / double(n_test) << "%\n"; for (unsigned i = 0; i < 10; i++) { std::cout << "Taxa de acertos do dig. " << i << ": "; if(double(quantity[i]) >= 1.0) std::cout << 100 * double(hits[i]) / double(quantity[i]) << "%\n"; else std::cout << "Nenhum dig. testado\n"; } } void Tester::results(const std::string& filePath) { std::ifstream input; input.open(verificationFilePath); double hits[10]; double quantity[10]; for (unsigned i = 0; i < 10; i++) { hits[i] = 0; quantity[i] = 0; } int din; double totalHits = 0; for (unsigned i = 0; i < n_test; i++) { input >> din; quantity[din]++; if ((*mostProbableDigits)[i] == din) { hits[din]++; totalHits++; } } input.close(); std::ofstream output; output.open(filePath); output << "Taxa de acertos total: " << 100 * totalHits / double(n_test) << "%\n"; std::cout << "Taxa de acertos total: " << 100 * totalHits / double(n_test) << "%\n"; for (unsigned i = 0; i < 10; i++) { output << "Taxa de acertos dig. " << i << ": "; std::cout << "Taxa de acertos dig. " << i << ": "; if(double(quantity[i]) >= 1.0) { output << 100 * double(hits[i]) / double(quantity[i]) << "%\n"; std::cout << 100 * double(hits[i]) / double(quantity[i]) << "%\n"; } else { output << "No digit tested\n"; std::cout << "No digit tested\n"; } } }
#ifndef CLASEEWG #define CLASEEWG #include "Mybag.hh" #include <iostream> #include <vector> #include <queue> /*! * \brief Compare edges weights * * Is needed by priority_queue, to sort Edge objects in a correct order * */ class CompareEdges{ public: /*! * \brief Uses compareTo Edge member function to compare two edges weights * \return True if e1s weight is lower than e2s */ bool operator()(Edge& e1, Edge& e2){ return (e1.compareTo(e2)==-1); } }; /*! * \brief Extension of graph adjacency list to edge weighted graphs * * Creates an adjacency list that contains in each node an edge bag where can be store all vertex inceident edges * */ class EdgeWeightedGraph{ private: int NumV; /*!< Number of vertices*/ int NumE; /*!< Number of edges*/ MyBag** adj; /*!< Double pointer to adjacency list matrix*/ priority_queue<Edge, vector<Edge>, CompareEdges> pq; /*!< Priority queue where all edges will be stored*/ vector<Edge> buf; public: /*! * \brief Constructor * \param V Number of graph vertices */ EdgeWeightedGraph(int V); /*! * \brief Destructor */ ~EdgeWeightedGraph(); /*! * \brief Get number of vertices */ int V(); /*! * \brief Get number of edges */ int E(); /*! * \brief Prints all incident edges of v vertex */ void print(int v); /*! * \brief Add edge e to this graph */ void addEdge( Edge e); /*! * \brief Returns a priority queue with all the edges sorted by weight */ priority_queue<Edge, vector<Edge>, CompareEdges> priorityQueue(){ return pq; } /*! * \brief Returns a bag structure pointer of the adjacency list */ MyBag* Iterator(int v); // }; #endif
#include <iostream> #include <mathtoolbox/backtracking-line-search.hpp> #include <mathtoolbox/gradient-descent.hpp> using Eigen::VectorXd; void mathtoolbox::optimization::RunGradientDescent(const VectorXd& x_init, const std::function<double(const VectorXd&)>& f, const std::function<VectorXd(const VectorXd&)>& g, const VectorXd& lower_bound, const VectorXd& upper_bound, const double epsilon, const double default_alpha, const unsigned int max_num_iters, VectorXd& x_star, unsigned int& num_iters) { assert(x_init.size() > 0); const int num_dims = x_init.size(); const bool is_lower_bounded = (lower_bound.size() != 0); const bool is_upper_bounded = (upper_bound.size() != 0); assert(!is_lower_bounded || x_init.size() == lower_bound.size()); assert(!is_upper_bounded || x_init.size() == upper_bound.size()); // Initialize the solution x_star = x_init; // Calculate the initial value double y_star = f(x_star); for (int iter = 0; iter < max_num_iters; ++iter) { // Calculate the next candidate position const VectorXd grad = g(x_star); const VectorXd p = [&]() { // Initialize the direction VectorXd p = -grad; // Freeze dimensions that are on the boundary and are directed outside for (int dim = 0; dim < num_dims; ++dim) { if ((is_lower_bounded && p(dim) - lower_bound(dim) < epsilon && grad(dim) > 0.0) || (is_upper_bounded && upper_bound(dim) - p(dim) < epsilon && grad(dim) < 0.0)) { p(dim) = 0.0; } } return p; }(); const double step_size = RunBacktrackingBoundedLineSearch(f, grad, x_star, p, lower_bound, upper_bound, default_alpha, 0.5); VectorXd x_new = x_star + step_size * p; // Enforce bounding-box conditions by simple projection if (is_lower_bounded) { x_new = x_new.cwiseMax(lower_bound); } if (is_upper_bounded) { x_new = x_new.cwiseMin(upper_bound); } const double y_new = f(x_new); const double absolute_diff = std::abs(y_new - y_star); const double relative_diff = absolute_diff / std::max({std::abs(y_new), std::abs(y_star), 1.0}); // Update the state parameters x_star = x_new; y_star = y_new; num_iters = iter + 1; // Check the termination condition if (absolute_diff < epsilon || relative_diff < epsilon) { return; } } std::cerr << "Warning: the gradient descent did not converge." << std::endl; }
#include "wizhtmlreader.h" #include "share/wizmisc.h" #include <QDebug> const COLORREF CWizHtmlElemAttr::_clrInvalid = (COLORREF)0xFFFFFFFF; const unsigned short CWizHtmlElemAttr::_percentMax = USHRT_MAX; CWizHtmlElemAttr::CNamedColors CWizHtmlElemAttr::_namedColors; class CWizHtmlEntityResolver { private: class CCharEntityRefs : public std::map<CString, unsigned short> { public: CCharEntityRefs() { /** C0 Controls and Basic Latin */ (*this)[_T("quot")] = _T('\x22'); (*this)[_T("amp")] = _T('\x26'); (*this)[_T("apos")] = _T('\x27'); (*this)[_T("lt")] = _T('\x3C'); (*this)[_T("gt")] = _T('\x3E'); /** ISO 8859-1 (Latin-1) characters */ (*this)[_T("nbsp")] = _T('\xA0'); (*this)[_T("iexcl")] = _T('\xA1'); (*this)[_T("cent")] = _T('\xA2'); (*this)[_T("pound")] = _T('\xA3'); (*this)[_T("current")] = _T('\xA4'); (*this)[_T("yen")] = _T('\xA5'); (*this)[_T("brvbar")] = _T('\xA6'); (*this)[_T("sect")] = _T('\xA7'); (*this)[_T("uml")] = _T('\xA8'); (*this)[_T("copy")] = _T('\xA9'); (*this)[_T("ordf")] = _T('\xAA'); (*this)[_T("laquo")] = _T('\xAB'); (*this)[_T("not")] = _T('\xAC'); (*this)[_T("shy")] = _T('\xAD'); (*this)[_T("reg")] = _T('\xAE'); (*this)[_T("macr")] = _T('\xAF'); (*this)[_T("deg")] = _T('\xB0'); (*this)[_T("plusmn")] = _T('\xB1'); (*this)[_T("sup2")] = _T('\xB2'); (*this)[_T("sup3")] = _T('\xB3'); (*this)[_T("acute")] = _T('\xB4'); (*this)[_T("micro")] = _T('\xB5'); (*this)[_T("para")] = _T('\xB6'); (*this)[_T("middot")] = _T('\xB7'); (*this)[_T("cedil")] = _T('\xB8'); (*this)[_T("sup1")] = _T('\xB9'); (*this)[_T("ordm")] = _T('\xBA'); (*this)[_T("raquo")] = _T('\xBB'); (*this)[_T("frac14")] = _T('\xBC'); (*this)[_T("frac12")] = _T('\xBD'); (*this)[_T("frac34")] = _T('\xBE'); (*this)[_T("iquest")] = _T('\xBF'); (*this)[_T("Agrave")] = _T('\xC0'); (*this)[_T("Aacute")] = _T('\xC1'); (*this)[_T("Acirc")] = _T('\xC2'); (*this)[_T("Atilde")] = _T('\xC3'); (*this)[_T("Auml")] = _T('\xC4'); (*this)[_T("Aring")] = _T('\xC5'); (*this)[_T("AElig")] = _T('\xC6'); (*this)[_T("Ccedil")] = _T('\xC7'); (*this)[_T("Egrave")] = _T('\xC8'); (*this)[_T("Eacute")] = _T('\xC9'); (*this)[_T("Ecirc")] = _T('\xCA'); (*this)[_T("Euml")] = _T('\xCB'); (*this)[_T("Igrave")] = _T('\xCC'); (*this)[_T("Iacute")] = _T('\xCD'); (*this)[_T("Icirc")] = _T('\xCE'); (*this)[_T("Iuml")] = _T('\xCF'); (*this)[_T("ETH")] = _T('\xD0'); (*this)[_T("Ntilde")] = _T('\xD1'); (*this)[_T("Ograve")] = _T('\xD2'); (*this)[_T("Oacute")] = _T('\xD3'); (*this)[_T("Ocirc")] = _T('\xD4'); (*this)[_T("Otilde")] = _T('\xD5'); (*this)[_T("Ouml")] = _T('\xD6'); (*this)[_T("times")] = _T('\xD7'); (*this)[_T("Oslash")] = _T('\xD8'); (*this)[_T("Ugrave")] = _T('\xD9'); (*this)[_T("Uacute")] = _T('\xDA'); (*this)[_T("Ucirc")] = _T('\xDB'); (*this)[_T("Uuml")] = _T('\xDC'); (*this)[_T("Yacute")] = _T('\xDD'); (*this)[_T("THORN")] = _T('\xDE'); (*this)[_T("szlig")] = _T('\xDF'); (*this)[_T("agrave")] = _T('\xE0'); (*this)[_T("aacute")] = _T('\xE1'); (*this)[_T("acirc")] = _T('\xE2'); (*this)[_T("atilde")] = _T('\xE3'); (*this)[_T("auml")] = _T('\xE4'); (*this)[_T("aring")] = _T('\xE5'); (*this)[_T("aelig")] = _T('\xE6'); (*this)[_T("ccedil")] = _T('\xE7'); (*this)[_T("egrave")] = _T('\xE8'); (*this)[_T("eacute")] = _T('\xE9'); (*this)[_T("ecirc")] = _T('\xEA'); (*this)[_T("euml")] = _T('\xEB'); (*this)[_T("igrave")] = _T('\xEC'); (*this)[_T("iacute")] = _T('\xED'); (*this)[_T("icirc")] = _T('\xEE'); (*this)[_T("iuml")] = _T('\xEF'); (*this)[_T("eth")] = _T('\xF0'); (*this)[_T("ntilde")] = _T('\xF1'); (*this)[_T("ograve")] = _T('\xF2'); (*this)[_T("oacute")] = _T('\xF3'); (*this)[_T("ocirc")] = _T('\xF4'); (*this)[_T("otilde")] = _T('\xF5'); (*this)[_T("ouml")] = _T('\xF6'); (*this)[_T("divide")] = _T('\xF7'); (*this)[_T("oslash")] = _T('\xF8'); (*this)[_T("ugrave")] = _T('\xF9'); (*this)[_T("uacute")] = _T('\xFA'); (*this)[_T("ucirc")] = _T('\xFB'); (*this)[_T("uuml")] = _T('\xFC'); (*this)[_T("yacute")] = _T('\xFD'); (*this)[_T("thorn")] = _T('\xFE'); (*this)[_T("yuml")] = _T('\xFF'); } }; // Constructors public: CWizHtmlEntityResolver() { } // Operations public: static UINT resolveEntity(const unsigned short* lpszEntity, unsigned short &chSubst) { ATLASSERT(m_CharEntityRefs.size()); const unsigned short* lpszBegin = lpszEntity; const unsigned short* lpszEnd = ::wiz_strchr(lpszEntity, ';'); unsigned short chTemp = 0; // entity references always end with a semi-colon ';' if (lpszEnd == NULL) return (0); // skip leading white-space characters while (::wiz_isspace(*lpszBegin)) lpszBegin = ::wiz_strinc(lpszBegin); // remaining string (including semi-colon) // must be at least 4 characters in length if (lpszEnd - lpszBegin < 3) return (0U); // entity references always begin with an ampersand '&' symbol if (*lpszBegin != _T('&')) return (0U); lpszBegin = ::wiz_strinc(lpszBegin); // numeric (decimal or hexadecimal) entity reference? if (*lpszBegin == _T('#')) { lpszBegin = ::wiz_strinc(lpszBegin); chTemp = *lpszBegin; int radix = (::wiz_isdigit(chTemp) ? 10 : (chTemp == _T('x') || chTemp == _T('X') ? 16 : 0)); if (radix) { if (radix == 16) lpszBegin = ::wiz_strinc(lpszBegin); unsigned long ulNum = ::wiz_strtoul(lpszBegin, NULL, radix); chSubst = (unsigned short)ulNum; lpszEnd = ::wiz_strinc(lpszEnd); return (lpszEnd - lpszEntity); } } // character entity reference? else { CString strKey(lpszBegin, lpszEnd - lpszBegin); // because some character entity references are // case-sensitive, we must fix them manually if (!strKey.CompareNoCase(_T("eth")) || !strKey.CompareNoCase(_T("thorn"))) { if (::wiz_isupper(strKey[0])) strKey.MakeUpper(); else strKey.MakeLower(); } else if (!strKey.CompareNoCase(_T("Oslash"))) { strKey.MakeLower(); strKey.SetAt(0, _T('O')); } else if (!strKey.CompareNoCase(_T("AElig"))) { strKey.MakeLower(); strKey.SetAt(0, _T('A')); strKey.SetAt(1, _T('E')); } else { CString strT = strKey.Mid(1); strKey.MakeLower(); if (strT.CompareNoCase(_T("grave")) == 0 || strT.CompareNoCase(_T("acute")) == 0 || strT.CompareNoCase(_T("circ")) == 0 || strT.CompareNoCase(_T("uml")) == 0 || strT.CompareNoCase(_T("tilde")) == 0 || strT.CompareNoCase(_T("cedil")) == 0 || strT.CompareNoCase(_T("ring")) == 0) { strKey.SetAt(0, strT[0]); } } // is this a known entity reference? CCharEntityRefs::const_iterator it = m_CharEntityRefs.find(strKey); if (it != m_CharEntityRefs.end()) { chTemp = it->second; chSubst = chTemp; lpszEnd = ::wiz_strinc(lpszEnd); return (lpszEnd - lpszEntity); } } return (0U); } // Data Members private: static CCharEntityRefs m_CharEntityRefs; }; CWizHtmlEntityResolver::CCharEntityRefs CWizHtmlEntityResolver::m_CharEntityRefs; ////////////////////////////////////////////////////////////////////////////////////////////////////// CWizHtmlElemAttr::CWizHtmlElemAttr(const CString& strAttribName, const CString& strAttribValue ) { Init(); m_strAttrName = strAttribName; m_strAttrValue = strAttribValue; } CWizHtmlElemAttr::CWizHtmlElemAttr(const CWizHtmlElemAttr &rSource) { Init(); m_strAttrName = rSource.m_strAttrName; m_strAttrValue = rSource.m_strAttrValue; } void CWizHtmlElemAttr::Init(void) { if (_namedColors.size()) return; /** 28 system colors */ /* _namedColors["activeborder"] = (COLORREF)0x8000000A; _namedColors["activecaption"] = (COLORREF)0x80000002; _namedColors["appworkspace"] = (COLORREF)0x8000000C; _namedColors["background"] = (COLORREF)0x80000001; _namedColors["buttonface"] = (COLORREF)0x8000000F; _namedColors["buttonhighlight"] = (COLORREF)0x80000014; _namedColors["buttonshadow"] = (COLORREF)0x80000010; _namedColors["buttontext"] = (COLORREF)0x80000012; _namedColors["captiontext"] = (COLORREF)0x80000009; _namedColors["graytext"] = (COLORREF)0x80000011; _namedColors["highlight"] = (COLORREF)0x8000000D; _namedColors["highlighttext"] = (COLORREF)0x8000000E; _namedColors["inactiveborder"] = (COLORREF)0x8000000B; _namedColors["inactivecaption"] = (COLORREF)0x80000003; _namedColors["inactivecaptiontext"] = (COLORREF)0x80000013; _namedColors["infobackground"] = (COLORREF)0x80000018; _namedColors["infotext"] = (COLORREF)0x80000017; _namedColors["menu"] = (COLORREF)0x80000004; _namedColors["menutext"] = (COLORREF)0x80000007; _namedColors["scrollbar"] = (COLORREF)0x80000000; _namedColors["threeddarkshadow"] = (COLORREF)0x80000015; _namedColors["threedface"] = (COLORREF)0x8000000F; _namedColors["threedhighlight"] = (COLORREF)0x80000014; _namedColors["threedlightshadow"] = (COLORREF)0x80000016; _namedColors["threedshadow"] = (COLORREF)0x80000010; _namedColors["window"] = (COLORREF)0x80000005; _namedColors["windowframe"] = (COLORREF)0x80000006; _namedColors["windowtext"] = (COLORREF)0x80000008; */ /** 16 basic colors */ _namedColors["black"] = RGB(0x00, 0x00, 0x00); _namedColors["gray"] = RGB(0x80, 0x80, 0x80); _namedColors["silver"] = RGB(0xC0, 0xC0, 0xC0); _namedColors["white"] = RGB(0xFF, 0xFF, 0xFF); _namedColors["yellow"] = RGB(0xFF, 0xFF, 0x00); _namedColors["olive"] = RGB(0x80, 0x80, 0x00); _namedColors["red"] = RGB(0xFF, 0x00, 0x00); _namedColors["maroon"] = RGB(0x80, 0x00, 0x00); _namedColors["fuchsia"] = RGB(0xFF, 0x00, 0xFF); _namedColors["purple"] = RGB(0x80, 0x00, 0x80); _namedColors["blue"] = RGB(0x00, 0x00, 0xFF); _namedColors["navy"] = RGB(0x00, 0x00, 0x80); _namedColors["aqua"] = RGB(0x00, 0xFF, 0xFF); _namedColors["teal"] = RGB(0x00, 0x80, 0x80); _namedColors["lime"] = RGB(0x00, 0xFF, 0x00); _namedColors["green"] = RGB(0x00, 0x80, 0xFF); /** additional named colors */ _namedColors["darkolivegreen"] = RGB(0x55, 0x6B, 0x2F); _namedColors["olivedrab"] = RGB(0x6B, 0x8E, 0x23); _namedColors["yellowgreen"] = RGB(0x9A, 0xCD, 0x32); _namedColors["lawngreen"] = RGB(0x7C, 0xFC, 0x00); _namedColors["chartreuse"] = RGB(0x7F, 0xFF, 0x00); _namedColors["greenyellow"] = RGB(0xAD, 0xFF, 0x2F); _namedColors["palegreen"] = RGB(0x98, 0xFB, 0x98); _namedColors["lightgreen"] = RGB(0x90, 0xEE, 0x90); _namedColors["darkgreen"] = RGB(0x00, 0x64, 0x00); _namedColors["forestgreen"] = RGB(0x22, 0x8B, 0x22); _namedColors["seagreen"] = RGB(0x2E, 0x8B, 0x57); _namedColors["mediumseagreen"] = RGB(0x3C, 0xB3, 0x71); _namedColors["limegreen"] = RGB(0x32, 0xCD, 0x32); _namedColors["darkseagreen"] = RGB(0x8F, 0xBC, 0x8B); _namedColors["springgreen"] = RGB(0x00, 0xFF, 0x7F); _namedColors["mediumspringgreen"] = RGB(0x00, 0xFA, 0x99); _namedColors["darkslategray"] = RGB(0x2F, 0x4F, 0x4F); _namedColors["darkcyan"] = RGB(0x00, 0x8B, 0x8B); _namedColors["cadetblue"] = RGB(0x5F, 0x9E, 0xA0); _namedColors["lightseagreen"] = RGB(0x20, 0xB2, 0xAA); _namedColors["mediumaquamarine"] = RGB(0x66, 0xCD, 0xAA); _namedColors["turquoise"] = RGB(0x40, 0xE0, 0xD0); _namedColors["aquamarine"] = RGB(0x7F, 0xFF, 0xD4); _namedColors["paleturquoise"] = RGB(0xAF, 0xEE, 0xEE); _namedColors["slategray"] = RGB(0x70, 0x80, 0x90); _namedColors["lightslategray"] = RGB(0x77, 0x88, 0x99); _namedColors["steelblue"] = RGB(0x46, 0x82, 0xB4); _namedColors["deepskyblue"] = RGB(0x00, 0xBF, 0xFF); _namedColors["darkturquoise"] = RGB(0x00, 0xCE, 0xD1); _namedColors["mediumturquoise"] = RGB(0x48, 0xD1, 0xCC); _namedColors["powderblue"] = RGB(0xB0, 0xE0, 0xE6); _namedColors["lightcyan"] = RGB(0xE0, 0xFF, 0xFF); _namedColors["darkblue"] = RGB(0x00, 0x00, 0x8B); _namedColors["mediumblue"] = RGB(0x00, 0x00, 0xCD); _namedColors["royalblue"] = RGB(0x41, 0x69, 0xe1); _namedColors["dodgerblue"] = RGB(0x1E, 0x90, 0xFF); _namedColors["cornflowerblue"] = RGB(0x64, 0x95, 0xED); _namedColors["skyblue"] = RGB(0x87, 0xCE, 0xEB); _namedColors["lightskyblue"] = RGB(0x87, 0xCE, 0xFA); _namedColors["lightblue"] = RGB(0xAD, 0xD8, 0xE6); _namedColors["midnightblue"] = RGB(0x19, 0x19, 0x70); _namedColors["darkslateblue"] = RGB(0x48, 0x3D, 0x8B); _namedColors["blueviolet"] = RGB(0x8A, 0x2B, 0xE2); _namedColors["slateblue"] = RGB(0x6A, 0x5A, 0xCD); _namedColors["mediumslateblue"] = RGB(0x7B, 0x68, 0xEE); _namedColors["mediumpurple"] = RGB(0x93, 0x70, 0xDB); _namedColors["lightsteelblue"] = RGB(0xB0, 0xC4, 0xDE); _namedColors["lavender"] = RGB(0xE6, 0xE6, 0xFA); _namedColors["indigo"] = RGB(0x4B, 0x00, 0x82); _namedColors["darkviolet"] = RGB(0x94, 0x00, 0xD3); _namedColors["darkorchid"] = RGB(0x99, 0x32, 0xCC); _namedColors["mediumorchid"] = RGB(0xBA, 0x55, 0xD3); _namedColors["orchid"] = RGB(0xDA, 0x70, 0xD6); _namedColors["violet"] = RGB(0xEE, 0x82, 0xEE); _namedColors["plum"] = RGB(0xDD, 0xA0, 0xDD); _namedColors["thistle"] = RGB(0xD8, 0xDF, 0xD8); _namedColors["darkmagenta"] = RGB(0x8B, 0x00, 0x8B); _namedColors["mediumvioletred"] = RGB(0xC7, 0x15, 0x85); _namedColors["deeppink"] = RGB(0xFF, 0x14, 0x93); _namedColors["palmvioletred"] = RGB(0xDB, 0x70, 0x93); _namedColors["hotpink"] = RGB(0xFF, 0x69, 0xB4); _namedColors["lightpink"] = RGB(0xFF, 0xB6, 0xC1); _namedColors["pink"] = RGB(0xFF, 0xC0, 0xCB); _namedColors["mistyrose"] = RGB(0xFF, 0xE4, 0xE1); _namedColors["brown"] = RGB(0xA5, 0x2A, 0x2A); _namedColors["indianred"] = RGB(0xCD, 0x5C, 0x5C); _namedColors["rosybrown"] = RGB(0xBC, 0x8F, 0x8F); _namedColors["salmon"] = RGB(0xFA, 0x80, 0x72); _namedColors["lightcoral"] = RGB(0xF0, 0x80, 0x80); _namedColors["darksalmon"] = RGB(0xE9, 0x96, 0x7A); _namedColors["lightsalmon"] = RGB(0xFF, 0xA0, 0x7A); _namedColors["peachpuff"] = RGB(0xFF, 0xDA, 0xB9); _namedColors["darkred"] = RGB(0x8B, 0x00, 0x00); _namedColors["firebrick"] = RGB(0xB2, 0x22, 0x22); _namedColors["crimson"] = RGB(0xDC, 0x14, 0x3C); _namedColors["orangered"] = RGB(0xFF, 0x45, 0x00); _namedColors["tomato"] = RGB(0xFF, 0x63, 0x47); _namedColors["coral"] = RGB(0xFF, 0x7F, 0x50); _namedColors["wheat"] = RGB(0xF5, 0xDE, 0xB3); _namedColors["papayawhip"] = RGB(0xFF, 0xEF, 0xD5); _namedColors["sienna"] = RGB(0xA0, 0x52, 0x2D); _namedColors["chocolate"] = RGB(0xD2, 0x69, 0x1E); _namedColors["darkorange"] = RGB(0xFF, 0x8C, 0x00); _namedColors["sandybrown"] = RGB(0xF4, 0xA4, 0x60); _namedColors["orange"] = RGB(0xFF, 0xA5, 0x00); _namedColors["navajowhite"] = RGB(0xFF, 0xDE, 0xAD); _namedColors["moccasin"] = RGB(0xFF, 0xE4, 0xB5); _namedColors["saddlebrown"] = RGB(0x8B, 0x45, 0x13); _namedColors["peru"] = RGB(0xCD, 0x85, 0x3F); _namedColors["burlywood"] = RGB(0xDE, 0xB8, 0x87); _namedColors["tan"] = RGB(0xD2, 0xB4, 0x8C); _namedColors["bisque"] = RGB(0xFF, 0xE4, 0xC4); _namedColors["blanchedalmond"] = RGB(0xFF, 0xEB, 0xCD); _namedColors["antiquewhite"] = RGB(0xFA, 0xEB, 0xD7); _namedColors["darkgoldenrod"] = RGB(0xB8, 0x86, 0x0B); _namedColors["goldenrod"] = RGB(0xDA, 0xA5, 0x20); _namedColors["darkkhaki"] = RGB(0xBD, 0xB7, 0x6B); _namedColors["gold"] = RGB(0xFF, 0xD7, 0x00); _namedColors["khaki"] = RGB(0xF0, 0xE6, 0x8C); _namedColors["palegoldenrod"] = RGB(0xEE, 0xE8, 0xAA); _namedColors["lemonchiffon"] = RGB(0xFF, 0xFA, 0xCD); _namedColors["beige"] = RGB(0xF5, 0xF5, 0xDC); _namedColors["lightgoldenrodyellow"]= RGB(0xFA, 0xFA, 0xD2); _namedColors["lightyellow"] = RGB(0xFF, 0xFF, 0xE0); _namedColors["ivory"] = RGB(0xFF, 0xFF, 0x00); _namedColors["cornsilk"] = RGB(0xFF, 0xF8, 0xDC); _namedColors["oldlace"] = RGB(0xFD, 0xF5, 0xE6); _namedColors["florawhite"] = RGB(0xFF, 0xFA, 0xF0); _namedColors["honeydew"] = RGB(0xF0, 0xFF, 0xF0); _namedColors["mintcream"] = RGB(0xF5, 0xFF, 0xFA); _namedColors["azure"] = RGB(0xF0, 0xFF, 0xFF); _namedColors["ghostwhite"] = RGB(0xF8, 0xF8, 0xFF); _namedColors["linen"] = RGB(0xFA, 0xF0, 0xE6); _namedColors["seashell"] = RGB(0xFF, 0xF5, 0xEE); _namedColors["snow"] = RGB(0xFF, 0xFA, 0xFA); _namedColors["dimgray"] = RGB(0x69, 0x69, 0x69); _namedColors["darkgray"] = RGB(0xA9, 0xA9, 0xA9); _namedColors["lightgray"] = RGB(0xD3, 0xD3, 0xD3); _namedColors["gainsboro"] = RGB(0xDC, 0xDC, 0xDC); _namedColors["whitesmoke"] = RGB(0xF5, 0xF5, 0xF5); _namedColors["ghostwhite"] = RGB(0xF8, 0xF8, 0xFF); _namedColors["aliceblue"] = RGB(0xF0, 0xF8, 0xFF); } bool CWizHtmlElemAttr::isNamedColorValue(void) const { if ( (m_strAttrValue.GetLength()) && (::wiz_isalpha(m_strAttrValue[0])) ) { CString strKey(m_strAttrValue); strKey.MakeLower(); if (_namedColors.find(m_strAttrValue) != _namedColors.end()) return (true); } return (false); } bool CWizHtmlElemAttr::isSysColorValue(void) const { if ( (m_strAttrValue.GetLength()) && (::wiz_isalpha(m_strAttrValue[0])) ) { COLORREF crTemp = _clrInvalid; CString strKey(m_strAttrValue); strKey.MakeLower(); CNamedColors::const_iterator it = _namedColors.find(strKey); if (it != _namedColors.end()) { crTemp = it->second; return ((unsigned int)crTemp >= 0x80000000 && (unsigned int)crTemp <= 0x80000018); } } return (false); } bool CWizHtmlElemAttr::isHexColorValue(void) const { // zero-length attribute value? if (m_strAttrValue.IsEmpty()) return (false); if (m_strAttrValue[0] == _T('#')) { if (m_strAttrValue.GetLength() > 1) { for (int i = 1; i < m_strAttrValue.GetLength(); i++) { if (!::wiz_isxdigit(m_strAttrValue[i])) return (false); } return (true); } } return (false); } COLORREF CWizHtmlElemAttr::getColorValue(void) const { COLORREF crTemp = _clrInvalid; if (isNamedColorValue()) { CString strKey(m_strAttrValue); strKey.MakeLower(); if (WizMapLookup(_namedColors, strKey, crTemp)) { /* // is this a system named color value? if ((unsigned int)crTemp >= 0x80000000 && (unsigned int)crTemp <= 0x80000018) crTemp = ::WizGetSysColor(crTemp & 0x7FFFFFFF); */ } } else if (isHexColorValue()) crTemp = ::wiz_strtoul(m_strAttrValue.Mid(1), NULL, 16); return (crTemp); } CString CWizHtmlElemAttr::getColorHexValue(void) const { CString strColorHex; if (isHexColorValue()) strColorHex = m_strAttrValue.Mid(1); else { COLORREF crTemp = getColorValue(); if (crTemp != _clrInvalid) strColorHex.Format(_T("#%06x"), crTemp); } return (strColorHex); } unsigned short CWizHtmlElemAttr::getPercentValue(unsigned short max ) const { ATLASSERT(max > 0); if (!isPercentValue()) return (0); unsigned short percentVal = (unsigned short)((short)*this); return ((percentVal > max ? max : percentVal)); } short CWizHtmlElemAttr::getLengthValue(LengthUnitsEnum &rUnit) const { static const char _szUnits[][4] = { /** relative length units */ _T("em"), _T("ex"), _T("px"), _T("%"), /** absolute length units */ _T("in"), _T("cm"), _T("mm"), _T("pt"), _T("pc") }; if (m_strAttrValue.IsEmpty()) return (0); // size_t i = 0; for (i = 0; i < sizeof(_szUnits)/sizeof(_szUnits[0]); i++) { if (m_strAttrValue.Right(::strlen(_szUnits[i])). \ CompareNoCase(_szUnits[i]) == 0) { rUnit = (LengthUnitsEnum)i; break; } } if (i == sizeof(_szUnits)/sizeof(_szUnits[0])) return (0); return (*this); } CWizHtmlElemAttr::operator bool () const { if (!m_strAttrValue.CompareNoCase(_T("true"))) return (true); if (!m_strAttrValue.CompareNoCase(_T("false"))) return (false); return (((short)*this ? true : false)); } void CWizHtmlElemAttr::putValue(const CString& strValue) { m_strAttrValue = strValue; m_strAttrValue.Trim(); // ignore line feeds m_strAttrValue.Remove(_T('\n')); // replace tab and carriage-return with a single space m_strAttrValue.Replace(_T('\r'), _T(' ')); m_strAttrValue.Replace(_T('\t'), _T(' ')); /** resolve entity reference(s) */ int iCurPos = -1, iParseLen = 0; unsigned short chSubst = 0; do { if ((iCurPos = m_strAttrValue.Find(_T('&'), ++iCurPos)) == -1) break; iParseLen = CWizHtmlEntityResolver::resolveEntity(m_strAttrValue.Mid(iCurPos), chSubst); if (iParseLen) { m_strAttrValue.Replace ( m_strAttrValue.Mid(iCurPos, iParseLen), CString(chSubst) ); } } while (true); } UINT CWizHtmlElemAttr::parseFromStr(const unsigned short* lpszString) { const unsigned short* lpszBegin = lpszString; const unsigned short* lpszEnd; unsigned short ch = 0; // skip leading white-space characters while (::wiz_isspace(*lpszBegin)) lpszBegin = ::wiz_strinc(lpszBegin); // name doesn't begin with an alphabet? if (!::wiz_isalpha(*lpszBegin)) return (0U); lpszEnd = lpszBegin; do { // attribute name may contain letters (a-z, A-Z), digits (0-9), // underscores '_', hyphen '-', colons ':', and periods '.' if ( (!::wiz_isalnum(*lpszEnd)) && (*lpszEnd != _T('-')) && (*lpszEnd != _T(':')) && (*lpszEnd != _T('_')) && (*lpszEnd != _T('.')) ) { //ATLASSERT(lpszEnd != lpszBegin); if (lpszEnd == lpszBegin) return (0U); // only white-space characters, a null-character, an // equal-sign, a greater-than symbol, or a forward-slash // can act as the separator between an attribute and its // value if (*lpszEnd == 0 || ::wiz_isspace(*lpszEnd) || *lpszEnd == _T('=') || *lpszEnd == _T('>') || *lpszEnd == _T('/')) { break; } return (0U); // any other character will fail parsing process } lpszEnd = ::wiz_strinc(lpszEnd); } while (true); // extract attribute name CString strAttrName(lpszBegin, lpszEnd - lpszBegin); if (*lpszEnd != _T('=')) { m_strAttrName = strAttrName; m_strAttrValue.Empty(); return (lpszEnd - lpszString); } else { // skip white-space characters after equal-sign // and the equal-sign itself do { lpszEnd = ::wiz_strinc(lpszEnd); } while (::wiz_isspace(*lpszEnd)); lpszBegin = lpszEnd; ch = *lpszEnd; // is attribute value wrapped in quotes? if (ch == _T('\'') || ch == _T('\"')) { lpszBegin = ::wiz_strinc(lpszBegin); // skip quote symbol do { lpszEnd = ::wiz_strinc(lpszEnd); } // Loop until we find the same quote character that // was used at the starting of the attribute value. // Anything within these quotes is considered valid! // NOTE that the entity references are resolved later. while (*lpszEnd != 0 && *lpszEnd != ch); } // open attribute value i.e. not wrapped in quotes? else { do { lpszEnd = ::wiz_strinc(lpszEnd); } // loop until we find a tag ending delimeter or any // white-space character, or until we reach at the // end of the string buffer while (*lpszEnd != 0 && !::wiz_isspace(*lpszEnd) && //*lpszEnd != _T('/') && *lpszEnd != _T('>')); *lpszEnd != _T('>')); } m_strAttrName = strAttrName; if (lpszEnd == lpszBegin) // empty attribute value? m_strAttrValue.Empty(); else // use putValue() instead of direct assignment; // this will automatically normalize data before // assigning according to the specs and will // also resolve entity references!!! putValue(CString(lpszBegin, lpszEnd - lpszBegin)); // calculate and return the count of characters successfully parsed return ((lpszEnd - lpszString) + (ch == _T('\'') || ch == _T('\"') ? 1 : 0) ); } return (0U); } CString CWizHtmlElemAttr::toString()const { if (-1 == m_strAttrValue.Find('"')) { return m_strAttrName + "=\"" + m_strAttrValue + "\""; } else { return m_strAttrName + "='" + m_strAttrValue + "'"; } } //////////////////////////////////////////////////////////////////////////////////////// CWizHtmlAttributes::CWizHtmlAttributes(CWizHtmlAttributes &rSource, bool bCopy) : m_parrAttrib(NULL) { if (!bCopy) { m_parrAttrib = rSource.m_parrAttrib; rSource.m_parrAttrib = NULL; } else { const int nElemCount = rSource.getCount(); if (nElemCount) { m_parrAttrib = new CElemAttrArray(); CWizHtmlElemAttr *pItem = NULL; /** DEEP COPY BEGIN */ for (int iElem = 0; iElem < nElemCount; iElem++) { if ((pItem = new CWizHtmlElemAttr(rSource[iElem])) == NULL) { removeAll(); return; } m_parrAttrib->push_back(pItem); pItem = NULL; } /** DEEP COPY END */ } } } UINT parseFromStr(const unsigned short* lpszString); int CWizHtmlAttributes::getCount(void) const { if (m_parrAttrib != NULL) return (m_parrAttrib->size()); return (0); } int CWizHtmlAttributes::getIndexFromName(const CString& strAttributeName) const { CWizHtmlElemAttr *pItem = NULL; for (int iElem = 0; iElem < getCount(); iElem++) { if ((pItem = (*m_parrAttrib)[iElem]) == NULL) // just in case continue; // perform a CASE-INSENSITIVE search if (pItem->m_strAttrName.CompareNoCase(strAttributeName) == 0) return (iElem); } return (-1); } CWizHtmlElemAttr CWizHtmlAttributes::operator[](int nIndex) const { if (!(nIndex >= 0 && nIndex < getCount())) { return (CWizHtmlElemAttr()); } // return ( *((*m_parrAttrib)[nIndex]) ); } CWizHtmlElemAttr* CWizHtmlAttributes::addAttribute(const CString& strName, const CString& strValue) { CWizHtmlElemAttr *pItem = new CWizHtmlElemAttr(strName, strValue); if (pItem != NULL) { if (m_parrAttrib == NULL) { if ((m_parrAttrib = new CElemAttrArray) == NULL) { WIZ_SAFE_DELETE_POINTER(pItem); return (NULL); } } } // m_parrAttrib->push_back(pItem); // return (pItem); } void CWizHtmlAttributes::setValueToName(const CString& strAttributeName, const CString& strValue) { removeAttribute(strAttributeName); addAttribute(strAttributeName, strValue); } bool CWizHtmlAttributes::removeAttribute(int nIndex) { if (!(nIndex >= 0 && nIndex < getCount())) return (false); CWizHtmlElemAttr *pItem = NULL; WIZ_SAFE_DELETE_POINTER(pItem); // m_parrAttrib->erase(m_parrAttrib->begin() + nIndex); // return (true); } bool CWizHtmlAttributes::removeAttribute(const CString& strAttributeName) { return removeAttribute(getIndexFromName(strAttributeName)); } bool CWizHtmlAttributes::removeAll(void) { CWizHtmlElemAttr *pItem = NULL; for (int iElem = 0; iElem < getCount(); iElem++) { WIZ_SAFE_DELETE_POINTER(pItem); } WIZ_SAFE_DELETE_POINTER(m_parrAttrib); return (true); } UINT CWizHtmlAttributes::parseFromStr(const unsigned short* lpszString) { CElemAttrArray *pcoll = NULL; CWizHtmlElemAttr oElemAttr; const UINT nStrLen = ::wiz_strlen(lpszString); UINT nRetVal = 0U, nTemp = 0U; do { // try to parse an attribute/value // pair from the rest of the string if (!(nTemp = oElemAttr.parseFromStr(&lpszString[nRetVal]))) { if (!nRetVal) goto LError; break; } // collection has not been instantiated until now? if (pcoll == NULL) { // instantiate now if ((pcoll = new CElemAttrArray) == NULL) // out of memory? { //TRACE0("(Error) CWizHtmlAttributes::parseFromStr: Out of memory.\n"); goto LError; } } // add attribute/value pair to collection pcoll->push_back(new CWizHtmlElemAttr(oElemAttr)); // advance seek pointer nRetVal += nTemp; } // do we still have something in the buffer to parse? while (nRetVal < nStrLen); // collection was never instantiated? if (pcoll == NULL) goto LError; // collection is empty? if (pcoll->empty()) goto LError; // current collection could not be emptied? if (!removeAll()) goto LError; m_parrAttrib = pcoll; pcoll = NULL; goto LCleanExit; // success! LError: WIZ_SAFE_DELETE_POINTER(pcoll); nRetVal = 0U; LCleanExit: return (nRetVal); } const unsigned short* FindRegExpEnd(const unsigned short* p) { while (*p) { unsigned short ch = *p; if (ch == _T('\r') || ch == _T('\n')) return p - 1; if (ch == _T('/') && *(p - 1) != _T('\\')) return p; p++; } return p; } inline BOOL IsJavascriptQuotBegin(const unsigned short* p) { const unsigned short ch = *p; if (ch != _T('"') && ch != _T('\'')) return FALSE; if (*(p - 1) == _T('\\')) return FALSE; return TRUE; } inline BOOL IsRegExpBegin(const unsigned short* pBegin, const unsigned short* p) { unsigned short ch = *p; // if (ch != _T('/')) return FALSE; if (*(p + 1) == _T('/')) //行注释 return FALSE; if (*(p + 1) == _T('*')) //快注释 return FALSE; // p--; while (p >= pBegin) { ch = *p; if (wiz_isspace(ch)) { p--; continue; } if (ch >= _T('a') && ch <= _T('z')) //除号 return FALSE; if (ch >= _T('A') && ch <= _T('Z')) //除号 return FALSE; if (ch == _T(')')) //除号 return FALSE; // if (ch == '=') return TRUE; if (ch == '(') return TRUE; if (ch == ',') return TRUE; // //Unknown // return FALSE; } return FALSE; } const unsigned short* GetStyleSource(const unsigned short* lpszUnparsed, CString* pstrStyle) { const unsigned short* p = lpszUnparsed; while (*p) { if (*p == _T('<')) { if (p[1] && p[2] && p[3] && p[4] && p[5] && p[6] && wiz_strnicmp(p + 1, _T("/style"), 6) == 0) { p += 7; while (*p && *p != _T('>')) { p++; } p++; break; } } p++; } ptrdiff_t nLen = p - lpszUnparsed; if (pstrStyle) { *pstrStyle = CString(lpszUnparsed, nLen); } return p; } const unsigned short* WizHTMLFindEndOfQuotInBlockScriptSource(const unsigned short* p, unsigned short chQuot) { const unsigned short* pOld = p; while (*p) { unsigned short ch = *p; // if (ch == '\\') { unsigned short chNext = *(p + 1); switch (chNext) { case '\\': case '\'': case 'b': case 'f': case 'n': case 'r': case 't': case '/': case '"': p++; break; } } else if (ch == chQuot) { //TOLOG(WizSubString(pOld, 0, p - pOld)); return p; } // p++; } // // return pOld; } const unsigned short* GetScriptSource(const unsigned short* lpszUnparsed, CString* pstrSource, BOOL bVB) { const unsigned short* p = lpszUnparsed; while (*p) { if (*p == _T('<')) { if ((p[1] && p[2] && p[3] && p[4] && p[5] && p[6] && p[7] && wiz_strnicmp(p + 1, _T("/script"), 7) == 0) || (p[1] && p[2] && p[3] && p[4] && p[5] && p[6] && p[7] && p[8] && wiz_strnicmp(p + 1, _T("\\/script"), 8) == 0)) {// p += 8; while (*p && *p != _T('>')) { p++; } p++; break; } } // if (bVB) {//vbscript if (*p == _T('"')) {//VBscript, javascript的引用 p++; int nQuotCount = 1; while (*p) { if (*p == _T('"') && *(p + 1) == _T('"')) { p++; } else if (*p == _T('"')) { nQuotCount++; if (nQuotCount % 2 == 0) { break; } } p++; } } else if (*p == _T('\'')) {//vbscript 注释 p++; while (*p && *p != _T('\n') && *p != _T('\r')) { p++; } } } else {//javascript if (IsRegExpBegin(lpszUnparsed, p)) { p++; p = FindRegExpEnd(p); } else if (IsJavascriptQuotBegin(p)) {//javascript的引用 const unsigned short ch = *p; p++; p = WizHTMLFindEndOfQuotInBlockScriptSource(p, ch); } else if (*p == _T('/') && *(p + 1) == _T('/')) {//javascript的行注释 p += 2; const unsigned short* lpszCommentsBegin = p; while (*p && *p != _T('\n') && *p != _T('\r')) { if (*p == _T('-') && *(p + 1) == _T('>')) { CString strLine = CString(lpszCommentsBegin, p - lpszCommentsBegin); if (-1 == strLine.Find(_T("<!--"))) { p++; break; } } else if (p[0] && p[1] && p[2] && p[3] && p[4] && p[5] && p[6] && p[7] && wiz_strnicmp(p, _T("</script"), 8) == 0) { p--; //跳出行注释尾部,因为最后有一个p++,所以需要先减1。 break; } p++; } } else if (*p == _T('/') && *(p + 1) == _T('*')) {//javascript的块注释 p += 2; while (*p && !(*p == _T('*') && *(p + 1) == _T('/'))) { p++; } p++; } } //to next p++; } ptrdiff_t nLen = p - lpszUnparsed; if (pstrSource) { *pstrSource = CString(lpszUnparsed, nLen); } return p; } CWizHtmlTag::CWizHtmlTag(CWizHtmlTag &rSource, bool bCopy) : m_pcollAttr(NULL) , m_strTagName(rSource.m_strTagName) , m_strTag(rSource.m_strTag) , m_bIsOpeningTag(rSource.m_bIsOpeningTag) , m_bIsClosingTag(rSource.m_bIsClosingTag) , m_bModified(false) { if (!bCopy) { m_pcollAttr = rSource.m_pcollAttr; rSource.m_pcollAttr = NULL; } else if (rSource.m_pcollAttr != NULL) { m_pcollAttr = new CWizHtmlAttributes(*(rSource.m_pcollAttr), true); } } UINT CWizHtmlTag::parseFromStr(const unsigned short* lpszString, bool &bIsOpeningTag, bool &bIsClosingTag, bool bParseAttrib /* = true */) { bool bClosingTag = false; bool bOpeningTag = false; CWizHtmlAttributes *pcollAttr = NULL; CString strTagName; UINT nRetVal = 0U, nTemp = 0U; bool bExtTag = false; //const unsigned short* lpszString = lpszString; const unsigned short* lpszBegin = lpszString; const unsigned short* lpszEnd = NULL; // skip leading white-space characters while (::wiz_isspace(*lpszBegin)) lpszBegin = ::wiz_strinc(lpszBegin); // HTML tags always begin with a less-than symbol if (*lpszBegin != _T('<')) return (0U); // skip tag's opening delimeter '<' lpszBegin = ::wiz_strinc(lpszBegin); // optimization for empty opening tags if (*lpszBegin == _T('>')) { ATLASSERT(strTagName.IsEmpty()); ATLASSERT(pcollAttr == NULL); ATLASSERT(!bClosingTag); nRetVal = lpszBegin - lpszString; goto LUpdateAndExit; } // if (*lpszBegin == '!' && *(lpszBegin + 1) != '-' && *(lpszBegin + 2) != '-') { bExtTag = true; } // // tag names always begin with an alphabet if (!::wiz_isalpha(*lpszBegin) && *lpszBegin != '!') { bClosingTag = (*lpszBegin == _T('/')); if (bClosingTag) lpszBegin = ::wiz_strinc(lpszBegin); else return (0U); } bOpeningTag = !bClosingTag; lpszEnd = lpszBegin; do { // tag name may contain letters (a-z, A-Z), digits (0-9), // underscores '_', hyphen '-', colons ':', and periods '.' // int ch = *lpszEnd; bool validChar = (wiz_isalnum(ch) || ch == '-' || ch == ':' || ch == '_' || ch == '.'); if (!validChar && bExtTag) { validChar = ch == '!' || ch == '[' || ch == ']'; } if (!validChar) { if (lpszEnd == lpszBegin) { return (0U); } // only white-space characters, a null-character, a // greater-than symbol, or a forward-slash can break // a tag name // unsigned short chEnd = *lpszEnd; if (chEnd == 0 || ::wiz_isspace(chEnd) || chEnd == _T('>') || (chEnd == _T('/') && (!bClosingTag)) ) { break; } return (0U); // any other character will fail parsing process } lpszEnd = ::wiz_strinc(lpszEnd); } while(true); // store tag name for later use strTagName = CString(lpszBegin, lpszEnd - lpszBegin); // if (bExtTag) { const unsigned short* p = lpszEnd; lpszEnd = ::wiz_strstr(p, "/>"); if (lpszEnd == NULL) { lpszEnd = ::wiz_strchr(p, '>'); } // if (lpszEnd == NULL) return (0U); } // is this a closing tag? if (bClosingTag) { // in a closing tag, there can be only one symbol after // tag name, i.e., the tag end delimeter '>'. Anything // else will result in parsing failure if (*lpszEnd != _T('>')) return (0U); // skip tag's ending delimeter lpszEnd = ::wiz_strinc(lpszEnd); ATLASSERT(strTagName.GetLength()); ATLASSERT(pcollAttr == NULL); nRetVal = lpszEnd - lpszString; goto LUpdateAndExit; } // tag contains attribute/value pairs? if (*lpszEnd != _T('>')) { lpszBegin = lpszEnd; lpszEnd = NULL; // skip white-space characters after tag name while (::wiz_isspace(*lpszBegin)) lpszBegin = ::wiz_strinc(lpszBegin); nTemp = 0U; if (bParseAttrib) // parse attribute/value pairs? { ATLASSERT(pcollAttr == NULL); // instantiate collection ... pcollAttr = new CWizHtmlAttributes; // ... and delegate parsing process nTemp = pcollAttr->parseFromStr(lpszBegin); } if (nTemp == 0) // attribute/value pair parsing is disabled? // - OR - // attribute/value pairs could not be parsed? { WIZ_SAFE_DELETE_POINTER(pcollAttr); if ((lpszEnd = ::wiz_strstr(lpszBegin, _T("/>"))) == NULL) { if ((lpszEnd = ::wiz_strchr(lpszBegin, _T('>'))) == NULL) return (0U); } } else { lpszEnd = lpszBegin + nTemp; // skip white-space after attribute/value pairs while (::wiz_isspace(*lpszEnd)) lpszEnd = ::wiz_strinc(lpszEnd); // tag's ending delimeter could not be found? if (*lpszEnd == 0) { WIZ_SAFE_DELETE_POINTER(pcollAttr); return (0U); } } // a tag like this one: <BR/> if (*lpszEnd == _T('/')) { ATLASSERT(bOpeningTag); bClosingTag = true; lpszEnd = ::wiz_strinc(lpszEnd); } } // HTML tags always end with a greater-than '>' symbol if (*lpszEnd != _T('>')) { WIZ_SAFE_DELETE_POINTER(pcollAttr); return (0U); } else lpszEnd = ::wiz_strinc(lpszEnd); nRetVal = lpszEnd - lpszString; // ATLASSERT(nRetVal > 0); // goto LUpdateAndExit; // just to show the flow-of-control LUpdateAndExit: strTagName.Trim(); if (nRetVal && bOpeningTag) { if (0 == strTagName.CompareNoCase("script")) { lpszEnd = ::GetScriptSource(lpszEnd, NULL, false); // nRetVal = lpszEnd - lpszString; } else if (0 == strTagName.CompareNoCase("style")) { lpszEnd = ::GetStyleSource(lpszEnd, NULL); // nRetVal = lpszEnd - lpszString; } } m_bIsClosingTag = bIsClosingTag = bClosingTag; m_bIsOpeningTag = bIsOpeningTag = bOpeningTag; m_strTagName = strTagName; m_strTagName.TrimLeft(); m_strTagName.TrimRight(); // just-in-case! m_strTag = CString(lpszString, nRetVal); WIZ_SAFE_DELETE_POINTER(m_pcollAttr); m_pcollAttr = pcollAttr; pcollAttr = NULL; m_bModified = false; return (nRetVal); } CString CWizHtmlTag::getTag(void) { if (isClosing() && !isOpening()) { ATLASSERT(!m_bModified); return m_strTag; } // if (m_bModified) { CString strAttributes; if (m_pcollAttr) { CWizStdStringArray arr; for (int i = 0; i < m_pcollAttr->getCount(); i++) { arr.push_back(m_pcollAttr->getAttribute(i).toString()); } // ::WizStringArrayToText(arr, strAttributes, " "); } m_strTag = WizFormatString2(isClosing() ? "<%1 %2 />" : "<%1 %2>", m_strTagName, strAttributes); m_bModified = false; } // return m_strTag; } void CWizHtmlTag::setValueToName(const CString& strAttributeName, const CString& strValue) { if (!m_pcollAttr) { m_pcollAttr = new CWizHtmlAttributes(); } // m_bModified = true; // m_pcollAttr->setValueToName(strAttributeName, strValue); } void CWizHtmlTag::removeAttribute(const CString& strAttributeName) { if (!m_pcollAttr) return; // m_bModified = true; // m_pcollAttr->removeAttribute(strAttributeName); } ///////////////////////////////////////////////////////////////// CWizHtmlReader::CWizHtmlReader() { m_bResolveEntities = false; // entities are resolved, by default m_dwAppData = 0L; // reasonable default! m_dwBufPos = 0L; // start from the very beginning m_dwBufLen = 0L; // buffer length is unknown yet // default is to raise all of the events m_eventMask = (EventMaskEnum)(notifyStartStop | notifyTagStart | notifyTagEnd | notifyCharacters | notifyComment ); m_pEventHandler = NULL; // no event handler is associated m_lpszBuffer = NULL; } CWizHtmlReader::EventMaskEnum CWizHtmlReader::setEventMask(DWORD dwNewEventMask) { EventMaskEnum oldMask = m_eventMask; m_eventMask = (EventMaskEnum)dwNewEventMask; return (oldMask); } CWizHtmlReader::EventMaskEnum CWizHtmlReader::setEventMask(DWORD addFlags, DWORD removeFlags) { DWORD dwOldMask = (DWORD)m_eventMask; DWORD dwNewMask = (dwOldMask | addFlags) & ~removeFlags; m_eventMask = (EventMaskEnum)dwNewMask; return ((EventMaskEnum)dwOldMask); } DWORD CWizHtmlReader::setAppData(DWORD dwNewAppData) { DWORD dwOldAppData = m_dwAppData; m_dwAppData = dwNewAppData; return (dwOldAppData); } IWizHtmlReaderEvents* CWizHtmlReader::setEventHandler(IWizHtmlReaderEvents* pNewHandler) { IWizHtmlReaderEvents *pOldHandler = m_pEventHandler; m_pEventHandler = pNewHandler; return (pOldHandler); } void CWizHtmlReader::NormalizeCharacters(CString &rCharacters) { //rCharacters.Replace(_T("\r\n"), _T("")); //rCharacters.Remove(_T('\n')); //rCharacters.Replace(_T('\r'), _T(' ')); //rCharacters.Replace(_T('\t'), _T(' ')); UNUSED_ALWAYS(rCharacters); } const unsigned short CWizHtmlReader::ReadChar(void) { ATLASSERT(m_lpszBuffer != NULL); if (m_dwBufPos >= m_dwBufLen) return (NULL); return (m_lpszBuffer[m_dwBufPos++]); } const unsigned short CWizHtmlReader::UngetChar(void) { ATLASSERT(m_lpszBuffer != NULL); ATLASSERT(m_dwBufPos); return (m_lpszBuffer[--m_dwBufPos]); } bool CWizHtmlReader::getEventNotify(DWORD dwEvent) const { ATLASSERT(dwEvent == notifyStartStop || dwEvent == notifyTagStart || dwEvent == notifyTagEnd || dwEvent == notifyCharacters || dwEvent == notifyComment); if (m_pEventHandler == NULL) return (false); return ((m_eventMask & dwEvent) == dwEvent); } bool CWizHtmlReader::getBoolOption(ReaderOptionsEnum option, bool& bCurVal) const { bool bSuccess = false; switch (option) { case resolveEntities: { bCurVal = m_bResolveEntities; bSuccess = true; break; } default: { bSuccess = false; break; } } return (bSuccess); } bool CWizHtmlReader::setBoolOption(ReaderOptionsEnum option, bool bNewVal) { bool bSuccess = false; switch (option) { case resolveEntities: { m_bResolveEntities = bNewVal; bSuccess = true; break; } default: { bSuccess = false; break; } } return (bSuccess); } bool CWizHtmlReader::parseComment(CString &rComment) { ATLASSERT(m_lpszBuffer != NULL); if (m_dwBufPos + 4 >= m_dwBufLen) return false; // HTML comments begin with '<!' delimeter and // are immediately followed by two hyphens '--' if (::wiz_strncmp(&m_lpszBuffer[m_dwBufPos], _T("<!--"), 4)) return (false); const unsigned short* lpszBegin = &m_lpszBuffer[m_dwBufPos + 4]; // HTML comments end with two hyphen symbols '--' const unsigned short* lpszEnd = ::wiz_strstr(lpszBegin, _T("--")); // comment ending delimeter could not be found? if (lpszEnd == NULL) // consider everything after current buffer position a comment { rComment = lpszBegin; m_dwBufPos += (4 + rComment.GetLength()); return (true); } CString strComment(lpszBegin, lpszEnd - lpszBegin); // end of buffer? if (lpszEnd + 2 >= m_lpszBuffer + m_dwBufLen) return (false); // skip white-space characters after comment ending delimeter '--' lpszEnd += 2; while (::wiz_isspace(*lpszEnd)) lpszEnd = ::wiz_strinc(lpszEnd); // comment has not been terminated properly if (*lpszEnd != _T('>')) return (false); lpszEnd = ::wiz_strinc(lpszEnd); m_dwBufPos += (lpszEnd - &m_lpszBuffer[m_dwBufPos]); rComment = strComment; return (true); } bool CWizHtmlReader::parseTag(CWizHtmlTag &rTag, bool &bIsOpeningTag, bool &bIsClosingTag) { ATLASSERT(m_lpszBuffer != NULL); ATLASSERT(m_dwBufPos + 3 <= m_dwBufLen); UINT nRetVal = rTag.parseFromStr(&m_lpszBuffer[m_dwBufPos], bIsOpeningTag, bIsClosingTag); if (!nRetVal) return (false); m_dwBufPos += nRetVal; return (true); } /////////////////////////////////////////////////////////////////////////////////////////////////////// UINT CWizHtmlReader::parseDocument(void) { ATLASSERT(m_lpszBuffer != NULL); bool bAbort = false; // continue parsing or abort? bool bIsClosingTag = false; // tag parsed is a closing tag? bool bIsOpeningTag = false; // tag parsed is an opening tag? CString strCharacters; // character data CString strComment; // comment data DWORD dwCharDataStart = 0L; // starting position of character data DWORD dwCharDataLen = 0L; // length of character data long lTemp = 0L; // temporary storage unsigned short ch = 0; // character at current buffer position CWizHtmlTag oTag; // tag information if ( (!m_lpszBuffer) || (!m_dwBufLen) ) return (0U); // reset seek pointer to beginning ResetSeekPointer(); // notify event handler about parsing startup if (getEventNotify(notifyStartStop)) { bAbort = false; m_pEventHandler->BeginParse(m_dwAppData, bAbort); if (bAbort) goto LEndParse; } // skip leading white-space characters while (isWhiteSpace(ReadChar())) ; ch = UngetChar(); while ((ch = ReadChar()) != 0) { switch (ch) { // tag starting delimeter? case _T('<'): { UngetChar(); // strComment.Empty(); if (!parseComment(strComment)) { bIsOpeningTag = false; bIsClosingTag = false; if (!parseTag(oTag, bIsOpeningTag, bIsClosingTag)) { ++dwCharDataLen; // manually advance buffer position // because the last call to UngetChar() // moved it back one character ch = ReadChar(); break; } } // clear pending notifications if ( (dwCharDataLen) || (strCharacters.GetLength()) ) { strCharacters += CString(&m_lpszBuffer[dwCharDataStart], dwCharDataLen); NormalizeCharacters(strCharacters); if ( (strCharacters.GetLength()) && (getEventNotify(notifyCharacters)) ) { bAbort = false; m_pEventHandler->Characters(strCharacters, m_dwAppData, bAbort); if (bAbort) goto LEndParse; } strCharacters.Empty(); } dwCharDataLen = 0L; dwCharDataStart = m_dwBufPos; if (strComment.GetLength()) { if (getEventNotify(notifyComment)) { bAbort = false; m_pEventHandler->Comment("<!--" + strComment + "-->", m_dwAppData, bAbort); if (bAbort) goto LEndParse; } } else { if ( (bIsOpeningTag) && (getEventNotify(notifyTagStart)) ) { bAbort = false; m_pEventHandler->StartTag(&oTag, m_dwAppData, bAbort); if (bAbort) goto LEndParse; } if ( (bIsClosingTag) && (getEventNotify(notifyTagEnd)) ) { bAbort = false; m_pEventHandler->EndTag(&oTag, m_dwAppData, bAbort); if (bAbort) goto LEndParse; } } break; } // entity reference beginning delimeter? case _T('&'): { UngetChar(); lTemp = 0; if (m_bResolveEntities) lTemp = CWizHtmlEntityResolver::resolveEntity(&m_lpszBuffer[m_dwBufPos], ch); if (lTemp) { strCharacters += CString(&m_lpszBuffer[dwCharDataStart], dwCharDataLen); strCharacters += ch; m_dwBufPos += lTemp; dwCharDataStart = m_dwBufPos; dwCharDataLen = 0L; } else { ch = ReadChar(); ++dwCharDataLen; } break; } // any other character default: { ++dwCharDataLen; break; } } } // clear pending notifications if ( (dwCharDataLen) || (strCharacters.GetLength()) ) { strCharacters += CString(&m_lpszBuffer[dwCharDataStart], dwCharDataLen); strCharacters += ch; NormalizeCharacters(strCharacters); strCharacters.TrimRight(); // explicit trailing white-space removal if ( (strCharacters.GetLength()) && (getEventNotify(notifyCharacters)) ) { bAbort = false; m_pEventHandler->Characters(strCharacters, m_dwAppData, bAbort); if (bAbort) goto LEndParse; } } LEndParse: // notify event handler about parsing completion if (getEventNotify(notifyStartStop)) m_pEventHandler->EndParse(m_dwAppData, bAbort); m_lpszBuffer = NULL; m_dwBufLen = 0L; return (m_dwBufPos); } UINT CWizHtmlReader::Read(const CString& strString) { const unsigned short* lpszString = strString; m_dwBufLen = ::wiz_strlen(lpszString); if (m_dwBufLen) { m_lpszBuffer = lpszString; return (parseDocument()); } return (0U); }
#include "node.h" #include "headers.h" #include <Bits.h> stack<POINT> path; vector<vector<bool>> visit; vector<vector<bool>> close; const Map* loadedMap; struct compare { bool operator()(Node* p1, Node* p2) { return p1->getF() == p2->getF() ? p1->getG() > p2->getG() : p1->getF() > p2->getF(); } }; priority_queue<Node*, vector<Node*>, compare> openNodes; Node* findPath(POINT start, POINT end, int size) { TIMER limitTimer; loadedMap = MapManager::loadedMap; const vector<vector<Node*>>& graph = loadedMap->graph; int i = 0; visit = vector<vector<bool>>(loadedMap->getHeight() / CELL_PIXEL, vector<bool>(loadedMap->getWidth() / CELL_PIXEL, false)); close = vector<vector<bool>>(loadedMap->getHeight() / CELL_PIXEL, vector<bool>(loadedMap->getWidth() / CELL_PIXEL, false)); openNodes = priority_queue<Node*, vector<Node*>, compare>(); graph[start.y][start.x]->setG(0); graph[start.y][start.x]->setH(getDistance(start, end)); graph[start.y][start.x]->setPrev(NULL); Node* nearest = graph[start.y][start.x]; selectNode(start, end, size); while (!openNodes.empty()) { Node* temp = openNodes.top(); openNodes.pop(); selectNode(temp->getPos(), end, size); if (nearest->getH() > temp->getH()) nearest = temp; if (visit[end.y][end.x]) { return graph[end.y][end.x]; } if (limitTimer.getElapsedTime() > 8) break; } return nearest; } void selectNode(POINT pos, POINT end, int size) { close[pos.y][pos.x] = true; updateNode(POINT({ pos.x - 1, pos.y }), end, pos, size); updateNode(POINT({ pos.x + 1, pos.y }), end, pos, size); updateNode(POINT({ pos.x, pos.y - 1 }), end, pos, size); updateNode(POINT({ pos.x, pos.y + 1 }), end, pos, size); updateNode(POINT({ pos.x - 1, pos.y - 1 }), end, pos, size); updateNode(POINT({ pos.x - 1, pos.y + 1 }), end, pos, size); updateNode(POINT({ pos.x + 1, pos.y - 1 }), end, pos, size); updateNode(POINT({ pos.x + 1, pos.y + 1 }), end, pos, size); } void updateNode(POINT pos, POINT end, POINT prev, int size) { const vector<vector<Node*>>& graph = loadedMap->graph; if (pos.x < 0 || pos.y < 0 || pos.x >= loadedMap->cellNx || pos.y >= loadedMap->cellNy) return; if (close[pos.y][pos.x] || loadedMap->isBlock(pos, size)) return; Node temp(pos, getDistance(pos, prev) + graph[prev.y][prev.x]->getG(), getDistance(pos, end), graph[prev.y][prev.x]); if (visit[pos.y][pos.x]) { if (temp > *graph[pos.y][pos.x]) { *graph[pos.y][pos.x] = temp; } } else { visit[pos.y][pos.x] = true; *graph[pos.y][pos.x] = temp; openNodes.push(graph[pos.y][pos.x]); } } int getDistance(POINT p1, POINT p2) { int bx = abs(p1.x - p2.x); int by = abs(p1.y - p2.y); return bx > by ? by * 14 + (bx - by) * 10 : bx * 14 + (by - bx) * 10; } void sortAgain() { priority_queue<Node*, vector<Node*>, compare> temp; while (!openNodes.empty()) { temp.push(openNodes.top()); openNodes.pop(); } openNodes = temp; } void drawPath(HDC& hdc, Node* path) { Graphics g(hdc); while (path) { VECTOR pos = { (float)path->getPos().x , (float)path->getPos().y }; pos = 8 * pos; POINT p = pixelToScreen(pos); g.DrawEllipse(&Pen(Color(255, 0, 0), 3), Rect(p.x - 10, p.y - 10, 20, 20)); path = path->getPrev(); } } void getPath(stack<POINT>& path, POINT start, Node* node) { while (node) { path.push(node->getPos()); node = node->getPrev(); } }
#ifndef __UTILS_H__ #define __UTILS_H__ #include <string> #define ENABLE_MY_POPEN 1 std::string get_exe_path(); bool file_exists(std::string sFilename); int make_directory(std::string sDirName); pid_t popen2(const char *command, int *infp, int *outfp); #ifdef ENABLE_MY_POPEN FILE* _popen(const char* program, register const char* type); int _pclose(FILE* iop); int _pipe_pid(FILE* iop); #endif // ENABLE_MY_POPEN #endif // __UTILS_H__
#pragma once enum RStates { RS_DEFAULT, RS_LINE, RS_CCW, RS_NOCULL, RS_COUNT }; class RasterizerStateManager { public: RasterizerStateManager(void); ~RasterizerStateManager(void); bool ApplyState(RStates eState); ID3D11RasterizerState* GetState(RStates eState) { if (eState < RS_COUNT) return m_pRasterizerStates[eState]; return nullptr; } RStates GetCurrentState(void) { return m_eCurrentState; } private: void CreateStates(void); ID3D11RasterizerState* m_pRasterizerStates[RS_COUNT]; unsigned int m_unStencilRefs[RS_COUNT]; RStates m_eCurrentState; };
// github.com/andy489 #include <iostream> #include <vector> using namespace std; typedef vector<int> vi; #define sz(x) ((int)x.size()) #define F(i, k, n) for(int i=k;i<n;i++) void cs(vi &v) { int N = sz(v); int range = 100000; vi count(range, 0); F(i, 0, N) count[v[i]]++; F(i, 0, range - 1) count[i + 1] += count[i]; vi sorted(N); for (int i = N - 1; i >= 0; i--) { sorted[count[v[i]] - 1] = v[i]; --count[v[i]]; } F(i, 0, N) v[N - i - 1] = sorted[i]; } int main() { ios::sync_with_stdio(false); cin.tie(0); int N; cin >> N; vi col(N); F(i, 0, N) cin >> col[i]; cs(col); for (const auto &el : col) cout << el << ' '; return 0; }
#include "BlendStateDescConstants.h" using namespace GraphicsEngine; D3D11_BLEND_DESC1 BlendStateDescConstants::Default() { D3D11_BLEND_DESC1 blendDesc; blendDesc.AlphaToCoverageEnable = false; blendDesc.IndependentBlendEnable = false; blendDesc.RenderTarget[0].BlendEnable = false; blendDesc.RenderTarget[0].LogicOpEnable = false; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].LogicOp = D3D11_LOGIC_OP_NOOP; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; return blendDesc; } D3D11_BLEND_DESC1 BlendStateDescConstants::Transparent() { auto blendDesc = Default(); blendDesc.AlphaToCoverageEnable = true; blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; return blendDesc; } D3D11_BLEND_DESC1 BlendStateDescConstants::AdditiveBlend() { auto blendDesc = Default(); blendDesc.RenderTarget[0].BlendEnable = true; blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; blendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; blendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; blendDesc.RenderTarget[0].LogicOp = D3D11_LOGIC_OP_NOOP; blendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; return blendDesc; }
/* * -------------------------------------------------------------------------- * THE "BUY-ME-A-BEER LICENSE" (Revision 0.1): * <mattias@allbinary.se> wrote this code. As long as you retain this notice * you can do whatever you want with this stuff. If we meet some day, and you * think my work is worth it (or you think it's worth it anyway), you can buy * me a beer in return. I love beer. * -------------------------------------------------------------------------- */ #ifndef __NODEHEAPNODE_H__ #define __NODEHEAPNODE_H__ 1 class NodeHeapNode { public: NodeHeapNode() {heapIndex=0;}; ~NodeHeapNode() {}; inline virtual unsigned int getPriority() { return 0; }; unsigned int heapIndex; }; #endif
#include<stdio.h> #include<conio.h> void convert(int num,int base) { if(num==0) return; convert(num/base,base); printf("%d ",num%base); } void main() { //int num=0; //float n=0.0f; clrscr(); convert(31999,2); getch(); }
/*题目: 给你一个整数数组 num 。请你返回和为 奇数 的子数组数目。由于答案可能 会很大,请你将结果对 10^9 + 7 取余后返回*/ /*思路:两个计数器odd,even,初始化为0,判断前缀和为奇数的odd++ ,为偶数的even++ ,odd*even+odd即为和为奇数的子数组数目。*/ #include<stdio.h> int main() { int num[3] = {3,2,1}; int odd = 0; int even = 0; int result; int size = sizeof(num)/sizeof(num[0]); long long res = 0; int sum = 0; for (int i = 0;i < size;i++) { sum += num[i]; if (sum % 2 == 0) { even++; } else { odd++; } } result = odd*even+odd; printf("和为 奇数 的子数组数目 = %d ",result%1000000007); }
#ifndef SQUARE_H #define SQUARE_H #include <QLabel> #include <QString> #include <map> typedef std::map<std::string, std::string> StyleMap; class Square : public QLabel { Q_OBJECT public: Square(QWidget* parent=nullptr, int _row=0, int _col=0); void set_color(int _color); int get_color() const; private: void render(); void setStyle(std::string key, std::string value); void applyStyle(); int row, col; int color; StyleMap style; static const int OFFSET_X = 16; static const int OFFSET_Y = 16; static const int SQUARE_WIDTH = 32; static const int SQUARE_HEIGHT = 32; }; #endif // SQUARE_H
#ifndef __CLUCK2SESAME_PLATFORM_POWERMANAGEMENT_POWERMANAGEMENT_INC #define __CLUCK2SESAME_PLATFORM_POWERMANAGEMENT_POWERMANAGEMENT_INC #include "Platform.inc" radix decimal .module POWERMANAGEMENT POWER_FLAG_PREVENTSLEEP equ 0 POWER_FLAG_SLEEPING equ 1 #ifndef __CLUCK2SESAME_PLATFORM_POWERMANAGEMENT_INITIALISE_ASM .externalVariable powerManagementFlags .externalVariable fastClockCount #endif #endif
//Alumno.cpp #include "Alumno.h" ostream& operator<<(ostream& out, Alumno stu){ out << stu.id << " " << stu.nombre.c_str() << " " << stu.promedio << endl; return out; } istream& operator>>(istream& in, Alumno& stu){ in >> stu.id >> stu.nombre >> stu.promedio; return in; } Alumno::Alumno(int id = 0, string nombre = "", double promedio = 0.0){ this->id = id; this->nombre = nombre; this->promedio = promedio; } int Alumno::getId(){ return this->id; } string Alumno::getNombre(){ return this->nombre; } double Alumno::getPromedio(){ return this->promedio; }
#include "header.h" #include <string> #include <iostream> #include <fstream> #include <sstream> #include "json.hpp" #include <stdio.h> using json = nlohmann::json; void output_fiber(SimulationStruct* sim, float *data, char* output) { ofstream myfile; myfile.open(output, ios::app); double scale1 = (double)0xFFFFFFFF * (double)sim->number_of_photons; if (NORMAL) { for (int i = 0; i < sim->num_detector; i++) { myfile << double(data[i] / scale1) << "\t"; } } else { for (int i = 0; i < sim->num_detector; i++) { myfile << double(data[i] / scale1) << " "; } } myfile << endl; myfile.close(); } int read_mua_mus(SimulationStruct** simulations, char* sim_input, char* tissue_input) //Wang modified { // load the simulation parameters and form into json format ifstream inFile; inFile.open(sim_input); stringstream simStrStream; simStrStream << inFile.rdbuf(); string simStr = simStrStream.str(); json sim_input_struct = json::parse(simStr); // read and set the parameters from json file unsigned long long number_of_photons = (unsigned long long)sim_input_struct["number_photons"]; const int n_simulations = sim_input_struct["number_simulation"]; //const int n_simulations =1; bool source_probe_oblique; if (sim_input_struct["source_probe_oblique"] == 1) { source_probe_oblique = true; } else if(sim_input_struct["source_probe_oblique"] == 0) { source_probe_oblique = false; } else { cout << "source_probe_oblique: " << sim_input_struct["source_probe_oblique"] << "is not 1 or 0!\n"; return 0; } bool detector_probe_oblique; if (sim_input_struct["detector_probe_oblique"] == 1) { detector_probe_oblique = true; } else if (sim_input_struct["detector_probe_oblique"] == 0) { detector_probe_oblique = false; } else { cout << "detector_probe_oblique: " << sim_input_struct["detector_probe_oblique"] << "is not 1 or 0!\n"; return 0; } double detector_reflectance = sim_input_struct["detector_reflectance"]; if (detector_reflectance < 0 || detector_reflectance>1) { cout << "Detector reflectance: " << detector_reflectance << " is out of range !\n"; return 0; } int n_layers = sim_input_struct["number_layers"]; if (n_layers > PRESET_NUM_LAYER) { cout << "Number of layer is too large!\nThis program only allow number lower than " << PRESET_NUM_LAYER << " !\n"; return 0; } float upper_n = sim_input_struct["upper_n"]; float lower_n = sim_input_struct["lower_n"]; int num_detector = sim_input_struct["probes"]["num_SDS"]; if (num_detector > PRESET_NUM_DETECTOR) { cout << "Number of SDS is too large!\nThis program only allow number lower than " << PRESET_NUM_DETECTOR << " !\n"; return 0; } if (num_detector != sim_input_struct["probes"]["detectors"].size()) { cout << "Number of SDS : "<<num_detector <<" not match the probe setting : "<< sim_input_struct["probes"]["detectors"].size() <<" !\n"; return 0; } float lower_thickness = 10.0; float start_weight; // init the parameter array // mua for i-th simulation, j-th layer float ** thickness = new float*[n_simulations]; float ** mua = new float*[n_simulations]; float ** mus = new float*[n_simulations]; float ** n = new float*[n_simulations]; float ** g = new float*[n_simulations]; for(int i=0;i<n_simulations;i++) { thickness[i] = new float[n_layers]; mua[i] = new float[n_layers]; mus[i] = new float[n_layers]; n[i] = new float[n_layers]; g[i] = new float[n_layers]; for (int j = 0; j < n_layers; j++) { thickness[i][j] = 0; mua[i][j] = 0; mus[i][j] = 0; n[i][j] = 0; g[i][j] = 0; } } // read tissue parameter fstream myfile; myfile.open(tissue_input); //Wang modified for (int i = 0; i < n_simulations; i++) { // for upper layers int j = 0; // layer index while ( j < n_layers - 1) { myfile >> thickness[i][j] >> mua[i][j] >> mus[i][j] >> n[i][j] >> g[i][j]; j++; } // for the last layer myfile >> mua[i][j] >> mus[i][j] >> n[i][j] >> g[i][j]; // check for input correctness if (mus[i][j] <= 0) { cout << "Mus for simulation " << i << " layer " << j << " Error with value " << mus[i][j] << " !\n"; return 0; } if (n[i][j] <= 1) { cout << "n for simulation " << i << " layer " << j << " Error with value " << n[i][j] << " !\n"; return 0; } if (g[i][j] > 1) { cout << "g for simulation " << i << " layer " << j << " Error with value " << g[i][j] << " !\n"; return 0; } } myfile.close(); // Allocate memory for the SimulationStruct array *simulations = (SimulationStruct*)malloc(sizeof(SimulationStruct)*n_simulations); if (*simulations == NULL) { perror("Failed to malloc simulations.\n"); return 0; }//{printf("Failed to malloc simulations.\n");return 0;} for (int i = 0; i < n_simulations; i++) { (*simulations)[i].source_probe_oblique = source_probe_oblique; (*simulations)[i].detector_probe_oblique = detector_probe_oblique; (*simulations)[i].number_of_photons = number_of_photons; (*simulations)[i].num_layers = n_layers; (*simulations)[i].num_detector = num_detector; (*simulations)[i].detector_reflectance = detector_reflectance; // read probe setting (*simulations)[i].detInfo = new DetectorInfoStruct[num_detector + 1]; // for source (*simulations)[i].detInfo[0].NA = sim_input_struct["probes"]["source"]["NA"]; (*simulations)[i].detInfo[0].raduis = sim_input_struct["probes"]["source"]["radius"]; (*simulations)[i].detInfo[0].position = 0; (*simulations)[i].detInfo[0].angle = float(sim_input_struct["probes"]["source"]["angle"]) * PI / 180; // for detector for (int d = 0; d < num_detector; d++) { (*simulations)[i].detInfo[d + 1].NA = sim_input_struct["probes"]["detectors"][d]["NA"]; (*simulations)[i].detInfo[d + 1].raduis = sim_input_struct["probes"]["detectors"][d]["radius"]; (*simulations)[i].detInfo[d + 1].position = sim_input_struct["probes"]["detectors"][d]["pos"]; (*simulations)[i].detInfo[d + 1].angle = float(sim_input_struct["probes"]["detectors"][d]["angle"]) * PI / 180; } // presetting critical angle for detectors (*simulations)->critical_arr = new float[num_detector + 1]; for (int d = 1; d <= num_detector; d++) { //(*simulations)->critical_arr[d] = asin((*simulations)[i].detInfo[d].NA / n_detector); (*simulations)->critical_arr[d] = asin((*simulations)[i].detInfo[d].NA / upper_n); } // Allocate memory for the layers (including one for the upper and one for the lower) (*simulations)[i].layers = (LayerStruct*)malloc(sizeof(LayerStruct)*(n_layers + 2)); if ((*simulations)[i].layers == NULL) { perror("Failed to malloc layers.\n"); return 0; }//{printf("Failed to malloc simulations.\n");return 0;} // Set upper refractive index (medium) (*simulations)[i].layers[0].n = upper_n; float z_min_cumulate = 0; float z_max_cumulate = 0; // for setting layers for (int l = 1; l <= n_layers; l++) { z_max_cumulate += thickness[i][l-1]; (*simulations)[i].layers[l].n = n[i][l - 1]; (*simulations)[i].layers[l].mua = mua[i][l - 1]; (*simulations)[i].layers[l].g = g[i][l - 1]; (*simulations)[i].layers[l].z_min = z_min_cumulate; (*simulations)[i].layers[l].z_max = z_max_cumulate; (*simulations)[i].layers[l].mutr = 1.0f / (mua[i][l - 1] + mus[i][l - 1]); z_min_cumulate += thickness[i][l - 1]; //cout << "layer " << l << ", mua= " << (*simulations)[i].layers[l].mua << ", z_min=" << (*simulations)[i].layers[l].z_min << ", z_max=" << (*simulations)[i].layers[l].z_max << endl; //system("pause"); } // set the depth of the lower layer if ((*simulations)[i].layers[n_layers].z_max < lower_thickness) { (*simulations)[i].layers[n_layers].z_max = lower_thickness; } // Set lower refractive index (medium) (*simulations)[i].layers[n_layers + 1].n = lower_n; //calculate start_weight double n1 = (*simulations)[i].layers[0].n; double n2 = (*simulations)[i].layers[1].n; double r = (n1 - n2) / (n1 + n2); r = r*r; start_weight = (unsigned int)((double)0xffffffff * (1 - r)); //printf("Start weight=%u\n",start_weight); (*simulations)[i].start_weight = start_weight; } // free the memory for (int i = 0; i<n_simulations; i++) { delete[] thickness[i]; delete[] mua[i]; delete[] mus[i]; delete[] n[i]; delete[] g[i]; } delete[] thickness; delete[] mua; delete[] mus; delete[] n; delete[] g; return n_simulations; } void generate_filename(char *filename, char* prefix, int SDS_number, char* postfix) { // make the output file name //char prefix[100] = "pathlength_SDS_"; //char postfix[10] = ".txt"; string SDS_num = to_string(SDS_number); int i = 0; for (; prefix[i] != '\0'; i++) { filename[i] = prefix[i]; } for (int j = 0; j < SDS_num.length(); j++) { filename[i] = SDS_num[j]; i++; } for (int j = 0; postfix[j] != '\0'; j++) { filename[i] = postfix[j]; i++; } filename[i] = '\0'; } // SDS_to_output: exact number of SDS to output, 1 for SDS1 , 0 for output all SDS void output_SDS_pathlength(SimulationStruct* simulation, float ***pathlength_weight_arr, int *temp_SDS_detect_num, int SDS_to_output, bool do_output_bin) { /*if (SDS_to_output != 0) { cout << "SDS_to_output= " << SDS_to_output << endl; } else { cout << "SDS_to_output= all" << endl; }*/ int start_SDS_index, end_SDS_index; if (SDS_to_output==0){ start_SDS_index = 0; end_SDS_index = simulation->num_detector; } else { start_SDS_index = SDS_to_output - 1; end_SDS_index = SDS_to_output; } for (int s = start_SDS_index; s < end_SDS_index; s++) { char output[100]; if (do_output_bin) { generate_filename(output, "pathlength_SDS_", s + 1, ".bin"); // output the pathlength to binary file FILE* pFile; pFile = fopen(output, "wb"); for (int i = 0; i < temp_SDS_detect_num[s]; i++) { fwrite(pathlength_weight_arr[s][i], sizeof(float), simulation->num_layers + 2, pFile); } fclose(pFile); } else { generate_filename(output, "pathlength_SDS_", s + 1, ".txt"); // output the pathlength to txt file ofstream myfile; myfile.open(output, ios::app); for (int i = 0; i < temp_SDS_detect_num[s]; i++) { for (int j = 0; j <= simulation->num_layers + 1; j++) { myfile << pathlength_weight_arr[s][i][j] << '\t'; } myfile << endl; } myfile.close(); } //cout << "output to: " << output << ", add " << temp_SDS_detect_num[s] << " photons" << endl; temp_SDS_detect_num[s] = 0; } } void output_average_pathlength(SimulationStruct* sim, double *average_PL) { ofstream myfile; myfile.open("average_pathlength.txt", ios::app); for (int s = 0; s < sim->num_detector; s++) { // output the pathlength for (int l = 0; l < sim->num_layers; l++) { myfile << average_PL[s*sim->num_layers + l] << '\t'; } } myfile << endl; myfile.close(); } void output_sim_summary(SimulationStruct* simulation, SummaryStruct sumStruc, bool do_replay) { double scale1 = (double)0xFFFFFFFF * (double)sumStruc.number_of_photons; double sim_speed = 0; ofstream myfile; myfile.open("summary.json", ios::app); myfile << "{\n"; myfile << "\"MCML_version_K\": " << MCML_VERSION << ",\n"; myfile << "\"num_photon\": " << sumStruc.number_of_photons << ",\n"; myfile << "\"sim_time\": " << (double)(sumStruc.time2 - sumStruc.time1) / CLOCKS_PER_SEC << ",\n"; if (do_replay) { myfile << "\"replay_time\": " << (double)(sumStruc.time3 - sumStruc.time2) / CLOCKS_PER_SEC << ",\n"; sim_speed = (double)sumStruc.number_of_photons / ((double)(sumStruc.time3 - sumStruc.time1) / CLOCKS_PER_SEC); } else { sim_speed = (double)sumStruc.number_of_photons / ((double)(sumStruc.time2 - sumStruc.time1) / CLOCKS_PER_SEC); } myfile << "\"sim_speed(photons/s)\": " << sim_speed << ",\n"; myfile << "\"sim_GPU\": \"" << sumStruc.GPU_name << "\",\n"; myfile << "\"each_photon_weight\": " << scale1 << ",\n"; myfile << "\"number_layers\": " << simulation->num_layers << ",\n"; myfile << "\"detect_mode\": "; if (simulation->source_probe_oblique) myfile << "\"fiber\""; else myfile << "\"ring\""; myfile << ",\n"; myfile << "\"num_SDS\": " << simulation->num_detector << ",\n"; myfile << "\"SDS_detected_number\": ["; for (int d = 0; d < simulation->num_detector-1; d++) { myfile << " " << sumStruc.total_SDS_detect_num[d] << " ,"; } myfile << " " << sumStruc.total_SDS_detect_num[simulation->num_detector - 1] << " ]\n"; myfile << "}"; myfile.close(); } void output_A_rz(SimulationStruct* sim, unsigned long long *data, bool do_output_bin) { double scale1 = (double)0xFFFFFFFF * (double)sim->number_of_photons; double scale2; // scale for different r and z for (int s = 0; s < sim->num_detector; s++) { char output[100]; if (do_output_bin) { generate_filename(output, "A_rz_SDS_", s + 1, ".bin"); FILE* pFile; pFile = fopen(output, "wb"); for (int z = 0; z < record_nz; z++) { for (int r = 0; r < record_nr; r++) { // divided by the small grid volume scale2 = scale1 * 2 * PI*(r + 0.5)*record_dr*record_dr*record_dz; float temp_output = float(double(data[s*record_nr*record_nz + z*record_nr + r] / scale2)); fwrite(&temp_output, sizeof(float), 1, pFile); // NOT divided by the small grid volume //myfile << double(data[z*record_nr + r] / scale1) << "\t"; } } fclose(pFile); } else { generate_filename(output, "A_rz_SDS_", s + 1, ".txt"); ofstream myfile; myfile.open(output, ios::app); for (int z = 0; z < record_nz; z++) { for (int r = 0; r < record_nr; r++) { // divided by the small grid volume scale2 = scale1 * 2 * PI*(r + 0.5)*record_dr*record_dr*record_dz; myfile << double(data[s*record_nr*record_nz + z*record_nr + r] / scale2) << "\t"; // NOT divided by the small grid volume //myfile << double(data[z*record_nr + r] / scale1) << "\t"; } myfile << endl; } myfile.close(); } } } void output_A0_z(SimulationStruct* sim, unsigned long long *data, bool do_output_bin) { double scale1 = (double)0xFFFFFFFF * (double)sim->number_of_photons; double scale2 = scale1 * 2 * PI*(0 + 0.5)*record_dr*record_dr*record_dz; // scale for different r and z for (int s = 0; s < sim->num_detector; s++) { char output[100]; if (do_output_bin) { generate_filename(output, "A0_z_SDS_", s + 1, ".bin"); FILE* pFile; pFile = fopen(output, "wb"); for (int z = 0; z < record_nz; z++) { float temp_output = float(double(data[s*record_nz + z] / scale2)); fwrite(&temp_output, sizeof(float), 1, pFile); } fclose(pFile); } else { generate_filename(output, "A0_z_SDS_", s + 1, ".txt"); ofstream myfile; myfile.open(output, ios::app); for (int z = 0; z < record_nz; z++) { myfile << double(data[s*record_nz + z] / scale2) << endl; } myfile.close(); } } } // GPU cores per SM int cuda_version_to_core_count(int ver1, int ver2) { int ver = ver1 * 10 + ver2; if (ver < 20) return 8; else if (ver < 21) return 32; else if (ver < 30)return 48; else if (ver < 40)return 192; // CC 3.X: 192 else if (ver < 50)return 192; else if (ver < 60)return 128; // CC 5.X: 128 else if (ver == 60)return 64; // CC 6.0: 64 else if (ver <= 62)return 128; // CC 6.1, 6.2: 128 else return 128; } // max thread per block int cuda_version_to_block_thread(int ver1, int ver2) { int ver = ver1 * 10 + ver2; if (ver < 30) return 8; else if (ver < 50) return 16; else return 32; } int list_GPU(GPUInfo **info) { int deviceCount, activedev = 0; cudaGetDeviceCount(&deviceCount); if (deviceCount == 0) { cout<<"ERROR: No CUDA-capable GPU device found\n"; return 0; } *info = (GPUInfo *)calloc(deviceCount, sizeof(GPUInfo)); // scan from the first device for (int dev = 0; dev<deviceCount; dev++) { cudaDeviceProp dp; cudaGetDeviceProperties(&dp, dev); strncpy((*info)[dev].name, dp.name, max_GPU_name_length); (*info)[dev].id = dev + 1; (*info)[dev].major = dp.major; (*info)[dev].minor = dp.minor; (*info)[dev].globalmem = dp.totalGlobalMem; (*info)[dev].constmem = dp.totalConstMem; (*info)[dev].sharedmem = dp.sharedMemPerBlock; (*info)[dev].regcount = dp.regsPerBlock; (*info)[dev].clock = dp.clockRate; (*info)[dev].MPs = dp.multiProcessorCount; (*info)[dev].core = dp.multiProcessorCount*cuda_version_to_core_count(dp.major, dp.minor); (*info)[dev].maxMPthread = dp.maxThreadsPerMultiProcessor; (*info)[dev].autothreadpb = cuda_version_to_block_thread(dp.major, dp.minor); (*info)[dev].autoblock = (*info)[dev].maxMPthread / (*info)[dev].autothreadpb; (*info)[dev].autototalthread = (*info)[dev].autoblock * (*info)[dev].autothreadpb * (*info)[dev].MPs; if (strncmp(dp.name, "Device Emulation", 16)) { if (Print_GPU_info) { cout<<"======================= GPU Infomation ==========================\n"; printf("Device %d of %d:\t\t%s\n", (*info)[dev].id, deviceCount, (*info)[dev].name); printf("Compute Capability:\t%u.%u\n", (*info)[dev].major, (*info)[dev].minor); printf("Global Memory:\t\t%u B\nConstant Memory:\t%u B\n" "Shared Memory:\t\t%u B\nRegisters:\t\t%u\nClock Speed:\t\t%.2f GHz\n", (unsigned int)(*info)[dev].globalmem, (unsigned int)(*info)[dev].constmem, (unsigned int)(*info)[dev].sharedmem, (unsigned int)(*info)[dev].regcount, (*info)[dev].clock*1e-6f); printf("Number of MPs:\t\t%u\nNumber of Cores:\t%u\n", (*info)[dev].MPs, (*info)[dev].core); printf("Max Thread per MP:\t%d\nBlock per SM:\t\t%d\nThread per Block:\t%d\nTotal Thread:\t\t%d\n", (*info)[dev].maxMPthread, (*info)[dev].autoblock, (*info)[dev].autothreadpb, (*info)[dev].autototalthread); printf("\n"); } } } return deviceCount; }
#include <stdio.h> int main() { unsigned long long a = 10; printf("%d\n", sizeof(a)); return 0; }
/////////////////////////////////////////////////////////////////// //Copyright 2019-2020 Perekupenko Stanislav. All Rights Reserved.// //@Author Perekupenko Stanislav (stanislavperekupenko@gmail.com) // /////////////////////////////////////////////////////////////////// #include "CPP_FirstPersonCharacter.h" #include "Components/SkeletalMeshComponent.h" #include "Components/CapsuleComponent.h" #include "CPP_ClickInterface.h" #include "SACPPGameModeBase.h" ACPP_FirstPersonCharacter::ACPP_FirstPersonCharacter() { bUseControllerRotationPitch = true; bUseControllerRotationYaw = true; bUseControllerRotationRoll = true; GetMesh()->SetCollisionEnabled(ECollisionEnabled::NoCollision); GetCapsuleComponent()->BodyInstance.SetResponseToAllChannels(ECollisionResponse::ECR_Ignore); GetCapsuleComponent()->BodyInstance.SetResponseToChannel(ECollisionChannel::ECC_WorldStatic, ECollisionResponse::ECR_Block); GetCapsuleComponent()->BodyInstance.SetResponseToChannel(ECollisionChannel::ECC_WorldDynamic, ECollisionResponse::ECR_Block); } void ACPP_FirstPersonCharacter::BeginPlay() { Super::BeginPlay(); PlayerController = GetWorld()->GetFirstPlayerController(); EditorGameMode = Cast<ASACPPGameModeBase>(GetWorld()->GetAuthGameMode()); } void ACPP_FirstPersonCharacter::SetupPlayerInputComponent(UInputComponent* _playerInputComponent) { Super::SetupPlayerInputComponent(_playerInputComponent); InputComponent->BindAction("LeftMouseButton", IE_Pressed, this, &ACPP_FirstPersonCharacter::LeftMouseButtonPressed); InputComponent->BindAction("LeftMouseButton", IE_Released, this, &ACPP_FirstPersonCharacter::LeftMouseButtonReleased); InputComponent->BindAction("RightMouseButton", IE_Pressed, this, &ACPP_FirstPersonCharacter::RightMouseButtonPressed); InputComponent->BindAxis("MoveForward", this, &ACPP_FirstPersonCharacter::MoveForward); InputComponent->BindAxis("MoveRight", this, &ACPP_FirstPersonCharacter::MoveRight); InputComponent->BindAxis("LookUp", this, &ACPP_FirstPersonCharacter::LookUp); InputComponent->BindAxis("Turn", this, &ACPP_FirstPersonCharacter::Turn); InputComponent->BindAction("Touch", IE_DoubleClick, this, &ACPP_FirstPersonCharacter::DoubleTouch); InputComponent->BindAction("Touch", IE_Released, this, &ACPP_FirstPersonCharacter::LeftMouseButtonReleased); InputComponent->BindAction("Touch", IE_Pressed, this, &ACPP_FirstPersonCharacter::TouchPressed); } void ACPP_FirstPersonCharacter::LeftMouseButtonPressed() { FHitResult outHit; if (!(PlayerController->GetHitResultUnderCursorByChannel(UEngineTypes::ConvertToTraceType(ECC_GameTraceChannel2), true, outHit))) { if (PlayerController->GetHitResultUnderCursorByChannel(UEngineTypes::ConvertToTraceType(ECC_Visibility), true, outHit)) { if (outHit.GetActor()) { ICPP_ClickInterface* interface = Cast<ICPP_ClickInterface>(outHit.GetActor()); if (interface) { interface->Execute_LeftMouseClick(outHit.GetActor(), outHit.Location); } } } }else{ MoveEnable = false; } } void ACPP_FirstPersonCharacter::LeftMouseButtonReleased() { MoveEnable = true; if (EditorGameMode) { EditorGameMode->ReleaseGizmo(); } } void ACPP_FirstPersonCharacter::RightMouseButtonPressed() { FHitResult OutHit; if (!(PlayerController->GetHitResultUnderCursorByChannel(UEngineTypes::ConvertToTraceType(ECC_GameTraceChannel2), true, OutHit))) { if (PlayerController->GetHitResultUnderCursorByChannel(UEngineTypes::ConvertToTraceType(ECC_Visibility), true, OutHit)) { if (OutHit.GetActor()) { ICPP_ClickInterface* interface = Cast<ICPP_ClickInterface>(OutHit.GetActor()); if (interface) { interface->Execute_RightMouseClick(OutHit.GetActor(), OutHit.Location); } } } } } void ACPP_FirstPersonCharacter::TouchPressed() { FHitResult outHit; if ((PlayerController->GetHitResultUnderFingerByChannel(ETouchIndex::Touch1, UEngineTypes::ConvertToTraceType(ECC_GameTraceChannel2), true, outHit))) { MoveEnable = false; } } void ACPP_FirstPersonCharacter::DoubleTouch() { FHitResult outHit; if (!(PlayerController->GetHitResultUnderFingerByChannel(ETouchIndex::Touch1, UEngineTypes::ConvertToTraceType(ECC_GameTraceChannel2), true, outHit))) { if (PlayerController->GetHitResultUnderFingerByChannel(ETouchIndex::Touch1, UEngineTypes::ConvertToTraceType(ECC_Visibility), true, outHit)) { if (outHit.GetActor()) { ICPP_ClickInterface* interface = Cast<ICPP_ClickInterface>(outHit.GetActor()); if (interface) { interface->Execute_LeftMouseClick(outHit.GetActor(), outHit.Location); } } } } } void ACPP_FirstPersonCharacter::MoveForward(float _axisValue) { if (MoveEnable) { AddMovementInput(GetActorForwardVector(), _axisValue); } } void ACPP_FirstPersonCharacter::MoveRight(float _axisValue) { if (MoveEnable) { AddMovementInput(GetActorRightVector(), _axisValue); } } void ACPP_FirstPersonCharacter::LookUp(float _axisValue) { if (MoveEnable) { AddControllerPitchInput(_axisValue); } } void ACPP_FirstPersonCharacter::Turn(float _axisValue) { if (MoveEnable) { AddControllerYawInput(_axisValue); } }
///////////////////////////////////////////////////////////////////////////////////////////// // Copyright 2017 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////// #include "ColorUtil.h" float3 HueToRGB(float hue) { float intPart; float fracPart = modf(hue * 6.0f, &intPart); int region = static_cast<int>(intPart); switch (region) { case 0: return float3(1.0f, fracPart, 0.0f); case 1: return float3(1.0f - fracPart, 1.0f, 0.0f); case 2: return float3(0.0f, 1.0f, fracPart); case 3: return float3(0.0f, 1.0f - fracPart, 1.0f); case 4: return float3(fracPart, 0.0f, 1.0f); case 5: return float3(1.0f, 0.0f, 1.0f - fracPart); }; return float3(0.0f, 0.0f, 0.0f); }
#pragma once #include <tudocomp/Compressor.hpp> #include <tudocomp/decompressors/WrapDecompressor.hpp> #include <tudocomp/Literal.hpp> namespace tdc { template<typename coder_t> class LiteralEncoder: public CompressorAndDecompressor { public: inline static Meta meta() { Meta m(Compressor::type_desc(), "encode", "Encodes the input symbol-wise."); m.param("coder", "The output encoder.") .strategy<coder_t>(TypeDesc("coder")); return m; } using CompressorAndDecompressor::CompressorAndDecompressor; inline virtual void compress(Input& input, Output& output) override final { auto iview = input.as_view(); typename coder_t::Encoder coder( config().sub_config("coder"), output, ViewLiterals(iview)); for(uint8_t c : iview) { coder.encode(c, literal_r); } } inline virtual void decompress(Input& input, Output& output) override final { auto ostream = output.as_stream(); typename coder_t::Decoder decoder(config().sub_config("coder"), input); while(!decoder.eof()) { ostream << decoder.template decode<uint8_t>(literal_r); } } inline std::unique_ptr<Decompressor> decompressor() const override { return std::make_unique<WrapDecompressor>(*this); } }; }
// MIDI IN byte matrix_vert1; byte matrix_vert2; void midifeedback () { { // read the incoming byte: if (incomingByte==241){ // this message opens the editor upload mode openeditor= !openeditor; // apri o chiudi la ricezione del preset if (openeditor == 1) // se entri in modalità ricezione porta a zer il counter { editorcounter=0; } else { reset_mempos(); load_preset_base(); // load_preset(0); load_preset(page); // load preset from eerom memory after upload lastbutton[encoder_mempos[0]] = 0; // for(int led = 0; led < 8; led++) { // reset di tutti i led e tutti i banchi toggle // bit_status[4][led]=0; bit_status[5][led]=0; bit_status[0][led]=0; bit_status[1][led]=0; bit_status[2][led]=0; bit_status[3][led]=0; } // all leds and toggles off #if (shifter_active == 1 && stratos == 0) shifter.setAll(0); shifterwrite =0; // spegni fisicamente tutti i leds #endif } } else /////////////////////////// se il messaggio non è un 241 if ( incomingByte>= 128 && incomingByte<= 191 || incomingByte == 224 ) // a partire da note off fino a control change // il resto dei messaggio non viene ricevuto { action=1; type=incomingByte; if (openeditor==0){ byte note_off_case; // se ricevo un note off devo farlo comportare come un note on velocity zero. if (incomingByte < 144 ) note_off_case =16; else note_off_case =0; for(byte ledA = 0; ledA < max_modifiers*2; ledA++) bit_write(2,ledA,(type+note_off_case==(typetable[ledA]))); } } //------------------------------------------------------------------------------------------- else if ( (action==0)&&(note==255) ){ // do nothing action=2; } //------------------------------------------------------------------------------------------- else if ( action==1 && note==255 ) { // wait for the note (databyte) note=incomingByte; if (openeditor==0) for( byte ledA = 0; ledA < max_modifiers*2; ledA++) { if (valuetable[ledA]== note ) bit_write(3,ledA,bit_read(2,ledA)); } } //------------------------------------------------------------------------------------------- else if ( (action==1)&&(note!=255) ){ // ...and then the velocity velocity=incomingByte; if (type < 144 ) velocity = 0 ; //------------------------------------------------------------------------------------------- if ( openeditor == 1 ){ if( type < 208) // fino a tutti i control-change la triade midi viene mandata alla procedura eeprom_write() eeprom_write(); // procedura che contiene le istruzioni per mettere in memoria il dato ricevuto. // else{ // basterà mandare un segnale pitch-bend // il contenuto dei due databyte forma il byte verticale per completare la matrice. // 224 matrix_vert1 = note; matrix_vert2 = velocity; } } //------------------------------------------------------------------------------------------------------------------------------------------------ else { // normali procedure di feedback midi // se openeditor == 0 if (velocity!=0 ) // ricevuto segnale ACCESO { if (type < 160) scale_learn(note); #if (MIDI_thru == 1) if (type < 160) noteOn(type,note,127,0); else noteOn(type,note,velocity,0); // le note vengono sempre sparate fuori al massimo. #endif // bit tables: // 1 - ledstatus 1 e 2 // 2 - feedback_bit1 // 3 - feedback_bit2 // 4 - bit_toggle 1 e 2 for(int ledD = 0; ledD < max_modifiers; ledD++) { // elaborazione led feedback if (valuetable[ledD]==note && bit_read(3,ledD) == 1 && modetable[ledD] < 11 ) { // prima pagina bit_write(1, lightable[ledD]-1, 1); // il led relativo al pulsante (ricevuto) viene memorizzato come acceso old_pitch = 126; // old_pitch viene usato nel filtro anti-doppioni interno alla void NoteOn // (che invia i messagi midi definitivamente) //---------------------------------- if (page==0) { // accendi un led SOLO SE la pagina = 0 if (modetable[ledD] >= 3) offgroup(ledD,0); // offgroup : canale, midiout (1 = manda midi) // se il pulsante è in un gruppo toggle, spengo gli altri pulsanti nel gruppo if ( lightable[ledD] > 0 ) { // se al pulsante è effettivamente associato un led. // 0 = nessun effetto visivo if (valuetable[general_mempos] != 0 ) // nomobo mode { #if (shifter_active == 1 && stratos == 0) ledControl(ledD, 1); #endif } else { #if (shifter_active == 1 && stratos == 0) shifter.setPin(lightable[ledD]-1,1); shifterwrite=1; // il led viene acceso // da notare il "-1" , che serve per allineare la numerazione dell'editor, che parte da 1 #endif #if (Matrix_Pads == 1 ) single_h(matrix_remap[ledD-16],lightable[ledD]-1,1); // visualizzazione simbolino // (quale pad , quale simbolo, positivo o negativo) #endif } } #if (DMX_active == 1 && stratos == 0) DmxSimple.write(dmxtable[ledD], velocity); #endif } { // midi feedback su toggle if (modetable[ledD] >1 && modetable[ledD] < 11) // se il pulsante e' in toggle e togglegroups // { lastbutton[ledD]=0; bit_write(4,ledD,0); } // 4 = toggletable { //lastbutton[ledD]=0; bit_write(4,ledD,1); } else if (modetable[ledD] == 1) // se il pulsante e' button mode semplice { bit_write(4,ledD,1); // 4 = toggletable // lastbutton[ledD] = 0; } } } // nb: lastbutton viene usato in modo diverso per pulsanti o pot! // -------------------------------------------------- if (valuetable[ledD+max_modifiers]==note && bit_read(3,ledD+max_modifiers) == 1 && modetable[ledD+max_modifiers] < 11 ) // feedback solo per i pulsanti { // seconda pagina bit_write(1, lightable[ledD]+max_modifiers-1, 1); // il led relativo al pulsante (ricevuto) viene memorizzato come acceso old_pitch = 126; // old_pitch viene usato nel filtro anti-doppioni interno alla void NoteOn // (che invia i messagi midi definitivamente) //---------------------------------- if (page!=0) { // agisci solo se sei su seconda pagina if (modetable[ledD] >= 3) offgroup(ledD,0); // offgroup : canale, midiout (1 = manda midi) // se il pulsante è in un gruppo toggle, spengo gli altri pulsanti nel gruppo if ( lightable[ledD] > 0 ) { if (valuetable[general_mempos] != 0 ) { // se sei in modalità NOMOBO #if (shifter_active == 1 && stratos == 0) ledControl(ledD, 1); #endif }else{ #if (shifter_active == 1 && stratos == 0) shifter.setPin(lightable[ledD]-1,1); shifterwrite=1; #endif #if (Matrix_Pads == 1 ) single_h(matrix_remap[ledD-16],lightable[ledD]-1,1); // visualizzazione simbolino // (quale pad , quale simbolo, positivo o negativo) #endif } } #if (DMX_active == 1 && stratos == 0) DmxSimple.write(dmxtable[ledD], velocity); #endif } { if (modetable[ledD] >1 && modetable[ledD] < 11) { bit_write(4,ledD+max_modifiers,1); } else if (modetable[ledD] == 1) { bit_write(4,ledD+max_modifiers,1); } } } } } /////////////////////// ////////////////////// --------------------------------------------------------------------------------------------------------------- ///////////////////// if (velocity==0 ){ #if (MIDI_thru == 1) noteOn(type,note,velocity,0); #endif for(int ledE = 0; ledE < max_modifiers; ledE++) { // shifter.setPin(led, ledstatus2[led]); // elaborazione led feedback if (valuetable[ledE]==note && bit_read(3,ledE) ==1 && modetable[ledE] < 11 // il feedback visivo funziona solo per i pulsanti, non per i pot e altro ) { // prima pagina bit_write(1, lightable[ledE]-1, 0); // ledstatus // memorizzo il ledstgatus come spento bit_write(3,ledE,0); // feedback2 if (page==0) { if ( lightable[ledE] > 0 ) { if (valuetable[general_mempos] != 0 ) // nomobo { #if (shifter_active == 1 && stratos == 0) ledControl(ledE, 0); #endif } else { #if (shifter_active == 1 && stratos == 0) shifter.setPin(lightable[ledE]-1,0); shifterwrite=1; #endif #if (Matrix_Pads == 1 ) single_h(matrix_remap[ledE-16],lightable[ledE]-1,0); // visualizzazione simbolino // (quale pad , quale simbolo, positivo o negativo) #endif } } #if (DMX_active == 1 && stratos == 0) DmxSimple.write(dmxtable[ledE], 0); #endif } // gestione toggletable if (modetable[ledE] >1 && modetable[ledE] < 11) // se il pulsante è in toggle o togglegroups { //lastbutton[ledE]=1; // nota: nella void push_button, lastbutton viene portato a zero quando un pulsante e' PREMUTO // - viene abilitato a mandare midiON solo se lastbutton e' 1 bit_write(4,ledE,0); // 4 = toggletable // nota: quando la toggletable (4) e' = 1 , // la pressione del pulsante genera midiout (ved void pushbuttons) } else if (modetable[ledE] == 1) // se il pulsante è in modalità normale { bit_write(4,ledE,0); } } if (valuetable[ledE+max_modifiers]==note && bit_read(3,ledE+max_modifiers) ==1 && modetable [ledE+max_modifiers] <11 ) // feedback solo per pulsanti { // secoda pagina bit_write(1, lightable[ledE]+max_modifiers-1, 0); bit_write(3,ledE+max_modifiers,0); if (page!=0) { // spegni le luci solo se sei sulla seconda pagina if ( lightable[ledE] > 0 ) { // se il pulsante ha un led associato // 0 = nessun led if (valuetable[general_mempos] != 0 ) { #if (shifter_active == 1 && stratos == 0) ledControl(ledE, 0); #endif } else { #if (shifter_active == 1 && stratos == 0) shifter.setPin(lightable[ledE]-1,0); shifterwrite=1; #endif #if (Matrix_Pads == 1 ) single_h(matrix_remap[ledE-16],lightable[ledE]-1,0); // visualizzazione simbolino // (quale pad , quale simbolo, positivo o negativo) #endif } } #if (DMX_active == 1 && stratos == 0) DmxSimple.write(dmxtable[ledE], 0); #endif } if (modetable[ledE] >1 && modetable[ledE] < 11) { lastbutton[ledE]=1; bit_write(4,ledE+max_modifiers,0); } else if (modetable[ledE] == 1) { bit_write(4,ledE+max_modifiers,0); } } } } } note=255; // out of range (0,127) value action=0; } else{ // nothing } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void reset_mempos () { mouse_mempos =0; encoder_mempos[0]=0; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void eeprom_write() { { if (type <160) { editorcounter = 0; #if (shifter_active == 1 && stratos == 0) if (valuetable[general_mempos] == 0 ) {shifter.setAll(HIGH); shifter.write(); delay(5); shifter.setAll(LOW); shifter.write(); } #endif } // ________________________________________________________________________________________________________________ // i messaggi vengono posizionati in eeprom in tale ordine: // 0-65 = type 512 - 2nd page // 64-128 = value 576 - 2nd page // 128-192 = toggle mode 640 - 2nd page // 192-256 = DMX 704 - 2nd page // 256-320 = min 768 - 2nd page // 320-384 = max 832 - 2nd page // 384-448 = nel korova viene memorizzatoo il keyboard 896 // 448-512 led 960 - 2nd page // pz g matt 15 switch (editorcounter) { case 0 : //////////////////////////////////////////////////////////////////////////////////// NOTE - MEMORYPOSITION if ( velocity < 56 ) memoryposition = remapper(velocity); else if ( velocity < 64 ) memoryposition = velocity; else if ( velocity < 120 )memoryposition = remapper(velocity); else memoryposition = velocity; if (memoryposition < 64) { if (matrix_vert1 > 0 ) { bitWrite(note,7,bitRead(matrix_vert1,0)); } // { bitWrite(note,7,1); } EEPROM.write(memoryposition+64,note); // value - valuetable[] - pitch della nota }else{ EEPROM.write(memoryposition+512+64-64,note); // value 2nd // ATTENZIONE: c'è un -64 che serve per compensare la numerazione memoryposition 2nd page } break; case 1 : //////////////////////////////////////////////////////////////////////////////////////////// MIN - MAX if (memoryposition < 64) { if (matrix_vert1 > 0 ) { bitWrite(note,7,bitRead(matrix_vert1,1)); bitWrite(velocity,7,bitRead(matrix_vert1,2)); } EEPROM.write(memoryposition+320,note); // max // maxvalue[] // soglia minima della escursione del byte2 nel messaggio midi EEPROM.write(memoryposition+256,velocity); // min // minvalue[] // soglia massima della escursione del byte2 nel messaggio midi } else{ EEPROM.write(memoryposition+512+320-64,note); // max 2nd EEPROM.write(memoryposition+512+256-64,velocity); // min 2nd } // ATTENZIONE: c'è un -64 che serve per compensare la numerazione memoryposition 2nd page break; case 2 : ///////////////////////////////////////////////////////////////////////////////////////// MODE - DMX if (memoryposition < 64) { if (matrix_vert2 > 0 ) { // bitWrite(note,7,bitRead(matrix_vert1,4)); bitWrite(velocity,7,bitRead(matrix_vert2,0)); } EEPROM.write(memoryposition+128,note); // MODE // modetable[] // modalità di funzionamento del modificatore. es: button, pot, toggle, groups, page etc... //bitWrite(velocity,7,1); EEPROM.write(memoryposition+192,velocity); // dmx // dmxtable[] // canale dmx - nota: l'escursione dmx è 0-127 ma moltiplicata per 2, quindi 0-255. } else{ EEPROM.write(memoryposition+128+512-64,note); // MODE 2ND EEPROM.write(memoryposition+192+512-64,velocity); // dmx 2nd } // ATTENZIONE: c'è un -64 che serve per compensare la numerazione memoryposition 2nd page break; case 3 : ////////////////////////////////////////////////////////////////////////////////////// keyboard - miditype if (memoryposition < 64) { if (matrix_vert2 > 0 ) { // bitWrite(note,7,bitRead(matrix_vert1,4)); bitWrite(note,7,bitRead(matrix_vert2,1)); } EEPROM.write(memoryposition,type-176+(velocity*16)+144); // TYPE // typetable[] // // note: velocity = miditype proveniente dall'editor numerato da 0 a 6 - viene moltiplicato per 16 e sistemato da 144 in poi a seconda del canale // type contiene ovviamente anche l'informazione del canale midi 0-16 EEPROM.write(memoryposition+384,note); // qwerty // qwertyvalue[] // =  memorizzato a partire dalla posizione 384 } else{ EEPROM.write(memoryposition+512-64,type-176+(velocity*16)+144); // type 2nd EEPROM.write(memoryposition+384+512-64,note); // trying not to cross memory limit - qwertyvalue stored 64 memory slots before } // ATTENZIONE: c'è un -64 che serve per compensare la numerazione memoryposition 2nd page break; case 4 : //////////////////////////////////////////////////////////////////////////////////////// LED - / if (memoryposition < 64) { EEPROM.write(memoryposition+448,note); // LED // lightable[] // il dato viene memorizzato solo sulla prima pagina } else{ EEPROM.write(memoryposition+512-64+448,note); } // ATTENZIONE: c'è un -64 che serve per compensare la numerazione memoryposition 2nd page break; case 5 : /////////////////////////////////////////////////////////////////////////////////////////////// if (memoryposition < 64) { if (matrix_vert1 > 0 ) { bitWrite(note,7,bitRead(matrix_vert1,3)); } if (matrix_vert2 > 0 ) { bitWrite(velocity,7,bitRead(matrix_vert2,2));} EEPROM.write(memoryposition+128,note); // User_byte_1 - modetable[] EEPROM.write(memoryposition,velocity); // User_byte_2 - typetable[] } else{ EEPROM.write(memoryposition+512-64+128,note); // User_byte_5 - modetable[] EEPROM.write(memoryposition+512-64,velocity); // User_byte_6 - typetable[] } // ATTENZIONE: c'è un -64 che serve per compensare la numerazione memoryposition 2nd page break; case 6 : /////////////////////////////////////////////////////////////////////////////////////////////////////////// if (memoryposition < 64) { if (matrix_vert2 > 0 ) { // bitWrite(note,7,bitRead(matrix_vert1,4)); bitWrite(note,7,bitRead(matrix_vert2,3)); } EEPROM.write(memoryposition+448,note); // User_byte_3 - lightable[] // EEPROM.write(memoryposition+448,velocity); // User_byte_4 - riga verticale } else{ EEPROM.write(memoryposition+512-64+448,note); // User_byte_7 - lightable[] // EEPROM.write(memoryposition+512+448,velocity); // User_byte_8 - riga verticale } // ATTENZIONE: c'è un -64 che serve per compensare la numerazione memoryposition 2nd page matrix_vert1 = 0; matrix_vert2 = 0; break; } editorcounter++; /* if (editorcounter > 4){ editorcounter = 0; #if (shifter_active == 1 && stratos == 0) if (valuetable[general_mempos] == 0 ) {shifter.setAll(HIGH); shifter.write(); delay(5); shifter.setAll(LOW); shifter.write(); } #endif } */ } }
#ifndef KB_LDR_h #define KB_LDR_h #include <Arduino.h> #include <Wire.h> #define LDR_PIN 36 //#define high_light 0 //#define low_light 1 class KB_LDR { public: void begin(void); uint16_t mapLDR(); uint16_t mapLDRinvert(); uint16_t mapLDRlux(); float getLDR(); float adc_read(); void LuxSetGain(uint8_t G); uint16_t LuxLowGain(); uint16_t LuxHighGain(); uint16_t LuxRead(); protected: float ldr; private: //float adc_offset; //uint8_t ldr_gain_new = low_light, ldr_gain_prev = low_light; float swldr = 600; uint8_t currentGain; //uint8_t G =1; //start high gain }; #endif /* KB_LDR_h */
#include <bits/stdc++.h> using namespace std; const int MAX_INT = std::numeric_limits<int>::max(); const int MIN_INT = std::numeric_limits<int>::min(); const int INF = 1000000000; const int NEG_INF = -1000000000; #define max(a,b)(a>b?a:b) #define min(a,b)(a<b?a:b) #define MEM(arr,val)memset(arr,val, sizeof arr) #define PI acos(0)*2.0 #define eps 1.0e-9 #define are_equal(a,b)fabs(a-b)<eps #define LS(b)(b& (-b)) // Least significant bit #define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians typedef long long ll; typedef pair<int,int> ii; typedef pair<int,char> ic; typedef pair<long,char> lc; typedef vector<int> vi; typedef vector<ii> vii; int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);} int lcm(int a,int b){return a*(b/gcd(a,b));} int n, m, s = 1, t, x, y, z; int main(){ scanf("%d %d", &n, &m); t = n; vector<vii> adj(n+1, vii()); for (int i = 0; i < m; i++){ scanf("%d %d %d", &x, &y, &z); adj[x].push_back(ii(y, z)); adj[y].push_back(ii(x, z)); } vector<vii> paths(n+1, vii()); vi dist(V, INF); dist[s] = 0; queue<int> q; q.push(s); vi p; // addition: the predecessor/parent vector while (!q.empty()){ int u = q.front(); q.pop(); for (int j = 0; j < (int)adj[u].size(); j++){ ii v = adj[u][j]; //all outgoing edges from u if (dist[v.first] == INF){ dist[v.first] = dist[u] + 1; paths[v.first].push_back(ii(u, z)); p[v.first] = u; //addition: the parent of vertex v.first is u q.push(v.first); } else if (dist[v.first] == dist[u] + 1) paths[v.first].push_back(ii(u, z)); } } }
int ledPin = 2; void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); while (! Serial); Serial.println("Enter On to turn on the LED!"); } void loop(){ if (Serial.available()){ char ch = Serial.read(); if (ch == 'a'){ digitalWrite(ledPin, HIGH); Serial.println("You have turned on the LED!"); Serial.println("Enter Off to turn off the LED!"); } if (ch == 'b'){ digitalWrite(ledPin, LOW); Serial.println("You have turned off the LED!"); Serial.println("Enter On to turn on the LED!"); } } }
/* * SPDX-FileCopyrightText: (C) 2019-2022 Matthias Fehring <mf@huessenbergnetz.de> * SPDX-License-Identifier: BSD-3-Clause */ #include "validatorcharnotallowed_p.h" using namespace Cutelyst; ValidatorCharNotAllowed::ValidatorCharNotAllowed(const QString &field, const QString &forbiddenChars, const ValidatorMessages &messages, const QString &defValKey) : ValidatorRule(*new ValidatorCharNotAllowedPrivate(field, forbiddenChars, messages, defValKey)) { } ValidatorCharNotAllowed::~ValidatorCharNotAllowed() { } bool ValidatorCharNotAllowed::validate(const QString &value, const QString &forbiddenChars, QChar *foundChar) { bool valid = true; for (const QChar &forbiddenChar : forbiddenChars) { if (value.contains(forbiddenChar)) { valid = false; if (foundChar) { *foundChar = forbiddenChar; } break; } } return valid; } ValidatorReturnType ValidatorCharNotAllowed::validate(Context *c, const ParamsMultiMap &params) const { ValidatorReturnType result; Q_D(const ValidatorCharNotAllowed); const QString v = value(params); if (!v.isEmpty()) { if (Q_LIKELY(!d->forbiddenChars.isEmpty())) { QChar foundChar; if (Q_LIKELY(ValidatorCharNotAllowed::validate(v, d->forbiddenChars, &foundChar))) { result.value.setValue(v); } else { result.errorMessage = validationError(c, foundChar); } } else { qCWarning(C_VALIDATOR) << "ValidatorCharNotAllowed: Empty validation data for field" << field() << "at" << c->controllerName() << "::" << c->actionName(); result.errorMessage = validationDataError(c); } } else { defaultValue(c, &result, "ValidatorCharNotAllowed"); } return result; } QString ValidatorCharNotAllowed::genericValidationError(Context *c, const QVariant &errorData) const { QString error; const QChar foundChar = errorData.toChar(); Q_D(const ValidatorCharNotAllowed); const QString _label = label(c); if (_label.isEmpty()) { error = c->translate("Cutelyst::ValidatorCharNotAllowed", "Must not contain the following characters: “%1”. But contains the following illegal character: “%2”.").arg(d->forbiddenChars, QString(foundChar)); } else { error = c->translate("Cutelyst::ValidatorCharNotAllowed", "The text in the “%1“ field must not contain the following characters: “%2“. But contains the following illegal character: “%3”.").arg(_label, d->forbiddenChars, QString(foundChar)); } return error; } QString ValidatorCharNotAllowed::genericValidationDataError(Context *c, const QVariant &errorData) const { QString error; Q_UNUSED(errorData) const QString _label = label(c); if (_label.isEmpty()) { error = c->translate("Cutelyst::ValidatorCharNotAllowed", "The list of illegal characters for this field is empty."); } else { error = c->translate("Cutelyst::ValidatorCharNotAllowed", "The list of illegal characters for the “%1“ field is empty.").arg(_label); } return error; }
// // ResourceManager.cpp // Boids // // Created by Yanjie Chen on 3/2/15. // // #include "ResourceManager.h" #include "../constant/BoidsConstant.h" #include "../Utils.h" #include "../ArmatureManager.h" #include "cocostudio/CocoStudio.h" #include "../data/PlayerInfo.h" #include "external/json/document.h" #include "../util/CocosUtils.h" #define EQUIP_CONFIG_FILE "equip" #define TALENT_CONFIG_FILE "talent" #define BULLET_CONFIG_FILE "bullet" #define ITEM_CONFIG_FILE "item" #define LEVEL_CONFIG_FILE "level" #define PLAYER_INFO_CONFIG_FILE "player_info" #define SKILL_CONFIG_FILE "skill_conf" #define SKILL_UPGRADE_COST_CONFIG_FILE "skill_upgrade_cost" #define TEAM_LEVEL_EXP_CONFIG_FILE "team_level_exp" #define TEAM_SKILL_EXP_CONFIG_FILE "team_skill_exp_conf" #define TOWER_CONFIG_FILE "tower" #define UNIT_CONFIG_FILE "unit" #define UPGRADE_COST_CONFIG_FILE "upgrade_cost" #define DROP_CONFIG_FILE "drop" using namespace cocos2d; ResourceManager* ResourceManager::_instance = nullptr; ResourceManager::ResourceManager() { } ResourceManager::~ResourceManager() { } ResourceManager* ResourceManager::getInstance() { if( _instance == nullptr ) { _instance = new ResourceManager(); } return _instance; } void ResourceManager::destroy() { if( _instance ) { delete _instance; _instance = nullptr; } } void ResourceManager::loadMap( MapData* map_data ) { const ValueMap& meta_json = map_data->getMetaJson(); const ValueVector& unit_names = meta_json.at( "units" ).asValueVector(); this->loadUnitArmatures( unit_names ); const ValueVector& player_unit_names = PlayerInfo::getInstance()->getPlayerDeployedUnitNames(); this->loadUnitArmatures( player_unit_names ); } void ResourceManager::purgeMap( MapData* map_data ) { const ValueMap& meta_json = map_data->getMetaJson(); const ValueVector& unit_names = meta_json.at( "units" ).asValueVector(); this->purgeUnitArmatures( unit_names ); const ValueVector& player_unit_names = PlayerInfo::getInstance()->getPlayerDeployedUnitNames(); this->purgeUnitArmatures( player_unit_names ); } void ResourceManager::loadAllData() { this->loadDefaultData(); this->loadGameConfig(); this->loadUnitData(); this->loadTalentData(); this->loadEquipData(); this->loadTowerData(); this->loadUnitLevelupCostData(); this->loadBulletData(); this->loadCenterData(); // this->loadBuildingData(); this->loadBattleUIData(); this->loadLevelData(); this->loadSkillData(); this->loadSkillUpgradeCostData(); this->loadTeamLevelExpData(); this->loadDropData(); } void ResourceManager::loadDefaultData() { } void ResourceManager::unloadDefaultData() { SpriteFrameCache* frame_cache = SpriteFrameCache::getInstance(); frame_cache->removeSpriteFrames(); Director::getInstance()->getTextureCache()->removeAllTextures(); // frame_cache->removeUnusedSpriteFrames(); } void ResourceManager::loadOpenningResource() { SpriteFrameCache* frame_cache = SpriteFrameCache::getInstance(); frame_cache->addSpriteFramesWithFile( "ui/page/ui_movie1.plist", "ui/page/ui_movie1.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_movie2.plist", "ui/page/ui_movie2.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_movie3.plist", "ui/page/ui_movie3.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_movie4.plist", "ui/page/ui_movie4.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_movie5.plist", "ui/page/ui_movie5.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_movie67.plist", "ui/page/ui_movie67.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_movie8.plist", "ui/page/ui_movie8.png" ); } void ResourceManager::unloadOpenningResource() { SpriteFrameCache* frame_cache = SpriteFrameCache::getInstance(); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_movie1.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_movie2.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_movie3.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_movie4.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_movie5.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_movie6.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_movie7.plist" ); } void ResourceManager::loadUIResource() { SpriteFrameCache* frame_cache = SpriteFrameCache::getInstance(); frame_cache->addSpriteFramesWithFile( "ui/page/ui_common.plist", "ui/page/ui_common.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_win_lose_page.plist", "ui/page/ui_win_lose_page.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_battle.plist", "ui/page/ui_battle.png" ); // frame_cache->addSpriteFramesWithFile( "ui/page/ui_popup.plist", "ui/page/ui_popup.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_hero_detail.plist", "ui/page/ui_hero_detail.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_hero_manage.plist", "ui/page/ui_hero_manage.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_home.plist", "ui/page/ui_home.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_talent.plist", "ui/page/ui_talent.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_skill_icon.plist", "ui/page/ui_skill_icon.png" ); frame_cache->addSpriteFramesWithFile( "ui/ui_hero_p.plist", "ui/ui_hero_p.png" ); frame_cache->addSpriteFramesWithFile( "ui/ui_hero_f.plist", "ui/ui_hero_f.png" ); frame_cache->addSpriteFramesWithFile( "ui/ui_equip_icon.plist", "ui/ui_equip_icon.png" ); frame_cache->addSpriteFramesWithFile( "ui/map_common.plist", "ui/map_common.png" ); frame_cache->addSpriteFramesWithFile( "ui/ui_battle_hint.plist", "ui_battle_hint.png" ); } void ResourceManager::unloadUIResource() { SpriteFrameCache* frame_cache = SpriteFrameCache::getInstance(); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_common.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_win_lose_page.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_battle.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_hero_detail.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_hero_manage.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_home.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_talent.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_skill_icon.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/ui_hero_p.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/ui_hero_f.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/ui_equip_icon.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/map_common.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/ui_battle_hint.plist" ); } void ResourceManager::loadBattleResource() { SpriteFrameCache* frame_cache = SpriteFrameCache::getInstance(); frame_cache->addSpriteFramesWithFile( "ui/ui_battle_hint.plist", "ui/ui_battle_hint.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_win_lose_page.plist", "ui/page/ui_win_lose_page.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_common.plist", "ui/page/ui_common.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_pause.plist", "ui/page/ui_pause.png" ); frame_cache->addSpriteFramesWithFile( "ui/page/ui_battle.plist", "ui/page/ui_battle.png" ); frame_cache->addSpriteFramesWithFile( "ui/ui_equip_icon.plist", "ui/ui_equip_icon.png" ); frame_cache->addSpriteFramesWithFile( "ui/ui_equip_drop.plist", "ui/ui_equip_drop.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/base_terrain.plist", "maps/map_images/base_terrain.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/building_1.plist", "maps/map_images/building_1.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/building_2.plist", "maps/map_images/building_2.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/building_3.plist", "maps/map_images/building_3.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/building_4.plist", "maps/map_images/building_4.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/decoration_1.plist", "maps/map_images/decoration_1.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/decoration_2.plist", "maps/map_images/decoration_2.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/decoration_3.plist", "maps/map_images/decoration_3.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/obstacle_1.plist", "maps/map_images/obstacle_1.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/terrain_0.plist", "maps/map_images/terrain_0.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/terrain_1.plist", "maps/map_images/terrain_1.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/terrain_2.plist", "maps/map_images/terrain_2.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/terrain_3.plist", "maps/map_images/terrain_3.png" ); frame_cache->addSpriteFramesWithFile( "maps/map_images/towers.plist", "maps/map_images/towers.png" ); frame_cache->addSpriteFramesWithFile( "ui/map_common.plist", "ui/map_common.png" ); frame_cache->addSpriteFramesWithFile( "ui/hero_avatars.plist", "ui/hero_avatars.png" ); frame_cache->addSpriteFramesWithFile( "ui/ui_boss_avatar.plist", "ui/ui_boss_avatar.png" ); frame_cache->addSpriteFramesWithFile( "effects/bullets/bullets.plist", "effects/bullets/bullets.png" ); frame_cache->addSpriteFramesWithFile( "effects/fx_unit_common.plist", "effects/fx_unit_common.png" ); } void ResourceManager::unloadBattleResource() { SpriteFrameCache* frame_cache = SpriteFrameCache::getInstance(); frame_cache->removeSpriteFramesFromFile( "ui/ui_battle_hint.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_win_lose_page.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_common.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/page/ui_pause.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/ui_equip_drop.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/ui_equip_icon.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/base_terrain.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/building_1.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/building_2.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/building_3.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/building_4.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/decoration_1.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/decoration_2.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/decoration_3.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/obstacle_1.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/terrain_0.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/terrain_1.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/terrain_2.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/terrain_3.plist" ); frame_cache->removeSpriteFramesFromFile( "maps/map_images/towers.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/map_common.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/hero_avatars.plist" ); frame_cache->removeSpriteFramesFromFile( "ui/ui_boss_avatar.plist" ); frame_cache->removeSpriteFramesFromFile( "effects/bullets/bullets.plist" ); frame_cache->removeSpriteFramesFromFile( "effects/fx_unit_common.plist" ); } void ResourceManager::loadGameConfig() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "config.json" ); rapidjson::Document config_json; config_json.Parse<0>( data_string.c_str() ); _game_config = CocosUtils::jsonObjectToValueMap( config_json ); } void ResourceManager::loadUnitData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "unit.json" ); rapidjson::Document unit_config_json; unit_config_json.Parse<0>( data_string.c_str() ); _unit_config = CocosUtils::jsonObjectToValueMap( unit_config_json ); } void ResourceManager::loadTalentData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "talent.json" ); rapidjson::Document config_json; config_json.Parse<0>( data_string.c_str() ); _talent_config = CocosUtils::jsonObjectToValueMap( config_json ); } void ResourceManager::loadEquipData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "equip.json" ); rapidjson::Document equip_config_json; equip_config_json.Parse<0>( data_string.c_str() ); _equip_config = CocosUtils::jsonObjectToValueMap( equip_config_json ); } void ResourceManager::loadTowerData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "tower.json" ); rapidjson::Document tower_config_json; tower_config_json.Parse<0>( data_string.c_str() ); _tower_config = CocosUtils::jsonObjectToValueMap( tower_config_json ); } void ResourceManager::loadUnitLevelupCostData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "upgrade_cost.json" ); rapidjson::Document unit_levelup_cost_config_json; unit_levelup_cost_config_json.Parse<0>( data_string.c_str() ); _unit_levelup_cost_config = CocosUtils::jsonObjectToValueMap( unit_levelup_cost_config_json ); } void ResourceManager::loadBulletData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "bullet.json" ); rapidjson::Document bullet_config_json; bullet_config_json.Parse<0>( data_string.c_str() ); _bullet_config = CocosUtils::jsonObjectToValueMap( bullet_config_json ); } void ResourceManager::loadCenterData() { // std::string data_string = FileUtils::getInstance()->getStringFromFile( "vision_center.json" ); // rapidjson::Document vision_config_json; // vision_config_json.Parse<0>( data_string.c_str() ); // _vision_config = CocosUtils::jsonObjectToValueMap( vision_config_json ); } void ResourceManager::loadBuildingData() { // std::string data_string = FileUtils::getInstance()->getStringFromFile( "building.json" ); // rapidjson::Document building_config_json; // building_config_json.Parse<0>( data_string.c_str() ); // _building_config = CocosUtils::jsonObjectToValueMap( building_config_json ); } void ResourceManager::loadBattleUIData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "item.json" ); rapidjson::Document battle_ui_config_json; battle_ui_config_json.Parse<0>( data_string.c_str() ); _battle_ui_config = CocosUtils::jsonObjectToValueMap( battle_ui_config_json ); } void ResourceManager::loadSkillData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "skill_conf.json" ); rapidjson::Document skill_config_json; skill_config_json.Parse<0>( data_string.c_str() ); _skill_config = CocosUtils::jsonObjectToValueMap( skill_config_json ); } void ResourceManager::loadSkillUpgradeCostData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "skill_upgrade_cost.json" ); rapidjson::Document config_json; config_json.Parse<0>( data_string.c_str() ); _skill_upgrade_cost_config = CocosUtils::jsonObjectToValueMap( config_json ); } void ResourceManager::loadTeamLevelExpData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "team_level_exp.json" ); rapidjson::Document level_exp_config_json; level_exp_config_json.Parse<0>( data_string.c_str() ); _team_level_exp_config = CocosUtils::jsonObjectToValueMap( level_exp_config_json ); } void ResourceManager::loadTeamSkillExpData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( "team_skill_exp_conf.json" ); rapidjson::Document team_skill_exp_config_json; team_skill_exp_config_json.Parse<0>( data_string.c_str() ); _team_skill_exp_config = CocosUtils::jsonObjectToValueMap( team_skill_exp_config_json ); } void ResourceManager::loadDropData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( std::string( DROP_CONFIG_FILE ) + ".json" ); rapidjson::Document config_json; config_json.Parse<0>( data_string.c_str() ); _drop_config = CocosUtils::jsonObjectToValueMap( config_json ); } void ResourceManager::loadLevelData() { FileUtils* file_util = FileUtils::getInstance(); std::string data_string = file_util->getStringFromFile( std::string( LEVEL_CONFIG_FILE ) + ".json" ); rapidjson::Document config_json; config_json.Parse<0>( data_string.c_str() ); _level_config = CocosUtils::jsonObjectToValueMap( config_json ); } void ResourceManager::loadUnitEffects() { SpriteFrameCache::getInstance()->addSpriteFramesWithFile( "effects/fx_unit_common.plist", "effects/fx_unit_common.png" ); Animation* animation = this->createAnimation( UNIT_BLEED, 5, 0.04, 1 ); AnimationCache::getInstance()->addAnimation( animation, UNIT_BLEED ); } void ResourceManager::loadBulletArmature( const std::string& name, const std::string& type ) { if( type == "spine" ) { std::string path = Utils::stringFormat( "effects/bullets/%s", name.c_str() ); ArmatureManager::getInstance()->loadArmatureData( path ); } else if( type == "cocos" ) { std::string path = Utils::stringFormat( "effects/bullets/%s/skeleton.ExportJson", name.c_str() ); cocostudio::ArmatureDataManager::getInstance()->addArmatureFileInfo( path ); } } void ResourceManager::purgeBulletArmature( const std::string& name, const std::string& type ) { if( type == "spine" ) { std::string path = Utils::stringFormat( "effects/bullets/%s", name.c_str() ); ArmatureManager::getInstance()->unloadArmatureData( path ); } else if( type == "cocos" ) { std::string path = Utils::stringFormat( "effects/bullets/%s/skeleton.ExportJson", name.c_str() ); cocostudio::ArmatureDataManager::getInstance()->removeArmatureFileInfo( path ); } } const cocos2d::ValueMap& ResourceManager::getUnitData( const std::string& name ) { return _unit_config.at( name ).asValueMap(); } const cocos2d::ValueMap& ResourceManager::getEquipData( const std::string& equip_id ) { return _equip_config.at( equip_id ).asValueMap(); } const cocos2d::ValueMap& ResourceManager::getTowerData( const std::string& name ) { return _tower_config.at( name ).asValueMap(); } const cocos2d::ValueMap& ResourceManager::getBulletData( const std::string& name ) { return _bullet_config.at( name ).asValueMap(); } const ValueMap& ResourceManager::getSkillData( const std::string& name ) { return _skill_config.at( name ).asValueMap(); } int ResourceManager::getUnitPrice( const std::string& name ) { auto itr = _unit_levelup_cost_config.find( name ); if( itr != _unit_levelup_cost_config.end() ) { return itr->second.asValueMap().at( "price" ).asInt(); } return -1; } int ResourceManager::getSkillUpgradeCost( const std::string& name, int level ) { auto itr = _skill_upgrade_cost_config.find( name ); if( itr != _skill_upgrade_cost_config.end() ) { const ValueVector& costs = itr->second.asValueVector(); if( level <= costs.size() ) { return costs.at( level - 1 ).asInt(); } } return -1; } int ResourceManager::getUnitUpgradeCost( const std::string& name, int level ) { auto itr = _unit_levelup_cost_config.find( name ); if( itr != _unit_levelup_cost_config.end() ) { const ValueVector& costs = itr->second.asValueMap().at( "costs" ).asValueVector(); if( level <= costs.size() ) { return costs.at( level - 1 ).asInt(); } } return -1; } void ResourceManager::loadUnitArmatures( const cocos2d::ValueVector& armature_names ) { for( auto itr = armature_names.begin(); itr != armature_names.end(); ++itr ) { std::string unit_name = itr->asString(); const ValueMap& unit_config = this->getUnitData( unit_name ); bool is_double_face = unit_config.at( "double_face" ).asBool(); if( is_double_face ) { std::string path = Utils::stringFormat( "characters/%s", unit_name.c_str() ); ArmatureManager::getInstance()->loadArmatureData( path ); } else { std::string front_path = Utils::stringFormat( "characters/%s/%s_f", unit_name.c_str() ); ArmatureManager::getInstance()->loadArmatureData( front_path ); std::string back_path = Utils::stringFormat( "chacaters/%s/%s_b", unit_name.c_str() ); ArmatureManager::getInstance()->loadArmatureData( back_path ); } bool is_melee = unit_config.at( "is_melee" ).asBool(); if( !is_melee ) { auto itr = unit_config.find( "bullet_name" ); if( itr != unit_config.end() ) { std::string bullet_name = itr->second.asString(); if( bullet_name != "" ) { const cocos2d::ValueMap& single_bullet_config = this->getBulletData( bullet_name ); itr = single_bullet_config.find( "body_type" ); if( itr != single_bullet_config.end() ) { std::string resource_name = single_bullet_config.at( "name" ).asString() + "_body"; std::string type = single_bullet_config.at( "body_type" ).asString(); this->loadBulletArmature( resource_name, type ); } itr = single_bullet_config.find( "start_type" ); if( itr != single_bullet_config.end() ) { std::string resource_name = single_bullet_config.at( "name" ).asString() + "_start"; std::string type = itr->second.asString(); this->loadBulletArmature( resource_name, type ); } itr = single_bullet_config.find( "hit_type" ); if( itr != single_bullet_config.end() ) { std::string resource_name = single_bullet_config.at( "hit_name" ).asString() + "_hit"; std::string type = single_bullet_config.at( "hit_type" ).asString(); this->loadBulletArmature( resource_name, type ); } } } } } } void ResourceManager::purgeUnitArmatures( const cocos2d::ValueVector& armature_names ) { for( auto itr = armature_names.begin(); itr != armature_names.end(); ++itr ) { std::string unit_name = itr->asString(); const ValueMap& unit_config = this->getUnitData( unit_name ); bool is_double_face = unit_config.at( "double_face" ).asBool(); if( is_double_face ) { std::string path = Utils::stringFormat( "characters/%s", unit_name.c_str() ); ArmatureManager::getInstance()->unloadArmatureData( path ); } else { std::string front_path = Utils::stringFormat( "characters/%s/%s_f", unit_name.c_str() ); ArmatureManager::getInstance()->unloadArmatureData( front_path ); std::string back_path = Utils::stringFormat( "chacaters/%s/%s_b", unit_name.c_str() ); ArmatureManager::getInstance()->unloadArmatureData( back_path ); } bool is_melee = unit_config.at( "is_melee" ).asBool(); if( !is_melee ) { auto itr = unit_config.find( "bullet_name" ); if( itr != unit_config.end() ) { std::string bullet_name = itr->second.asString(); if( bullet_name != "" ) { const ValueMap& single_bullet_config = this->getBulletData( bullet_name ); itr = single_bullet_config.find( "body_type" ); if( itr != single_bullet_config.end() ) { std::string resource_name = single_bullet_config.at( "name" ).asString() + "_body"; std::string type = itr->second.asString(); this->purgeBulletArmature( resource_name, type ); } itr = single_bullet_config.find( "start_type" ); if( itr != single_bullet_config.end() ) { std::string resource_name = single_bullet_config.at( "name" ).asString() + "_start"; std::string type = itr->second.asString(); this->purgeBulletArmature( resource_name, type ); } itr = single_bullet_config.find( "hit_type" ); if( itr != single_bullet_config.end() ) { std::string resource_name = single_bullet_config.at( "hit_name" ).asString() + "_hit"; std::string type = itr->second.asString(); this->purgeBulletArmature( resource_name, type ); } } } } } } void ResourceManager::loadBuildingArmature( const std::string& name ) { } void ResourceManager::purgeBuildingArmature( const std::string& name ) { } cocos2d::Animation* ResourceManager::createAnimation( const std::string& name, int count, float delay, int loops ) { cocos2d::Vector<cocos2d::SpriteFrame*> frame_array; SpriteFrameCache* frame_cache = SpriteFrameCache::getInstance(); for( int i = 1; i <= count; i++ ) { std::string frame_name = Utils::stringFormat( "%s_%02d.png", name.c_str(), i ); frame_array.pushBack( frame_cache->getSpriteFrameByName( frame_name ) ); } return Animation::createWithSpriteFrames( frame_array, delay, loops ); } cocos2d::Sprite* ResourceManager::getAnimationSprite( const std::string& name ) { return nullptr; } std::string ResourceManager::getPathForResource( const std::string& name, eResourceType type ) { if( type == eResourceType::Character_Double_Face ) { return Utils::stringFormat( "characters/%s", name.c_str() ); } else if( type == eResourceType::Character_Front ) { return Utils::stringFormat( "characters/%s/%s_f", name.c_str(), name.c_str() ); } else if( type == eResourceType::Character_Back ) { return Utils::stringFormat( "characters/%s/%s_b", name.c_str(), name.c_str() ); } else if( type == eResourceType::Tower ) { return Utils::stringFormat( "towers/%s", name.c_str() ); } else { return std::string( "" ); } } /* dmg damage atk atk def def dod dod cri cri hit hit hp hp mp mp dur duration mov move */ std::string ResourceManager::getSkillDesc( const std::string& skill_name, int level ) { const ValueMap& skill_conf = this->getSkillConfig().at( skill_name ).asValueMap(); std::string ret = skill_conf.at( "desc" ).asString(); size_t i = ret.find( "dmg" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "damage", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } i = ret.find( "atk" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "atk", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } i = ret.find( "def" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "def", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } i = ret.find( "dod" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "dod", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } i = ret.find( "cri" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "cri", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } i = ret.find( "hit" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "hit", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } i = ret.find( "hp" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "hp", skill_conf, level ); ret.replace( i, 2, Utils::toStr( value ) ); } i = ret.find( "mp" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "mp", skill_conf, level ); ret.replace( i, 2, Utils::toStr( value ) ); } i = ret.find( "dur" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "duration", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } i = ret.find( "mov" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "mov", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } i = ret.find( "asp" ); if( i != std::string::npos ) { int value = this->getSkillValueOfKey( "asp", skill_conf, level ); ret.replace( i, 3, Utils::toStr( value ) ); } return ret; } int ResourceManager::getSkillValueOfKey( const std::string& key, const cocos2d::ValueMap& skill_conf, int level ) { auto itr = skill_conf.find( key ); if( itr != skill_conf.end() ) { float v; if( itr->second.getType() == Value::Type::VECTOR ) { v = itr->second.asValueVector().at( level - 1 ).asFloat(); } else { v = itr->second.asFloat(); } if( v < 1.0f ) { v *= 100; } return (int)v; } return 0; }
/** * \file TowerDart.cpp * * \author PaulaRed */ #include "pch.h" #include "TowerDart.h" #include "ImageMap.h" #include "Game.h" #include "ProjectileDart.h" using namespace std; using namespace Gdiplus; /// Dart image ID const int DartID = 51; /// Pi const double Pi = 3.14159265358979323846; /// The dart's speed in pixels per second const int DartSpeed = 200; /** * Constructor * \param level The level object that this item is a part of * \param game The Game this item is a member of */ CTowerDart::CTowerDart(CLevel* level, CGame* game) : CTower(level, game, TowerImageID) { // the image ID is not properly set in the CTower constructor because it is // not yet initialized. This fixes that SetImageID(TowerImageID); game->AddImage(TowerImageID, TowerImageName); mTimeTillFire = mTimeBetweenShots; } /** Handle updates for darts * \param elapsed The time since the last update */ void CTowerDart::Update(double elapsed) { if (!IsActive()) return; if (GetLevel()->IsActive()) { mTimeTillFire -= elapsed; if (mTimeTillFire < 0) { mTimeTillFire += mTimeBetweenShots; Fire(); } } } /** * Fire dart */ void CTowerDart::Fire() { // Get image specifics shared_ptr<Bitmap> dartTowerImage = GetGame()->GetImage(TowerImageID); double wid = dartTowerImage->GetWidth(); double hit = dartTowerImage->GetHeight(); // Create 8 darts for (double i = 0; i < 8; i++) { shared_ptr<CItem> item = nullptr; auto dart = make_shared<CProjectileDart>(GetLevel(), GetGame(), DartID); // Set the dart's angle dart->SetAngle(i * (Pi / 4.0) - Pi / 4.0); double a = dart->GetAngle(); double dist = dart->GetDistance(); double sn = sin(a); // sin double cs = cos(a); // cos // Assign dart location double x = GetX() + cs * dart->GetDistance(); double y = GetY() + sn * dart->GetDistance(); dart->SetLocation(x, y); // Upcast and append to level's AddDeferred item = dart; GetLevel()->AddDeferred(item); // Set X and Y speed dart->SetSpeed(DartSpeed * cs, DartSpeed * sn); } }
/* Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] */ #include <iostream> #include <vector> typedef std::vector<int> vi; vi sortColors(vi vec); void printVector(vi vec); int main() { vi vec = { 0,1,2,2,1,0,0,2,0,1,1,0 }; std::cout << "Vector before sort: "; printVector(vec); vec = sortColors(vec); std::cout << "Vector after sort: "; printVector(vec); return 0; } vi sortColors(vi vec) { if (vec.empty()) { return{}; } int index = 0; int low = 0; int high = vec.size()-1; while (index <= high) { if (vec[index] < 1) { std::swap(vec[index++], vec[low++]); } else if (vec[index] > 1) { std::swap(vec[index], vec[high--]); } else { index++; } } return vec; } void printVector(vi vec) { for (auto const &i : vec) { std::cout << i; } std::cout << std::endl; }
/* * Myradius.h * * Created on: Aug 4, 2013 * Author: marchi */ #ifndef MYRADIUS_H_ #define MYRADIUS_H_ #include <vector> #include <string> #include <algorithm> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <sstream> #include <map> #include <cstdlib> #include "RadiiDBase.h" #include "InputRadii.h" using std::vector; using std::string; using std::cout; using std::endl; using std::map; const int maxwrite=10; namespace Topol_NS { class Myradius{ static bool bHyd; static InputRadii * IR; static RadiiDBase * RDB; static bool init; static int count; public: Myradius(){ try{if(!init) throw string("Must initialize Myradius first. Abort ");} catch(const string & s){cout << s<<endl;exit(1);}; } Myradius(InputRadii x, RadiiDBase y){ setRadius(x,y); }; void setRadius(InputRadii x, RadiiDBase y){ IR=new InputRadii; RDB=new RadiiDBase; *IR=x; *RDB=y; init=true; }; double operator()(const string, const string); static void setNOHYD(){bHyd=false;}; }; } #endif /* MYRADIUS_H_ */
#include<string> #include<cmath> #include "line.h" Line::Line(double x1,double y1, double x2, double y2): _x1{x1},_x2{x2},_y1{y1},_y2{y2} {}; std::string Line::to_string(){ std::string s="(" + std::to_string(_x1) + "," + std::to_string(_y1) + ")" + "-"+ "(" + std::to_string(_x2) + "," + std::to_string(_y2) + ")"; return s; } double Line::length(){ return sqrt( pow(_x1-_x2,2) + pow(_y1-_y2,2) ); }
// binary insertion sort // _ ____ __ _ _ __ // (_/_(_(_(_)(__ / (_(_/_(_(_(_/__(/_/ (_ // /( .-/ .-/ // (_) (_/ (_/ #include "../_library_sort_.h" // Độ phức tạp: // Best: O(n) | Avarage: O(nlogn) | Worst: O(nlogn) | Memory: O(1) | Stable // Ưu điểm: // - Cải tiến từ Insertion sort // - Tận dụng Binary Search để tìm vị chèn nhanh // Nhược điểm: // - Không nhanh với thuật toán khác template<class T> void BinaryInsertionSort(T *arr, lli n) { lli left, right, mid; T key; for (lli i = 1; i < n; i++) { key = arr[i]; left = 0; right = i - 1; // Tìm vị trí chèn x while (left <= right) { // Tìm vị trí thích hợp mid mid = (left + right) / 2; if (key < arr[mid]) { right = mid - 1; } else { left = mid + 1; } } for (lli j = i - 1; j >= left; j--) { // Dời các phần tử sẽ đứng sau key arr[j + 1] = arr[j]; } // Chèn lại key vào dãy arr[left] = key; } } // Inserion Sort đệ quy template<class T> void BinaryInsertionSort_UseRecursion(T *arr, lli n) { if (n <= 1) { return; } BinaryInsertionSort_UseRecursion(arr, n - 1); int key = arr[n - 1]; lli left = 0; lli right = n - 1; lli mid; while (left <= right) { // Tìm vị trí thích hợp mid mid = (left + right) / 2; if (key < arr[mid]) { right = mid - 1; } else { left = mid + 1; } } lli j; for (j = right - 1; j >= left; j--) { // Dời các phần tử sẽ đứng sau key arr[j + 1] = arr[j]; } // Chèn lại key vào dãy arr[j + 1] = key; } int main() { lli *arr; lli n{}; Input(arr, n); BinaryInsertionSort(arr, n); Output(arr, n); return 0; }
#include "Common.h" #include "Testing.h" #include "Server.h" #if defined ( FO_LINUX ) || defined ( FO_MAC ) # include <sys/stat.h> #endif #ifndef FO_TESTING int main( int argc, char** argv ) #else static int main_disabled( int argc, char** argv ) #endif { Thread::SetName( "ServerYoungDaemon" ); LogToFile( "FOnlineServerDaemon.log" ); InitialSetup( "FOnlineServerDaemon", argc, argv ); #if defined ( FO_LINUX ) || defined ( FO_MAC ) // Start daemon pid_t parpid = fork(); if( parpid < 0 ) { WriteLog( "Create child process (fork) fail, error '{}'.", ERRORSTR ); return 1; } else if( parpid != 0 ) { // Close parent process return 0; } close( STDIN_FILENO ); close( STDOUT_FILENO ); close( STDERR_FILENO ); if( setsid() < 0 ) { WriteLog( "Generate process index (setsid) failed, error '{}'.\n", ERRORSTR ); return 1; } umask( 0 ); #else RUNTIME_ASSERT( !"Invalid OS" ); #endif Thread::SetName( "ServerDaemon" ); FOServer server; server.Run(); return server.Run(); }
#include "stdafx.h" #include "data/Syntaxer.h" #include "data/Syntaxer_impl.h" namespace filtering { ////////////////////////////////////////////////////////////////////////// void syntaxer::R() { // R = W (\n W)* // try { W(); R2(); } LogExceptionPath("R"); } void syntaxer::R2() { lexeme set[]= {"\n"}; try { if (size()) { if (std::count(set, ENDOF(set), top())) { lexeme opera=top(); pop(); if (size()) { W(); out(lexeme("&&")); R2(); } } } } LogExceptionPath("R2"); } void syntaxer::W() { // W = Q (&& Q)* try { Q(); W2(); } LogExceptionPath("W"); } void syntaxer::W2() { lexeme set[]= {"&&", "||", "and", "or"}; try { if (size()) { if (std::count(set, ENDOF(set), top())) { lexeme opera=top(); pop(); opera.set_punctuator(); Q(); out(opera); W2(); } } } LogExceptionPath("W2"); } void syntaxer::Q() { // Q = E (< E)* try { E(); Q2(); } LogExceptionPath("Q"); } void syntaxer::Q2() { lexeme set[]= {"<", ">", "<=", ">=", "==", "!=", "<>", "="}; try { if (size()) { if (std::count(set, ENDOF(set), top())) { lexeme opera=top(); pop(); E(); out(opera); } } } LogExceptionPath("Q2"); } void syntaxer::E() { // E = T (+ T)* try { T(); E2(); } LogExceptionPath("E"); } void syntaxer::E2() { try { if (size()) if (top()==lexeme("+") || top()==lexeme("-")) { lexeme opera=top(); pop(); T(); out(opera); E2(); } } LogExceptionPath("X"); } void syntaxer::T() { // T = F (* F) try { F(); T2(); } LogExceptionPath("T"); } void syntaxer::T2() { try { if (size()) if (top()==lexeme("*") || top()==lexeme("/")) { lexeme opera=top(); pop(); F(); out(opera); T2(); } } LogExceptionPath("Y"); } void syntaxer::F() { // F = ( R ) // F = !R // F = -R try { syntax_error::assert_expected(size(), "expected value", lexeme()); if (top()==lexeme("(")) { pop(); R(); syntax_error::assert_expected(top()==lexeme(")"), "')' expected", top()); pop(); out( lexeme("()") ); } else if (top()==lexeme("!") || top()==lexeme("not")) { lexeme opera=top(); pop(); opera.set_punctuator(); F(); out(opera); } else if (top()==lexeme("-")) { pop(); F(); out( lexeme("-u") ); } else { out(top()); pop(); } } LogExceptionPath("F"); } lexeme syntaxer::top() { syntax_error::assert_expected(reader_.size(), "lexeme expected", lexeme("eof")); return reader_.front(); } void syntaxer::pop() { syntax_error::assert_expected(reader_.size(), "lexeme expected", lexeme("eof")); reader_.erase(reader_.begin()); } unsigned syntaxer::size() const { return reader_.size(); } void syntaxer::out(const lexeme &lex) { output_.push_back(lex); if (lex.get_type()==apunctuator) { if (lex==lexeme("!") || lex==lexeme("not") || lex==lexeme("-u") || lex==lexeme("()")) { syntax_error::assert_expected(process_tree_.size(), "token expected after", lex); shared_ptr<node> r=process_tree_.top(); process_tree_.pop(); process_tree_.push( shared_ptr<node>( new node(lex, shared_ptr<node>(), r)) ); } else { syntax_error::assert_expected(process_tree_.size()>=2, "expected after", lex); shared_ptr<node> r=process_tree_.top(); process_tree_.pop(); shared_ptr<node> l=process_tree_.top(); process_tree_.pop(); process_tree_.push( shared_ptr<node>( new node(lex, l, r)) ); } } else { process_tree_.push( shared_ptr<node>( new node(lex)) ); } } node syntaxer::get_process_tree() const { debug::Assert<fault>(process_tree_.size(), HERE); return *process_tree_.top(); } std::vector<lexeme>::const_iterator syntaxer::begin() const { return output_.begin(); } std::vector<lexeme>::const_iterator syntaxer::end() const { return output_.end(); } ////////////////////////////////////////////////////////////////////////// namespace { typedef double (*operator_t)(double, double); double add(double a, double b) { return a+b; } double sub(double a, double b) { return a-b; } double mul(double a, double b) { return a*b; } double div(double a, double b) { return a/b; } double le(double a, double b) { return a<b; } double leq(double a, double b) { return a<=b; } double gr(double a, double b) { return a>b; } double grq(double a, double b) { return a>=b; } double eq(double a, double b) { return a==b; } double ne(double a, double b) { return a!=b; } double an(double a, double b) { return a&&b; } double orr(double a, double b) { return a||b; } double nott(double, double b) { return !b; } double neg(double, double b) { return -b; } double par(double, double b) { return b; } struct operators_ini { void push(std::string str, operator_t op) { lexeme lex(str); unsigned hash=lex.get_hash(); if (operators_.size() <= hash) operators_.resize(hash+1); assert(operators_[hash]==0); operators_[hash] = op; } operators_ini() { push("+", add); push("-", sub); push("*", mul); push("/", div); push("<", le); push("<=", leq); push(">", gr); push(">=", grq); push("==", eq); push("=", eq); push("!=", ne); push("<>", ne); push("&&", an); push("and", an); push("||", orr); push("or", orr); push("!", nott); push("not", nott); push("-u", neg); push("()", par); } double get(unsigned hash, double a, double b) { assert(hash<operators_.size()); assert(operators_[hash]); return operators_[hash](a, b); } private: std::vector<operator_t> operators_; } calculator; } // namespace node::node(lexeme op, shared_ptr<node> l, shared_ptr<node> r) : lexeme_(op), left_(l), right_(r) { } node::node(lexeme op, shared_ptr<node> r) : lexeme_(op), right_(r) { } node::node(lexeme l) : lexeme_(l) { } double node::get_value(const double *data) { switch (lexeme_.get_type()) { case apunctuator: { double lv=left_ ? left_->get_value(data) : 0; double rv=right_ ? right_->get_value(data) : 0; return calculator.get(lexeme_.get_hash(), lv, rv); } case areference: return data[lexeme_.get_reference()]; case anumber: return lexeme_.get_number(); case asymbol: return 0; default: debug::Assert<fault>(false, HERE); return 0; } } double node::get_value(data::slice *slc, unsigned index) { switch (lexeme_.get_type()) { case apunctuator: { double lv=left_ ? left_->get_value(slc, index) : 0; double rv=right_ ? right_->get_value(slc, index) : 0; return calculator.get(lexeme_.get_hash(), lv, rv); } case areference: return slc->get_value(index, (aera::chars)lexeme_.get_reference()); case anumber: return lexeme_.get_number(); case asymbol: return 0; default: debug::Assert<fault>(false, HERE); return 0; } } std::string node::string() const { return lexeme_.get_string()=="()" ? "(" + right_->string()+")" : (left_ ? left_->string() : "") + lexeme_.get_string() + (right_ ? right_->string() : ""); } lexeme node::get_lexeme() const { return lexeme_; } ////////////////////////////////////////////////////////////////////////// node tree_maker(lexer &lx) { syntaxer sn(STL_II(lx)); return sn.get_process_tree(); } node tree_maker(std::string string) { lexer lx(string.size() ? string : "1"); return tree_maker(lx); } node tree_maker(std::string string, vars_t &map) { lexer lx(string.size() ? string : "1"); lx.apply(map); return tree_maker(lx); } ////////////////////////////////////////////////////////////////////////// }
unsigned long sendNTPpacket(IPAddress& address) { Serial.println("sending NTP packet..."); // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: udp.beginPacket(address, 123); //NTP requests are to port 123 udp.write(packetBuffer, NTP_PACKET_SIZE); udp.endPacket(); } bool getTime() { //get a random server from the pool WiFi.hostByName(ntpServerName, timeServerIP); sendNTPpacket(timeServerIP); // send an NTP packet to a time server // wait to see if a reply is available delay(1000); int cb = udp.parsePacket(); if (!cb) { Serial.println("no packet yet"); delay(1000); return (false); } else { Serial.print("packet received, length="); Serial.println(cb); // We've received a packet, read the data from it udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer //the timestamp starts at byte 40 of the received packet and is four bytes, // or two words, long. First, esxtract the two words: highWord = word(packetBuffer[40], packetBuffer[41]); lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): secsSince1900 = highWord << 16 | lowWord; // now convert NTP time into everyday time: Serial.print("Unix time = "); // subtract seventy years: epoch = secsSince1900 - seventyYears; // print the hour, minute and second: Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) realHour = (epoch % 86400L) / 3600; Serial.print(realHour); // print the hour (86400 equals secs per day) realMin = (epoch % 3600) / 60; Serial.print(realMin); // print the minute (3600 equals secs per minute) realSec = epoch % 60; Serial.println(realSec); // print the second hour = realHour; minutes = realMin; seconds = realSec; return (true); } } void updateTime() { timeNow = millis() / 1000; seconds = timeNow - timeLast; if (seconds == 60) { timeLast = timeNow; minutes = minutes + 1; seconds = 0; } if (minutes == 60) { while (!getTime()); } }
class MainForm:public Form, public IProgrss { TextBox* txtFilePath; TextBox* txtFileNumber; ProgressBar *progressBar; public: void Button1_Click() { string filePath = txtFilePath->getText(); int number = atoi(txtFileNumber->getText().c_str()); ConsoleNotifier cn; FileSplitter splitter(filePath,number); splitter.addIprogress(this);//订阅通知 splitter.addIprogress(&cn);//订阅通知 splitter.split(); splitter.removeIprogress(this); } virtual void DoProgress(float value) { progressBar->setValue(value); } }; class ConsoleNotifier : public IProgess { public: virtual void DoProgress(float value) { std::cout<<"."; } };