text
stringlengths
8
6.88M
// Copyright ©2016 Black Sphere Studios // For conditions of distribution and use, see copyright notice in "bss_util.h" #ifndef __C_HEAP_H__BSS__ #define __C_HEAP_H__BSS__ #include "bss_compare.h" #include "cDynArray.h" #include <memory> #include <limits> namespace bss_util { template<class T, typename CT_> struct MFUNC_DEFAULT { BSS_FORCEINLINE static void BSS_FASTCALL MFunc(const T&, CT_, MFUNC_DEFAULT*) {} }; // This is a binary max-heap implemented using an array. Use CompTInv to change it into a min-heap, or to make it use pairs. template<class T, typename CT_=uint32_t, char(*CFunc)(const T&, const T&)=CompT<T>, ARRAY_TYPE ArrayType = CARRAY_SIMPLE, typename Alloc=StaticAllocPolicy<T>, class MFUNC = MFUNC_DEFAULT<T, CT_>> class BSS_COMPILER_DLLEXPORT cBinaryHeap : protected cDynArray<T, CT_, ArrayType, Alloc>, protected MFUNC { protected: typedef cDynArray<T, CT_, ArrayType, Alloc> AT_; using AT_::_array; using AT_::_capacity; using AT_::_length; #define CBH_PARENT(i) ((i-1)/2) #define CBH_LEFT(i) ((i<<1)+1) #define CBH_RIGHT(i) ((i<<1)+2) public: inline cBinaryHeap(const cBinaryHeap& copy) : AT_(copy) { } inline cBinaryHeap(cBinaryHeap&& mov) : AT_(std::move(mov)) { } inline cBinaryHeap() : AT_(0) {} inline cBinaryHeap(const T* src, CT_ length) : AT_(length) { _copy(_array, src, sizeof(T)*length); _length = length; Heapify(_array, _length); } template<CT_ SIZE> inline cBinaryHeap(const T(&src)[SIZE]) : AT_(SIZE) { _copy(_array, src, sizeof(T)*SIZE); _length = SIZE; Heapify(_array, _length); } inline ~cBinaryHeap() {} inline const T& Peek() { return _array[0]; } inline const T& Get(CT_ index) { assert(index<_length); return _array[index]; } inline T Pop() { T r=std::move(_array[0]); Remove(0); return std::move(r); } inline bool Empty() { return !_length; } inline CT_ Length() { return _length; } inline void Clear() { _length=0; } // Inserts a value inline void Insert(const T& val) { _insert(val); } inline void Insert(T&& val) { _insert(std::move(val)); } // Sets a key and percolates inline bool Set(CT_ index, const T& val) { return _set(index, val); } inline bool Set(CT_ index, T&& val) { return _set(index, std::move(val)); } // To remove a node, we replace it with the last item in the heap and then percolate down inline bool Remove(CT_ index) { if(index>=_length) return false; //We don't have to copy _array[_length - 1] because it stays valid during the percolation if(_length>1) //We can't percolate down if there's nothing in the array! PercolateDown(_array, _length - 1, index, _array[_length - 1], this); AT_::RemoveLast(); return true; } // Percolate up through the heap template<typename U> static void PercolateUp(T* _array, CT_ _length, CT_ k, U && val, cBinaryHeap* p = 0) { assert(k<_length); uint32_t parent; while(k > 0) { parent = CBH_PARENT(k); if(CFunc(_array[parent], std::forward<U>(val)) > 0) break; _array[k] = std::move(_array[parent]); MFUNC::MFunc(_array[k], k, p); k = parent; } _array[k]=std::forward<U>(val); MFUNC::MFunc(_array[k], k, p); } // Percolate down a heap template<typename U> static void PercolateDown(T* _array, CT_ length, CT_ k, U && val, cBinaryHeap* p = 0) { assert(k<length); assert(k<(std::numeric_limits<CT_>::max()>>1)); CT_ i; for(i = CBH_RIGHT(k); i < length; i = CBH_RIGHT(i)) { if(CFunc(_array[i-1], _array[i]) > 0) // CFunc (left,right) and return true if left > right --i; //left is greater than right so pick that one if(CFunc(std::forward<U>(val), _array[i]) > 0) break; _array[k]=std::move(_array[i]); MFUNC::MFunc(_array[k], k, p); k=i; assert(k<(std::numeric_limits<CT_>::max()>>1)); } if(i >= length && --i < length && CFunc(std::forward<U>(val), _array[i])<=0) //Check if left child is also invalid (can only happen at the very end of the array) { _array[k]=std::move(_array[i]); MFUNC::MFunc(_array[k], k, p); k=i; } _array[k]=std::forward<U>(val); MFUNC::MFunc(_array[k], k, p); } operator T*() { return _array; } operator const T*() const { return _array; } inline const T* begin() const { return _array; } inline const T* end() const { return _array+_length; } inline T* begin() { return _array; } inline T* end() { return _array+_length; } inline cBinaryHeap& operator=(const cBinaryHeap& copy) { AT_::operator=(copy); return *this; } inline cBinaryHeap& operator=(cBinaryHeap&& mov) { AT_::operator=(std::move(mov)); return *this; } template<CT_ SIZE> inline static void Heapify(T(&src)[SIZE]) { Heapify(src, SIZE); } inline static void Heapify(T* src, CT_ length) { T store; for(CT_ i = length/2; i>0;) { store=src[--i]; PercolateDown(src, length, i, store); } } template<CT_ SIZE> inline static void HeapSort(T(&src)[SIZE]) { HeapSort(src, SIZE); } inline static void HeapSort(T* src, CT_ length) { Heapify(src, length); T store; while(length>1) { store=src[--length]; src[length]=src[0]; PercolateDown(src, length, 0, store); } } protected: template<typename U> inline void _insert(U && val) { AT_::_checksize(); new(_array + _length) T(); int k = _length++; PercolateUp(_array, _length, k, std::forward<U>(val), this); } // Sets a key and percolates template<typename U> inline bool _set(CT_ index, U && val) { if(index>=_length) return false; if(CFunc(_array[index], std::forward<U>(val)) <= 0) //in this case we percolate up PercolateUp(_array, _length, index, std::forward<U>(val), this); else PercolateDown(_array, _length, index, std::forward<U>(val), this); return true; } }; // This will grab the value closest to K while that value is still greater then or equal to K //inline size_t GetNearest(const K& key) //{ // BINHEAP_CELL& cur=_array[0]; // if(_array.empty() || CFunc(cur.first,key)<0) // return 0; // //const BINHEAP_CELL& last=BINHEAP_CELL(key(),0); // BINHEAP_CELL& right=cur; // BINHEAP_CELL& left=cur; // int index=0; // while(true) // { // //last=cur; // left=_array[index*=2 + 1]; // right=_array[index + 2]; // if(CFunc(left.first,right.first)>0) //if this is true then left > right // { // ++index; // left=right; // } // else // index+=2; // //switch(CFunc(key,left.first)) // //{ // //case 1: //this is a valid choice // // cur=left; // // break; // //case 0: //we have a winner // // return left.second; // //case -1: //if this is true we went too far // // return cur.second; // //} // } //} /*while(k<_length) { left=CBH_LEFT(k); right=CBH_RIGHT(k); largest=k; if(left<_length && CFunc(_array[left].first,store.first) <= 0) { largest=left; if(right<_length && CFunc(_array[right].first,_array[largest].first) <= 0) largest=right; } else if(right<_length && CFunc(_array[right].first,store.first) <= 0) largest=right; if(largest==k) break; _array[k]=_array[largest]; k=largest; } _array[k]=store;*/ } #endif
//Header Files #include <string> #include <iostream> #include <fstream> #include "HashTable.cpp" using namespace std; /** * @file HashTable.cpp * @author Henry Huffman * @version 1.1 * @brief This program (login.cpp) reads in data from a file, place the data into a hashtable, retrieve data and output it to the user * @details More specifically, this program uses basic file i/o to take in data and place it into the hash. This hash consists of an array of structs. * Once the data is stored, we then attempt to see if the password and username match any of the passwords and usernames stored. * * @date Tuesday, October 28th, 2014 */ /** * User struct * * This struct is used to store the username and password. The setKey function sets the key of the current data member. * The getKey ofcourse gets the key of the specified user profile. */ //struct used for manipulations struct User { /** * setKey function * * @param newKey - the key that must be placed into the the current user's profile * * @pre there may or may not be a key assigned to the current user profile * @post there will be a key assigned to the current user profile specified in the parameters * * @return none */ //this function sets the key, in this case it is a string void setKey( string newKey ) { //the name string is set the specified key of the user name = newKey; } /** * getKey function * * @param - none * * @pre there must be a keyword set in the struct * @post there will be a keyword returned * * @return the keyword that is a string */ //the gets the current name stored inside of the struct string getKey() const { //return the string name return name; } //hash function simply gets the large number we use to modulo and place correctly into hash table int hash(const string str) const { //initialize the value to zero int val = 0; //convert string to a integer value for (unsigned int i=0; i<str.length(); i++) val += str[i]; //return this integer value return val; } //data members of the user struct, the name and keyword string name, keyword; }; /** * @main As previously mentioned, this program will read in data, and place it into the hash table. Then * it will take input from a user to search for a keyword specified by the user. It will then get * the password from the user. If the user's password matches the authentification then reports as sucessful. * Othwerise, the user could not the authenticated. */ int main() { //create a hashtable of structs HashTable<User, string> passwords(8); //create a temporary hashtable User temp; // create two strings. One for name and one for password string name,pass; //a bool to aide in determining if the name is found bool found; //open up the file ifstream fin( "password.dat" ); //if nothing can be taken into the file if ( !fin ) { //output error message cout << "Unable to open 'password.dat'!" << endl; //return to end program return 1; } //loop to take in information while good while ( fin >> temp.name >> temp.keyword ) { //insert data into the hash of structs passwords.insert( temp ); } // output the structure passwords.showStructure(); //prompt user cout << "Login: "; //loop while the name is given while ( cin >> name ) { //check to see if the name is in data found = passwords.retrieve( name, temp ); //prompt for password cout << "Password: "; //take in password cin >> pass; //if the password and username are found if( temp.keyword == pass && found ) { //output success cout << "Authentication successful" << endl; } //otherwise, else { //output failure cout << "Authentication failure" << endl; } //prompt for login cout << "Login: "; //reset found to false for next loop found = false; } //output endl to the screen cout << endl; //end the program return 0; }
#include <MovementComponent.h> using namespace breakout; MovementComponent::MovementComponent() { } MovementComponent::~MovementComponent() { } const std::array<float, 2>& MovementComponent::GetVelocity() const { return m_velocity; } void MovementComponent::SetVelocity(const std::array<float, 2>& velocity) { m_velocity = velocity; }
#include <graphenelib/asset.h> #include <graphenelib/contract.hpp> #include <graphenelib/contract_asset.hpp> #include <graphenelib/dispatcher.hpp> #include <graphenelib/global.h> #include <graphenelib/multi_index.hpp> #include <graphenelib/system.h> using namespace graphene; class tableinit : public contract { public: tableinit(uint64_t account_id) : contract(account_id) { } // @abi action void additem() { print("add item \n"); table_index tables(_self, _self); tables.emplace(_self, [&](auto &obj) { obj.owner = tables.available_primary_key(); //o.owner = 1、2、3、4... obj.str = "Hello"; }); } private: //@abi table table i64 struct table { uint64_t owner; std::string str; uint64_t primary_key() const { return owner; } GRAPHENE_SERIALIZE(table, (owner)(str)) }; typedef graphene::multi_index<N(table), table> table_index; }; GRAPHENE_ABI(tableinit,(additem))
// Copyright 2011 Yandex School Practice #include <gtest/gtest.h> #include "ltr/measures/measure.h" #include "ltr/measures/abs_error.h" #include "ltr/measures/accuracy.h" #include "ltr/measures/squared_error.h" #include "ltr/measures/average_precision.h" #include "ltr/measures/normalized_measure.h" #include "ltr/data/object.h" #include "ltr/data/object_list.h" #include "ltr/data/data_set.h" #include "ltr/utility/numerical.h" using ltr::Object; using ltr::ObjectList; using ltr::DataSet; using ltr::FeatureInfo; using ltr::utility::DoubleEqual; using ltr::AbsError; using ltr::SquaredError; using ltr::AveragePrecision; using ltr::Accuracy; using ltr::NormalizedMeasure; TEST(MeasureTest, MeasureTest) { Object object1; object1 << 1; object1.set_actual_label(0); object1.set_predicted_label(2); Object object2; object2 << 2; object2.set_actual_label(1.4); object2.set_predicted_label(1.4); Object object3; object3 << 3; object3.set_actual_label(3.5); object3.set_predicted_label(-3.5); Object object4; object4 << 4; object4.set_actual_label(0.5); object4.set_predicted_label(4.0); DataSet<Object> data_set(FeatureInfo(1)); DataSet<Object> empty_data_set(FeatureInfo(1)); data_set.add(object1, 1.0); data_set.add(object2, 2.0); data_set.add(object3, 0.5); data_set.add(object4, 1.2); AbsError ae; EXPECT_TRUE(DoubleEqual(ae.average(data_set), 2.063829787234042)); EXPECT_ANY_THROW(ae.average(empty_data_set)); SquaredError se; EXPECT_TRUE(DoubleEqual(se.average(data_set), 9.191489361702127)); EXPECT_ANY_THROW(se.average(empty_data_set)); ObjectList empty_olist; AveragePrecision ap; EXPECT_ANY_THROW(ap(empty_olist)); EXPECT_TRUE(ae.better(0.3, 1.2)); EXPECT_FALSE(se.better(0.2, 0.1)); EXPECT_TRUE(ap.better(1, 0.5)); EXPECT_FALSE(ap.better(0.3, 1.5)); } TEST(MeasureTest, NormalizedMeasureTest) { AbsError::Ptr abs_error(new AbsError()); NormalizedMeasure<Object> norm(abs_error); NormalizedMeasure<Object> norm2(abs_error, 1, -1); Object obj; obj.set_actual_label(1); obj.set_predicted_label(0); norm.setWeakMeasure(AbsError()); EXPECT_THROW(norm.value(obj), std::logic_error); norm.setWeakMeasure(Accuracy<Object>()); norm2.setWeakMeasure(Accuracy<Object>()); EXPECT_NO_THROW(norm.value(obj)); EXPECT_EQ(norm.worst(), -1); EXPECT_EQ(norm.best(), 1); EXPECT_EQ(norm.value(obj), -1); EXPECT_EQ(norm2.value(obj), 1); obj.set_predicted_label(1); EXPECT_EQ(norm.value(obj), 1); EXPECT_EQ(norm2.value(obj), -1); }
#include <nihttpd/nihttpd.h> #include <nihttpd/socket.h> #include <nihttpd/http.h> #include <iostream> using namespace nihttpd; static http_response gen_error_page( http_error err ){ http_response ret; std::string str = status_string( err.error_num ); std::string cont = "<!doctype html><html>" "<head><title>" + str + "</title></head>" "<body><h2>" + str + "</h2>" "</body></html>"; ret.set_content( cont ); ret.status = err.error_num; ret.headers["Connection"] = "close"; ret.headers["Content-Type"] = "text/html"; ret.headers["Content-Length"] = std::to_string( ret.content.size() ); ret.headers["Server"] = "nihttpd/0.0.1"; return ret; } connection server::wait_for_connection(void){ { // notify master thread, in case it's waiting because all workers are busy std::unique_lock<std::mutex> slock(listen_lock); available_threads++; } master.notify_one(); { std::unique_lock<std::mutex> slock(listen_lock); waiter.wait(slock, [this]{ return pending_connects.size() > 0; }); connection ret = pending_connects.front(); pending_connects.pop_front(); available_threads--; return ret; } } void server::worker(void){ while (true){ connection conn = wait_for_connection(); try { http_request request( conn ); router *route = find_route( request.location ); log( urgency::normal, " " + conn.client_ip() + ": " + request.action + " " + request.location ); if ( route == nullptr ){ throw http_error( HTTP_404_NOT_FOUND ); } route->dispatch( request, conn ); } catch ( const http_error &err ){ log( urgency::normal, " " + conn.client_ip() + ": request aborted with error: " + status_string( err.error_num )); http_response res = gen_error_page( err ); res.send_to( conn ); } log( urgency::debug, " closing connection" ); conn.disconnect(); } } server::server( ){ } void server::start( const std::string &host, const std::string &port ){ log( urgency::info, "starting nihttpd" ); try { sock = new listener( host, port ); self = std::thread( &server::run, this ); unsigned concurrency = 2 * (std::thread::hardware_concurrency() + 1); for (unsigned i = 0; i < concurrency; i++){ workers.push_front(std::thread(&server::worker, this)); log(urgency::debug, "started worker thread " + std::to_string(i)); } } catch ( const std::string &msg ){ log( urgency::high, "exception in listener: " + msg ); throw; } running = true; } void server::wait( void ){ if ( running ){ self.join(); } } void server::run( void ){ while ( true ){ connection meh = sock->accept_client(); log( urgency::normal, "connection from " + meh.client_ip() ); { log( urgency::debug, "trying to queue " + meh.client_ip() ); std::lock_guard<std::mutex> slock(listen_lock); pending_connects.push_back(meh); log( urgency::debug, "queued " + meh.client_ip() ); } log( urgency::debug, "notifying " + meh.client_ip() ); { std::unique_lock<std::mutex> slock(listen_lock); if (available_threads == 0) { log(urgency::debug, "no available worker threads, waiting..."); master.wait(slock, [this]{ return available_threads > 0; }); log(urgency::debug, "woke"); } } waiter.notify_one(); } } void server::log( urgency level, const std::string &msg ){ switch ( level ){ case urgency::debug: std::cout << "[debug] "; break; case urgency::low: std::cout << "[low] "; break; case urgency::normal: std::cout << " "; break; case urgency::info: std::cout << "[info] "; break; case urgency::high: std::cout << "[high] "; break; case urgency::critical: std::cout << "[!!!] "; break; } std::cout << "> " << msg << std::endl; } void server::add_route( std::unique_ptr<router> rut ){ routes.push_front( std::move( rut )); } router *server::find_route( std::string location ){ for ( const auto &x : routes ){ unsigned len = x->prefix.length(); if ( x->prefix == location.substr(0, len) ){ return x.get(); } } return nullptr; } router::router( std::string pref, std::string dest ){ prefix = pref; destination = dest; } void router::dispatch( http_request req, connection conn ){ // do nothing ; }
#include <cstdio> #include "../include/Judge.h" #include "../include/Sandbox.h" #include "../include/OIScoring.h" using namespace std; using namespace ACJudge2; using namespace web; std::map<Tstring, Language> Judge::languages; bool Judge::LoadCommands() { Tifstream file(T("../lang.cfg")); if (!file) return false; try { json::value cfg = json::value::parse(file); for (auto &d : cfg.as_array()) languages[d[T("name")].as_string()] = { d[T("name")].as_string(), d[T("compile")].as_string(), d[T("run")].as_string() }; } catch (json::json_exception e) { return false; } return true; } Tstring Judge::GetInputFile(ID taskId, ID inId) { return GetTaskPath(taskId) + inId; } Tstring Judge::GetOutputFile() { return GetBoxPath() + T("out"); } Tstring Judge::GetAnswerFile(ID taskId, ID outId) { return GetTaskPath(taskId) + outId; } Tstring Judge::GetErrorFile() { return GetBoxPath() + T("err"); } Tstring Judge::GetRunCommand(Tstring lang) { if (languages.find(lang) == languages.end()) throw T("Undefined language!"); Language language = languages[lang]; Tchar tmp[LENGTH]; Tsprintf(tmp, language.run.c_str(), (GetBoxPath() + T("bar")).c_str()); return tmp; } Tstring Judge::GetCompareCommand(ID taskId, ID inId, ID outId, Tstring lang) { if (lang == T("")) return T(""); // Default comparer if (languages.find(lang) == languages.end()) throw T("Undefined language!"); Language language = languages[lang]; Tchar tmp[LENGTH]; Tstring in = GetInputFile(taskId, inId); Tstring out = GetOutputFile(); Tstring ans = GetAnswerFile(taskId, outId); Tsprintf(tmp, (language.run + T(" ") + in + T(" ") + out + T(" ") + ans).c_str(), (GetBoxPath() + T("spj")).c_str()); return tmp; } Tstring Judge::GetPrepareCommand(Tstring lang) { if (languages.find(lang) == languages.end()) throw T("Undefined language!"); Language language = languages[lang]; Tchar tmp[LENGTH]; Tsprintf(tmp, language.compile.c_str(), (GetBoxPath() + T("bar")).c_str(), (GetBoxPath() + T("bar")).c_str()); return tmp; } Tstring Judge::GetPrepareSpjCommand(ID taskId, Tstring lang) { if (languages.find(lang) == languages.end()) throw T("Undefined language!"); Language language = languages[lang]; Tchar tmp[LENGTH]; Tsprintf(tmp, language.compile.c_str(), (GetTaskPath(taskId) + T("spj")).c_str(), (GetBoxPath() + T("spj")).c_str()); return tmp; } Tstring Judge::GetTaskPath(ID taskId) { return T("../tasks/") + taskId + T("/"); } Tstring Judge::GetBoxPath() { return T("../foo/"); } json::value Judge::GetTaskConfig(ID taskId) { try { Tifstream config; json::value cfg; config.open(GetTaskPath(taskId) + T("config")); cfg = json::value::parse(config); Tstring type = cfg[T("type")].as_string(); if (type == T("OI")) { auto &data = cfg[T("data")].as_array(); int score = 0; for (auto &d : data) score += d[T("score")].as_integer(); if (score != 100) return fail; } return cfg; } catch (json::json_exception e) { return fail; } } bool Judge::PrepareSpj(Tstring taskId, Tstring lang) { try { Sandbox().Run(GetPrepareSpjCommand(taskId, lang), 5000, INFINITE, false); } catch (Tstring s) { return false; } return true; } bool Judge::PrepareUserCode(Submission s) { try { Sandbox().Run(GetPrepareCommand(s.language), 5000, INFINITE, false); } catch (exception e) { return false; } return true; } json::value Judge::Prepare(Submission s) { try { auto &ret = GetTaskConfig(s.taskId); if (ret.has_field(T("fail"))) return fail; if (ret.has_field(T("spj"))) if (PrepareSpj(s.taskId, ret[T("spj")].as_string()) == false) return fail; if (PrepareUserCode(s) == false) return fail; return ret; } catch (json::json_exception e) { return fail; } } web::json::value Judge::Run(Submission submission) { auto task = Prepare(submission); if (task.has_field(T("fail"))) return fail; Tstring type = task[T("type")].as_string(); if (type == T("OI")) { return OIScoring(*this).Score(task, submission); } else if (type == T("ACM")) { return OIScoring(*this).Score(task, submission); } else if (type == T("CF")) { return OIScoring(*this).Score(task, submission); } else { return fail; } }
#include "GnMeshPCH.h" #ifdef WIN32 GNMESH_ENTRY void LinkError_GnMeshFunc() { return; } #endif
#include "Polygon.h" namespace P_RVD { void Polygon::initialize_from_mesh_facet( const Mesh* _mesh, t_index _facetIdx ) { clear(); Facet temp_facet = _mesh->meshFacets.getFacet(_facetIdx); Vertex* v1 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v1), 1.0, _facetIdx ) ); Vertex* v2 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v2), 1.0, _facetIdx ) ); Vertex* v3 = add_vertex( Vertex( _mesh->meshVertices.getPoint(temp_facet.m_v3), 1.0, _facetIdx ) ); } void Polygon::clip_by_plane(Polygon& _target, Points _points, t_index _i, t_index _j) { _target.clear(); if (getVertex_nb() == 0) { return; } //get the geometic position of the i and j. Vector3d position_i = _points.getPoint(_i); Vector3d position_j = _points.getPoint(_j); // Compute d = n . (2m), where n is the // normal vector of the bisector [i, j] // and m the middle point of the bisector. double d; d = (position_i + position_j).dot(position_i - position_j); //The predecessor of the first vertex is the last vertex t_index prev_index_vertex = getVertex_nb() - 1; const Vertex* prev_vertex = &(getVertex(prev_index_vertex)); Vector3d prev_vertex_position = prev_vertex->getPosition(); //then we compute prev_vertex_position "cross" n //prev_l = prev_vertex_position . n double prev_l = prev_vertex_position.dot(position_i - position_j); P_RVD::Sign prev_status = P_RVD::geo_sgn(2.0 * prev_l - d); //traverse the Vertex in this Polygon for (t_index k = 0; k < getVertex_nb(); ++k) { const Vertex* vertex = &(getVertex(k)); Vector3d vertex_position = vertex->getPosition(); double l = vertex_position.dot(position_i - position_j); //We compute: // side1(pi, pj, q) = sign(2*q.n - n.m) = sign(2*l - d) P_RVD::Sign status = P_RVD::geo_sgn(2.0 * l - d); // If status of edge extremities differ, // then there is an intersection. if (status != prev_status && (prev_status) != 0) { // create the intersection and update the Polygon Vertex I; Vector3d temp_position; //compute the position and weight double denom = 2.0 * (prev_l - l); double lambda1, lambda2; // Shit happens ! [Forrest Gump] if (::fabs(denom) < 1e-20) { lambda1 = 0.5; lambda2 = 0.5; } else { lambda1 = (d - 2.0 * l) / denom; // Note: lambda2 is also given // by (2.0*l2-d)/denom // (but 1.0 - lambda1 is a bit // faster to compute...) lambda2 = 1.0 - lambda1; } temp_position.x = lambda1 * prev_vertex_position.x + lambda2 * vertex_position.x; temp_position.y = lambda1 * prev_vertex_position.y + lambda2 * vertex_position.y; temp_position.z = lambda1 * prev_vertex_position.z + lambda2 * vertex_position.z; //Set the position of Vertex I.setPosition(temp_position); //Set the weight of Veretex I.setWeight(lambda1 * prev_vertex->getWeight() + lambda2 * vertex->getWeight()); //???? »¹Ã»Åª¶® if (status > 0) { I.copy_edge_from(*prev_vertex); I.setSeed(signed_t_index(_j)); } else { I.setEdgeType(Intersection); I.setSeed(vertex->getSeed()); } _target.add_vertex(I); //printf("add I : %.17lf, %.17lf, %.17lf, %lf\n", I.getPosition().x, I.getPosition().y, I.getPosition().z, I.getWeight()); } if (status > 0) { _target.add_vertex(*vertex); //printf("add vertex : %.17lf, %.17lf, %.17lf, %lf\n", vertex->getPosition().x, vertex->getPosition().y, vertex->getPosition().z, vertex->getWeight()); } prev_vertex = vertex; prev_vertex_position = vertex_position; prev_status = status; prev_l = l; prev_index_vertex = k; } return; } void Polygon::show_polygon() { printf("vertex number : %d\n", this->getVertex_nb()); for (int i = 0; i < getVertex_nb(); ++i) { printf("number %d : x : %.17lf, y : %.17lf, z : %.17lf, w : %lf\n", i + 1, getVertex(i).getPosition().x, getVertex(i).getPosition().y, getVertex(i).getPosition().z, getVertex(i).getWeight()); } } }
/* This file is part of SMonitor. Copyright 2015~2016 by: rayx email rayx.cn@gmail.com SMonitor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SMonitor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ #include "stdafx.h" #include "CNoFocusDelegate.h" CNoFocusDelegate::CNoFocusDelegate(QObject *parent) : QStyledItemDelegate(parent) { } CNoFocusDelegate::~CNoFocusDelegate() { } void CNoFocusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem itemOption(option); // remove the focus state if (itemOption.state & QStyle::State_HasFocus) { itemOption.state ^= QStyle::State_HasFocus; } QStyledItemDelegate::paint(painter, itemOption, index); }
#ifndef __MAP_TEMPLATE_H__ #define __MAP_TEMPLATE_H__ #include <iostream> using namespace std; template <class key__T, class val_T > class map_template { private: struct node { node* next; key__T key; val_T val; node() :next(NULL) { }; ~node() { }; }; node* head; public: void Add(key__T key, val_T value) { node* newnode = new node; newnode->next = head; head = newnode; head->val = value; head->key = key; }; void clear() { while (head) { node* t = head->next; delete head; head = t; }; }; val_T* Find(key__T key) const { node* c = head; while (c) { if (c->key == key) return &(c->val); c = c->next; }; return NULL; }; void swap(map_template& l) { node* t = head; head = l.head; l.head = t; }; map_template() { head = NULL; }; map_template(const map_template& l) { node* src, ** dst; head = NULL; src = l.head; dst = &head; try { while (src) { *dst = new node(*src); src = src->next; dst = &((*dst)->next); } } catch (...) { clear(); throw; }; }; map_template& operator= (const map_template& l) { if (&l == this) return *this; map_template t(l); swap(t); return *this; }; ~map_template() { clear(); }; friend std::ostream& operator << (std::ostream& o, const map_template& m) { for (node* i = m.head; i; i = i->next) o << i->val << ": " << i->key << '\n'; return o; }; }; #endif /* __MAP_TEMPLATE_H__ */
/* Copyright 2021 University of Manchester 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 "run_linker.hpp" #include <algorithm> #include <stdexcept> using orkhestrafs::dbmstodspi::RunLinker; // Make a new queue with removed links that are saved in a separate data // structure. Todo: The link removing is useful for detecting I/O but the // separate data structure is not needed. auto RunLinker::LinkPeripheralNodesFromGivenRuns( std::queue<std::pair<std::vector<ScheduledModule>, std::vector<QueryNode*>>> query_node_runs_queue, std::queue<std::map< std::string, std::map<int, std::vector<std::pair<std::string, int>>>>>& linked_nodes) -> std::queue< std::pair<std::vector<ScheduledModule>, std::vector<QueryNode*>>> { std::queue<std::pair<std::vector<ScheduledModule>, std::vector<QueryNode*>>> linked_nodes_queue; // Keeping a counter std::map<std::string, int> run_counter; while (!query_node_runs_queue.empty()) { // Read auto [current_set, current_query_nodes] = query_node_runs_queue.front(); query_node_runs_queue.pop(); // Modify CheckExternalLinks(current_query_nodes, linked_nodes, run_counter); // Write (Config vector stays the same) linked_nodes_queue.push( {std::move(current_set), std::move(current_query_nodes)}); } return linked_nodes_queue; } // Method to remove next or previous nodes from a node once it has been // scheduled void RunLinker::CheckExternalLinks( const std::vector<QueryNode*>& /*current_query_nodes*/, std::queue<std::map< std::string, std::map<int, std::vector<std::pair<std::string, int>>>>>& /*linked_nodes*/, std::map<std::string, int>& /*run_counter*/) { std::map<std::string, std::map<int, std::vector<std::pair<std::string, int>>>> current_links; // for (const auto& node : current_query_nodes) { // std::map<int, std::vector<std::pair<std::string, int>>> target_maps; // for (int next_node_index = 0; next_node_index < node->next_nodes.size(); // next_node_index++) { // std::vector<std::pair<std::string, int>> targets; // int required_run_count = std::count(node->module_locations.begin(), // node->module_locations.end(), -1); // if (!node->next_nodes[next_node_index]) { // if (required_run_count - 1 != run_counter[node->node_name]) { // run_counter[node->node_name]++; // targets.emplace_back(node->node_name, 0); // } // if (node->output_data_definition_files[next_node_index].empty()) { // node->output_data_definition_files[next_node_index] = // node->node_name + "_" + std::to_string(next_node_index) + // ".csv"; // } // } else if // (IsNodeMissingFromTheVector(node->next_nodes[next_node_index], // current_query_nodes)) { // int current_node_location = FindPreviousNodeLocation( // node->next_nodes[next_node_index]->previous_nodes, node); // auto current_filename = // node->output_data_definition_files[next_node_index]; // if (current_filename.empty() && // ReuseMemory(*node, *node->next_nodes[next_node_index])) { // // Need to do a choice here. If node finished. Put it into the // next // // one. If not finished. Do self. // if (node->is_finished && // required_run_count - 1 == run_counter[node->node_name]) { // targets.emplace_back(node->next_nodes[next_node_index]->node_name, // current_node_location); // } else { // run_counter[node->node_name]++; // targets.emplace_back(node->node_name, 0); // } // // Hardcoded self linking. // } else { // if (current_filename.empty()) { // current_filename = node->node_name + "_" + // std::to_string(next_node_index) + ".csv"; // node->output_data_definition_files[next_node_index] = // current_filename; // } // node->next_nodes[next_node_index] // ->input_data_definition_files[current_node_location] = // current_filename; // node->next_nodes[next_node_index] = nullptr; // } // } // if (!targets.empty()) { // target_maps.insert({next_node_index, targets}); // } // } // for (auto& previous_node : node->previous_nodes) { // if (IsNodeMissingFromTheVector(previous_node, current_query_nodes)) { // previous_node = nullptr; // } // } // if (!target_maps.empty()) { // current_links.insert({node->node_name, target_maps}); // } // } // linked_nodes.push(std::move(current_links)); } auto RunLinker::ReuseMemory(const QueryNode& /*source_node*/, const QueryNode& /*target_node*/) -> bool { // TODO(Kaspar): needs to consider the memory capabilities return true; } auto RunLinker::IsNodeMissingFromTheVector( const QueryNode* linked_node, const std::vector<QueryNode*>& current_query_nodes) -> bool { return (linked_node != nullptr) && std::find(current_query_nodes.begin(), current_query_nodes.end(), linked_node) == current_query_nodes.end(); } auto RunLinker::FindPreviousNodeLocation( const std::vector<QueryNode*>& previous_nodes, const QueryNode* previous_node) -> int { for (int previous_node_index = 0; previous_node_index < previous_nodes.size(); previous_node_index++) { auto* observed_node = previous_nodes[previous_node_index]; if (observed_node == previous_node) { return previous_node_index; } } throw std::runtime_error("No node found!"); }
#include <iostream> #include "vector.hpp" Vector::Vector() : m_size(5) { m_array = new List[m_size]; } Vector::Vector(const int size) : m_size(size) { m_array = new List[size]; } Vector::Vector(const Vector& object) { m_size = object.m_size; m_array = new List[m_size]; for (int i = 0; i < m_size; ++i) { m_array[i] = object.m_array[i]; } } Vector::~Vector() { delete[] m_array; m_array = nullptr; } bool Vector::insert(const int index, const std::string key, const int value) { return m_array[index].push_front(key, value) ; } bool Vector::getValueByKey(int index, std::string key, int& value) { return m_array[index].getValueByKey(key, value) ; } bool Vector::getKeyByValue(std::string& key, int value) { for (int i = 0; i < m_size; ++i) { if (m_array[i].getKeyByValue(key, value)) { return true; } } return false; } bool Vector::deleteByKey(int index, std::string key, int& value) { return m_array[index].deleteByKey(key, value); } int Vector::size() const { return m_size; } void Vector::clear() { for (int i = 0; i < m_size; ++i) { m_array[i].clear(); } } void Vector::printVector() const { for (int i = 0; i < m_size; ++i) { m_array[i].printList(); std::cout << std::endl; } std::cout << std::endl << std::endl; }
/* * Copyright 2019 LogMeIn * * 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. * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include <queue> #include "asyncly/executor/ExecutorStoppedException.h" #include "asyncly/executor/IExecutor.h" #include "asyncly/scheduler/IScheduler.h" #include "asyncly/scheduler/PriorityQueue.h" #include "asyncly/task/CancelableTask.h" #include "asyncly/task/Task.h" namespace asyncly { class BaseScheduler : public IScheduler { public: BaseScheduler(const ClockNowFunction& nowFunction); /** * prepareElapse() moves the elapsed scheduled tasks into a separate container which can be * executed by elapse() * prepareElapse() and elapse() should be called by the same thread (sequentially). */ void prepareElapse(); size_t elapse(); /** * Return the time_point of the next scheduled tasks, if it is older or equal than limit. * Otherwise limit is returned. */ clock_type::time_point getNextExpiredTime(clock_type::time_point limit) const; /** * Return the time_point of the last scheduled task but at least the current time (now). */ clock_type::time_point getLastExpiredTime() const; void clear(); // IScheduler clock_type::time_point now() const override; std::shared_ptr<Cancelable> execute_at( const IExecutorWPtr& executor, const clock_type::time_point& absTime, Task&&) override; std::shared_ptr<Cancelable> execute_after( const IExecutorWPtr& executor, const clock_type::duration& relTime, Task&&) override; private: struct TimerQueueElementCompare; using TimerQueueElement = std::pair<clock_type::time_point, Task>; using TimerQueue = detail:: PriorityQueue<TimerQueueElement, std::vector<TimerQueueElement>, TimerQueueElementCompare>; struct TimerQueueElementCompare { bool operator()(const TimerQueueElement& a, const TimerQueueElement& b) { return a.first > b.first; } }; TimerQueue m_timerQueue; std::queue<Task> m_elapsedQueue; ClockNowFunction m_now; }; inline BaseScheduler::BaseScheduler(const ClockNowFunction& nowFunction) : m_now(nowFunction) { } inline asyncly::clock_type::time_point BaseScheduler::now() const { return m_now(); } inline std::shared_ptr<Cancelable> BaseScheduler::execute_at( const IExecutorWPtr& executor, const clock_type::time_point& absTime, Task&& task) { auto sharedTask = std::make_shared<Task>(std::move(task)); auto cancelable = std::make_shared<TaskCancelable>(sharedTask); Task cancelableTask(CancelableTask(sharedTask, cancelable)); m_timerQueue.push({ absTime, [executor, cancelableTask{ std::move(cancelableTask) }]() mutable { if (auto p = executor.lock()) { try { p->post(std::move(cancelableTask)); } catch (ExecutorStoppedException) { // ignore } } } }); return cancelable; } inline std::shared_ptr<Cancelable> BaseScheduler::execute_after( const IExecutorWPtr& executor, const clock_type::duration& relTime, Task&& closure) { return execute_at(executor, m_now() + relTime, std::move(closure)); } inline void BaseScheduler::prepareElapse() { const auto now = m_now(); while (!m_timerQueue.empty() && m_timerQueue.peek().first <= now) { m_elapsedQueue.push(std::move(m_timerQueue.pop().second)); } } inline size_t BaseScheduler::elapse() { const auto elapsedTasks = m_elapsedQueue.size(); while (!m_elapsedQueue.empty()) { auto task = std::move(m_elapsedQueue.front()); m_elapsedQueue.pop(); task(); } return elapsedTasks; } inline clock_type::time_point BaseScheduler::getNextExpiredTime(clock_type::time_point limit) const { const auto now = m_now(); if (m_timerQueue.empty()) { return std::max(limit, now); } else if (m_timerQueue.peek().first <= limit) { return std::max(m_timerQueue.peek().first, now); } else { return std::max(limit, now); } } inline clock_type::time_point BaseScheduler::getLastExpiredTime() const { const auto now = m_now(); if (!m_timerQueue.empty()) { return std::max(m_timerQueue.peekBack().first, now); } else { return now; } } inline void BaseScheduler::clear() { m_timerQueue.clear(); while (!m_elapsedQueue.empty()) { m_elapsedQueue.pop(); } } }
// Voxel.h : main header file for the Voxel DLL // #pragma once #include "DataTypes/vec.h" #include "Cube.h" //#include "stdafx.h" #include "Utility_wrap.h" #include <memory> #include "VoxelHash.h" #include "Graphics/Surfaceobj.h" #include "sumTable.h" #define VOXEL_MIN -9999 #define VOXEL_MAX 9999 class VoxelObj { public: VoxelObj(); ~VoxelObj(); // Visualize void draw(drawMode mode = DRAW_WIRE); void drawVoxelIdx(); void drawMesh(); void drawTable(); // New int volumeInBox(Vec3i leftDown, Vec3i rightUp); int volumeInBox(Boxi b) { return volumeInBox(b.leftDown, b.rightUp); } int objectVolumei(); // Initialize void generateVoxelFromMesh_1(char* filePath, float res); void generateVoxelFromMesh(char* filePath, int res); void writeVoxelData(char* filePath); void readVoxelData(char* filePath); void loadVoxelFromFileFloat(char* filePath); BOOL intersectionWithBox(Vec3f leftDown, Vec3f rightUp, std::vector<int> &intersectedIdxs); BOOL intersectionWithBox(Vec3i leftDown, Vec3i rightUp, std::vector<int> &intersectedIdxs); // Get set arrayVec3i &points(){return m_points;}; // testing void getPointFromSumtable(); public: std::vector<Cube> m_cubes; long m_volume; VoxelHash *hashTable; // Voxel data std::vector<Vec3i> m_points; float m_voxelSize; Vec3i m_leftDown; Vec3i m_rightUp; Vec3i m_sizei; int *** m_voxelArray; sumTable m_sumTable; // Mesh SurfaceObj m_sufObj; }; typedef std::shared_ptr<VoxelObj> VoxelObjPtr;
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #include <unordered_map> #include <stack> #include <cstdio> #include <cmath> #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) #define INF (1e300) using namespace std; ifstream fin("1347_input.txt"); #define cin fin struct point { point(int x, int y) { this->x = x; this->y = y; } int x, y; }; double get_dist(point a, point b) { return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)); } int main() { int n; while (cin >> n) { vector<point> v(n, point(0, 0)); for (int i = 0; i < n; i++) cin >> v[i].x >> v[i].y; vector<vector<double> > f(n, vector<double>(n, INF)); vector<vector<double> > dist(n, vector<double>(n, 0)); for (int i = 0; i < n; i++) for (int j = i; j < n; j++) dist[j][i] = dist[i][j] = get_dist(v[i], v[j]); for (int i = 0; i < n; i++) f[n - 1][i] = dist[n - 1][i]; for (int i = n - 2; i >= 0; i--) for (int j = i; j >= 0; j--) { f[i][j] = min(f[i + 1][j] + dist[i + 1][i], f[i + 1][i] + dist[i + 1][j]); } printf("%.2f\n", f[0][0]); } }
#pragma once #ifndef UNICODE #define UNICODE #endif // !UNICODE #ifndef _UNICODE #define _UNICODE #endif // !_UNICODE #include <tchar.h> #include <windows.h> #include <VersionHelpers.h> #define SafeDelete(x) { delete x; x = 0; } #define ReleaseCOM(x) {if(x){ x->Release(); x=0;}} #define DEBUG_BREAK() __debugbreak() // Error checking TODO cambiare return false con qualcosa di pił significativo #if defined(DEBUG) || defined(_DEBUG) #ifndef HR #define HR(x) {HRESULT hr=(x); if(FAILED(hr)){return false;}} #endif #ifndef FSB_ASSERT #define FSB_ASSERT( expr ) (void)( !( expr ) && ( SBR::Report( _CRT_WIDE( #expr ), _CRT_WIDE( __FUNCTION__ ), _CRT_WIDE( __FILE__ ), __LINE__ ) ) && ( DEBUG_BREAK(), 1 ) ) #endif #else #ifndef HR #define HR(x) (x) #endif #ifndef FSB_ASSERT #define FSB_ASSERT( expr ) (void)sizeof(expr) #endif #endif enum class Result { SUCCESS, FAILURE }; constexpr int MAXNAMELEN = 256; constexpr int MAXSTRINGLEN = 512;
/* Write a program that displays the following pieces of information, each on a separate line: Your name Your address, with city, state, and ZIP code Your telephone number Your college major Use only a single cout statement to display all of this information. Author: Aaron Maynard */ #include <iostream> using namespace std; int main() { // Declare variables string name = "Aaron Maynard"; string address = "123 Main St., Dallas, TX 75261"; string phone = "123-456-7890"; string degree = "Computer Science"; // Print to screen cout << name << "\n" << address "\n" << phone "\n" << degree; system("pause"); return 0; }
#ifndef MacOpSystemInfo_H #define MacOpSystemInfo_H #include "modules/pi/OpSystemInfo.h" #include "modules/hardcore/keys/opkeys.h" #ifdef DPI_CAP_DESKTOP_SYSTEMINFO #include "adjunct/desktop_pi/DesktopOpSystemInfo.h" #endif #if defined(POSIX_SERIALIZE_FILENAME) && defined(POSIX_OK_FILE) #include "platforms/posix/posix_system_info.h" #endif #ifndef MACGOGI #include "platforms/mac/model/MacFileHandlerCache.h" #endif // MACGOGI class MacOpSystemInfo : #if defined(POSIX_SERIALIZE_FILENAME) && defined(POSIX_OK_FILE) public PosixSystemInfo #elif defined(DPI_CAP_DESKTOP_SYSTEMINFO) public DesktopOpSystemInfo #else public OpSystemInfo #endif // DPI_CAP_DESKTOP_SYSTEMINFO { public: MacOpSystemInfo(); virtual ~MacOpSystemInfo() {} #ifndef POSIX_OK_CLOCK virtual void GetWallClock( unsigned long& seconds, unsigned long& milliseconds ); /**< Returns the current local time as seconds and milliseconds since some epoch. */ virtual double GetWallClockResolution(); /**< Returns the resolution of the real-time clock, as a fraction of a second */ /** Returns the current time in milliseconds since 1970-01-01 00:00 GMT */ virtual double GetTimeUTC(); /** Get the time something has been running (expressed in milliseconds). "Something" doesn't matter what it is as long as within one Opera session, the value returned by this method are never less than the previous value returned. This method is eg used by schedulers and the like within Opera that don't want to have to deal with sudden time changes (common in mobile devices). @return runtime in ms */ virtual double GetRuntimeMS(); /** Get the time elapsed since some reference point, but with no fixed guarantees that * the reference point cannot change during an Opera session. Appropriate when you * want to capture length of intervals by comparing the (absolute) difference between * successive calls to GetRuntimeTickMS(), but the absolute precision of the result * for individual calls isn't paramount -- the difference is. * * @return The number of milliseconds since some reference point. No guarantees * that this will be monotonically increasing throughout an Opera session. */ virtual unsigned int GetRuntimeTickMS(); #endif // POSIX_OK_CLOCK #ifndef POSIX_OK_TIME_ZONE /** Returns the number of seconds west of GMT. Eg for Norway, return -3600 when it's normal time, -7200 when it's daylight savings time. */ virtual long GetTimezone(); virtual double DaylightSavingsTimeAdjustmentMS(double t); #endif // POSIX_OK_TIME_ZONE /** * Returns the size of the physical memory (not swap disk etc) in MB */ virtual UINT32 GetPhysicalMemorySizeMB(); /** Retrieve system proxy settings for the given protocol. This is used as * the default setting and can be overridden using the preferences. * * If your platform do not support system proxy settings, set enabled to * FALSE and clear the string value. This method should only leave for * fatal situations, otherwise it should just set enabled to FALSE. * * @param protocol String representation of protocol name. * ("http", "https", "ftp", "gopher" or "wais") * @param enabled (output) Stores a boolean value telling if this proxy * server is enabled or not. * @param proxyserver (output) Stores a string value representing the * address to the proxy server, in the form * "host:port". */ virtual void GetProxySettingsL(const uni_char *protocol, int &enabled, OpString &proxyserver); #ifdef SUPPORT_AUTO_PROXY_CONFIGURATION /** Retrieve the default automatic proxy URL for the system. This is used * as the default setting and can be overridden using the preferences. * * If your platform does not support system proxy settings, simply leave * the string as-is. This method should only leave for fatal situations. * * @param url (output) * Pointer to string to put the URL to the default automatix proxy * configuration (PAC) file for the system. * @param enabled (output) * Stores a boolean value telling if this proxy configuration is * enabled or not. */ virtual void GetAutoProxyURLL(OpString *url, BOOL *enabled); #endif /** Retrieve the default proxy exception list for the system. This is used * as the default setting and can be overridden using the preferences. * * If your platform does not support system proxy settings, simply leave * the input as-is. This method should only leave for fatal situations. * * @param exceptions (output) * Pointer to string to put the list of proxy exceptions * (comma-delimited) for the system. * @param enabled (output) * Stores a boolean value telling if this exception list is * enabled or not. */ virtual void GetProxyExceptionsL(OpString *exceptions, BOOL *enabled); #ifdef _PLUGIN_SUPPORT_ /** Fix-up the plugin path as read from the preferences. This method * receives the plugin path from the preferences and updates it to * include any entries that it must include. If you are staisfied * with the default value, you must still copy it over to the output * string. * * If dfpath is empty (i.e not set in the prefences) a proper default * path should be output. * * The path is separated by the standard path separator for the system, * semi-colon for Windows and colon for the Unix flavours. * * @param dfpath The plugin path read from the preferences. * @param newpath Output: The massaged path to remember. */ virtual void GetPluginPathL(const OpStringC &dfpath, OpString &newpath); #if defined(PI_PLUGIN_DETECT) && !defined(NS4P_COMPONENT_PLUGINS) OP_STATUS DetectPlugins(const OpStringC& suggested_plugin_paths, class OpPluginDetectionListener* listener); #endif // defined(PI_PLUGIN_DETECT) && !defined(NS4P_COMPONENT_PLUGINS) #endif // _PLUGIN_SUPPORT_ #if 0 #ifdef _APPLET_2_EMBED_ /** Retrieve the default Java class path for the system. */ virtual void GetDefaultJavaClassPathL(OpString &target); /** Retrieve the default Java policy filename for the system. */ virtual void GetDefaultJavaPolicyFilenameL(OpString &target); #endif // _APPLET_2_EMBED_ #endif #ifdef USE_OP_MAIN_THREAD /** * Are we currently running in Opera's main thread? */ virtual BOOL IsInMainThread(); #endif #ifdef OPSYSTEMINFO_CPU_FEATURES virtual unsigned int GetCPUFeatures(); #endif /** * Retrieve the MIME name for the system's default encoding. * The pointer must be valid as long as the OpSystemInfo object * is alive. */ virtual const char *GetSystemEncodingL(); /** * Expand system variables from in to out */ virtual OP_STATUS ExpandSystemVariablesInString(const uni_char* in, OpString* out); virtual OP_STATUS ExpandSystemVariablesInString(const uni_char* in, uni_char* out, INT32 out_max_len); /** * Get the default text editor for the system */ virtual const uni_char* GetDefaultTextEditorL(); #ifdef OPSYSTEMINFO_GETFILETYPENAME /** * Get a descriptive file type name from a file name. This is used in * directory listings to provide the user with a file type. If the * type of the file is unknown, the implementation should set the the * out parameter to an empty string. * * @param filename Name of the file that we request information from. * @param out String buffer to store the file description in. * @param out_max_len Length of out, in characters. */ virtual OP_STATUS GetFileTypeName(const uni_char* filename, uni_char *out, size_t out_max_len); #endif // OPSYSTEMINFO_GETFILETYPENAME #ifdef QUICK /** * Get the default mimetype/extension handler for a file */ virtual OP_STATUS GetFileHandler(const OpString* filename, OpString& contentType, OpString& handler); virtual OP_STATUS GetFileHandlers(const OpString& filename, const OpString &content_type, OpVector<OpString>& handlers, OpVector<OpString>& handler_names, OpVector<OpBitmap>& handler_icons, URLType type, UINT32 icon_size = 16); /** * Starts up an application displaying the folder of the file. * * @param file_path - the full path to the file * * @return OpStatus::OK if successful */ virtual OP_STATUS OpenFileFolder(const OpStringC & file_path, BOOL treat_folders_as_files = TRUE); /** * Returns TRUE if platform allow running downloaded content * * @return BOOL */ virtual BOOL AllowExecuteDownloadedContent(); virtual OP_STATUS GetProtocolHandler(const OpString& uri_string, OpString& protocol, OpString& handler); /** * Is the file passed in an executable */ virtual BOOL GetIsExecutable(OpString* filename); /** * Return an OpString containing illegal chars used in a filename for your platform */ virtual OP_STATUS GetIllegalFilenameCharacters(OpString* illegalchars); /** * Cleans a path for illegal characters. Any spaces in front and in the end will * be removed as well. * * @param replace Replace illegal character with a valid character if TRUE. Otherwise * remove the illegal character. * * @return TRUE if the returned string is non-empty */ virtual BOOL RemoveIllegalPathCharacters(OpString& path, BOOL replace); virtual BOOL RemoveIllegalFilenameCharacters(OpString& path, BOOL replace); virtual OpString GetLanguageFolder(const OpStringC &lang_code); /** * Return an OpString containing the newline string i textfiles for your platform */ virtual OP_STATUS GetNewlineString(OpString* newline_string); /** * Return the current down state of the modifier keys. It is a mask using the * SHIFTKEY_NONE, SHIFTKEY_CTRL, SHIFTKEY_SHIFT, SHIFTKEY_ALT, SHIFTKEY_META * and SHIFTKEY_SUPER */ virtual INT32 GetShiftKeyState(); #endif // QUICK #ifdef EMBROWSER_SUPPORT /** * If use_custom is true, use new_color as highlight color. Otherwise return to getting this color from the system. */ virtual OP_STATUS SetCustomHighlightColor(BOOL use_custom, COLORREF new_color); #endif //EMBROWSER_SUPPORT #ifndef NO_EXTERNAL_APPLICATIONS # ifdef DU_REMOTE_URL_HANDLER virtual OP_STATUS PlatformExecuteApplication(const uni_char* application, const uni_char* args, BOOL silent_errors); # else virtual OP_STATUS ExecuteApplication(const uni_char* application, const uni_char* args, BOOL silent_errors); # endif #endif // !NO_EXTERNAL_APPLICATIONS #ifdef EXTERNAL_APPLICATIONS_SUPPORT /** @override */ virtual OP_STATUS OpenURLInExternalApp(const URL& url); #endif #if defined(_CHECK_SERIAL_) || defined(M2_SUPPORT) || defined(DPI_CAP_DESKTOP_SYSTEMINFO) virtual OP_STATUS GetSystemIp(OpString& ip); #endif // _CHECK_SERIAL_ || M2_SUPPORT || DPI_CAP_DESKTOP_SYSTEMINFO virtual const char *GetOSStr(UA_BaseStringId ua); virtual const uni_char *GetPlatformStr(); #ifndef POSIX_OK_NATIVE virtual OP_STATUS OpFileLengthToString(OpFileLength length, OpString8* result); virtual OP_STATUS StringToOpFileLength(const char* length, OpFileLength* result); #endif #ifdef SYNCHRONOUS_HOST_RESOLVING virtual BOOL HasSyncLookup(); #endif // SYNCHRONOUS_HOST_RESOLVING OP_STATUS GetUserLanguages(OpString *result); void GetUserCountry(uni_char result[3]); #ifdef GUID_GENERATE_SUPPORT OP_STATUS GenerateGuid(OpGuid &guid); #endif // GUID_GENERATE_SUPPORT #ifdef DPI_CAP_DESKTOP_SYSTEMINFO virtual int GetDoubleClickInterval(); virtual OP_STATUS GetFileTypeInfo(const OpStringC& filename, const OpStringC& content_type, OpString & content_type_name, OpBitmap *& content_type_bitmap, UINT32 content_type_bitmap_size = 16); #endif // DPI_CAP_DESKTOP_SYSTEMINFO #ifdef OPSYSTEM_GET_UNIQUE_FILENAME_PATTERN /** Return a pattern containing %d for generating unique filenames for * download and ini-files typically " (%d)" on windows, "_%d" on unix */ virtual const uni_char * GetUniqueFileNamePattern() { return UNI_L("_%d"); } #endif #if !defined(POSIX_OK_PATH) # ifdef PI_CAP_PATHSEQUAL OP_STATUS PathsEqual(const uni_char* p1, const uni_char* p2, BOOL* equal); # endif #endif #if defined(POSIX_SERIALIZE_FILENAME) && defined(POSIX_OK_FILE) virtual uni_char* SerializeFileName(const uni_char *path); #endif // POSIX_SERIALIZE_FILENAME virtual void ComposeExternalMail(const uni_char* to, const uni_char* cc, const uni_char* bcc, const uni_char* subject, const uni_char* message, const uni_char* raw_address, MAILHANDLER mailhandler); virtual BOOL HasSystemTray(); #ifdef QUICK_USE_DEFAULT_BROWSER_DIALOG virtual BOOL ShallWeTryToSetOperaAsDefaultBrowser(); virtual OP_STATUS SetAsDefaultBrowser(); #endif #ifdef ACCESSIBILITY_EXTENSION_SUPPORT /** Tells wether a screen reader currently is running * * @return TRUE if we know a screen reader is running or has been running * FALSE otherwise. */ virtual BOOL IsScreenReaderRunning() { return m_screen_reader_running; } #endif //ACCESSIBILITY_EXTENSION_SUPPORT #ifdef OPSYSTEMINFO_GETPROCESSTIME virtual OP_STATUS GetProcessTime(double *time) { return OpStatus::ERR_NOT_SUPPORTED; } #endif // OPSYSTEMINFO_GETPROCESSTIME #ifdef OPSYSTEMINFO_GETBINARYPATH virtual OP_STATUS GetBinaryPath(OpString *path); #endif // OPSYSTEMINFO_GETBINARYPATH #ifdef PI_POWER_STATUS virtual BOOL IsPowerConnected(); virtual BYTE GetBatteryCharge(); virtual BOOL IsLowPowerState(); #endif // PI_POWER_STATUS //utility: void SetEventShiftKeyState(BOOL inEvent, ShiftKeyState state); BOOL GetEventShiftKeyState(ShiftKeyState &state); void SetScreenReaderRunning(BOOL running) { m_screen_reader_running = running; } OP_STATUS GetDefaultWindowTitle(OpString& title) { title.Empty(); return OpStatus::OK; } BOOL IsForceTabMode(); virtual BOOL IsSandboxed(); virtual BOOL SupportsContentSharing(); #ifdef PIXEL_SCALE_RENDERING_SUPPORT virtual INT32 GetMaximumHiresScaleFactor(); #endif // PIXEL_SCALE_RENDERING_SUPPORT virtual OpFileFolder GetDefaultSpeeddialPictureFolder(); private: #if (defined(OPSYSTEMINFO_PATHSEQUAL) || defined(PI_CAP_PATHSEQUAL)) && !defined(POSIX_OK_PATH) const char *ResolvePath(const uni_char *path, size_t stop, char *buffer) const; #endif OpString m_default_language_filename; #ifndef MACGOGI OpAutoStringHashTable<MacFileHandlerCache> m_file_handlers; #endif // MACGOGI BOOL m_use_event_shiftkey_state; ShiftKeyState m_event_shiftkey_state; BOOL m_screen_reader_running; }; enum SystemLanguage { kSystemLanguageUnknown, kSystemLanguageJapanese, kSystemLanguageSimplifiedChinese, kSystemLanguageTraditionalChinese, kSystemLanguageKorean }; SystemLanguage GetSystemLanguage(); #endif // MacOpSystemInfo_H
#pragma once namespace game { //コリジョン識別番号 enum class CollisionID { TekiID, TekiBulletID, PlayerID, PlayerBulletID }; class CollisionCircle; //CollisionCircleの仲介役のようなもの class CollisionData { //紐づけられているCollisionCircleオブジェクト CollisionCircle& m_collision; //削除フラグ bool deleteFlag = false; public: CollisionData(CollisionCircle& collision) noexcept:m_collision(collision) { } CollisionCircle& GetCollision() { return m_collision; } //削除要求をだす void Delete() noexcept { deleteFlag = true; } //削除できるかどうか bool IsDelete() const noexcept { return deleteFlag; } }; }
#ifndef ROOT_THcParmList #define ROOT_THcParmList ////////////////////////////////////////////////////////////////////////// // // THcParmList // ////////////////////////////////////////////////////////////////////////// #include "THaVarList.h" class THcParmList : public THaVarList { public: THcParmList() : THaVarList() {} virtual ~THcParmList() { Clear(); } virtual void Load( const char *fname); protected: ClassDef(THcParmList,0) // List of analyzer global parameters }; #endif
/***************************************************************************** * ExploringSfMWithOpenCV ****************************************************************************** * by Roy Shilkrot, 5th Dec 2012 * http://www.morethantechnical.com/ ****************************************************************************** * Ch4 of the book "Mastering OpenCV with Practical Computer Vision Projects" * Copyright Packt Publishing 2012. * http://www.packtpub.com/cool-projects-with-opencv/book *****************************************************************************/ #pragma once #include <vector> #include <boost/thread.hpp> #include <opencv2/core/core.hpp> #include <pcl/common/common.h> #include <pcl/visualization/pcl_visualizer.h> class CloudVisualizer { typedef pcl::PointCloud<pcl::PointXYZRGB> pclColoredPointCloud; typedef std::pair<std::string,pcl::PolygonMesh> pclCameraRepresntation; typedef std::pair<std::string,std::vector<Eigen::Matrix<float,6,1>>> pclColoredLine; std::deque<pclColoredPointCloud::Ptr> cloud_registry; boost::recursive_mutex _cloud_registry_mutex; pclColoredPointCloud::Ptr cloud_to_show; boost::recursive_mutex _cloud_to_show_mutex; std::deque<pclCameraRepresntation> camera_meshes; boost::recursive_mutex _camera_data_mutex; std::deque<pclColoredLine> camera_los; // Lines Of Sight volatile bool show_cameras; pcl::PolygonMesh scene_mesh; boost::recursive_mutex _scene_mesh_mutex; volatile enum SCENE_STATE : unsigned { SCENE_HIDDEN, SCENE_VISIBLE, SCENE_SHOW } show_scene; static void populatePointCloud(const std::vector<cv::Point3d>& pointcloud, const std::vector<cv::Vec3b>& pointcloud_RGB, pclColoredPointCloud::Ptr& mycloud); boost::scoped_ptr<boost::thread> visualizer_thread; static void visualizerCallback(CloudVisualizer* me, void* dummy); protected: static void KeyboardEventCallback (const pcl::visualization::KeyboardEvent& event_, void *void_this); public: enum CLOUD_SELECTION_DIRECTION { CSD_BACKWARD = -1, CSD_INDIFFERENT = 0, CSD_FORWARD = 1, CSD_LAST = CSD_BACKWARD & ~CSD_FORWARD, CSD_RESET = -CSD_LAST }; typedef std::pair<const std::vector<cv::Point3d>, const std::vector<cv::Vec3b>> RawCloudData; typedef std::vector<RawCloudData> RawCloudDataCollection; CloudVisualizer() : show_cameras(false), show_scene(SCENE_HIDDEN) { /* empty */ } void LoadClouds (const RawCloudDataCollection &cloud_data); void LoadCameras(const std::vector<std::pair<double, cv::Matx34d>> cam_data, const Eigen::Vector3f &color, double s = -1.0); void LoadSceneMesh(const pcl::PolygonMesh &scene_polygons) { _scene_mesh_mutex.lock(); scene_mesh = scene_polygons; SwitchSceneMesh(); _scene_mesh_mutex.unlock(); } void SelectCloudToShow(CLOUD_SELECTION_DIRECTION csd = CSD_INDIFFERENT); bool SwitchSceneMesh() { _scene_mesh_mutex.lock(); show_scene = !scene_mesh.polygons.empty() && show_scene == SCENE_HIDDEN ? SCENE_SHOW : SCENE_HIDDEN; _scene_mesh_mutex.unlock(); SelectCloudToShow(!!show_scene ? CSD_RESET : CSD_LAST); return !!show_scene; } void RunVisualizationThread() { if (visualizer_thread.get() != NULL) return; visualizer_thread.reset(new boost::thread(visualizerCallback, this, (void*)NULL)); } void WaitForVisualizationThread() { if (visualizer_thread.get() == NULL) return; visualizer_thread->join(); visualizer_thread.reset(); } }; #include <sfm/MultiCameraPnP.h> #include <sfm/MeshBuilder.h> class VisualizerListener : public CloudVisualizer, public MultiCameraPnP::UpdateListener { MeshBuilder *mesh_builder; public: VisualizerListener(MeshBuilder *builder = NULL) : mesh_builder(builder) { /* empty */ } void setBuilder(MeshBuilder *builder) { mesh_builder = builder; } MeshBuilder* getBuilder() { return mesh_builder; } const MeshBuilder* getBuilder() const { return mesh_builder; } void update(const MultiCameraPnP &whos_updated); void finish(const MultiCameraPnP &whos_finished); };
#include <iostream.h> #include <conio.h> void main(){ clrscr(); int var=7,var2=8; int *ptr; ptr=&var; cout<<"\nValue of var:"<<var; cout<<"\nAddress of var:"<<&var; cout<<"\nValue of var (via ptr):"<<*ptr; cout<<"\nValue of var (via ptr)"<<ptr; cout<<"\n\nValue of var2:"<<var2; cout<<"\nAddress of var2:"<<&var2; --ptr; cout<<'\n'<<ptr; cout<<'\n'<<*ptr<<"\n"; getch(); /* char *p; char arr[6]={'D','h','r','u','v','\0'}; cout<<"\narray is:"<<arr; p=arr; cout<<"\nAddress of first element of array:"<<arr<<" "<<p; cout<<"\nAll elements of array:(arr[5]={'D','h','r','u','v','\0'})\n"; int i=0; while(*p!='\0'){ cout<<*arr; p++; } */ int list[5]={2,5,6,0,9}; cout<<" "<<0[list]<<" "<<3[list]<<" "<<1[list]<<" "<<2[list]; getch(); 3[list]=4[list]+6; cout<<*(list+3); getch(); }
class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_set<int> record(nums.begin(), nums.end()); int ans = 0; for(int num: nums){ if(!record.count(num-1)){ // only consider the situation that num is the start of consecutive sequence int end = num + 1; while(record.count(end)){ ++end; } ans = max(ans, end - num); } } return ans; } }; // way to calculate the start and end class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_set<int> record(nums.begin(), nums.end()); int ans = 0; for(int num: nums){ if(!record.count(num)) continue; record.erase(num); int prev = num-1; int next = num+1; while(record.count(prev)) record.erase(prev--); while(record.count(next)) record.erase(next++); ans = max(ans, next - prev - 1); } return ans; } }; /* class Solution { public: int longestConsecutive(vector<int>& nums) { unordered_map<int, vector<bool>> mp; unordered_map<int, bool> visited; for(int num: nums){ if(mp.count(num)) continue; mp[num] = {false,false}; visited[num] = false; if(mp.count(num-1)){ mp[num-1][1]= true; mp[num][0] = true; } if(mp.count(num+1)){ mp[num][1] = true; mp[num+1][0] = true; } } int max = 0; for(int num: nums){ if(visited[num]) continue; int len = dfs(num, 0, mp, visited) + dfs(num, 1, mp, visited) - 1; if(len > max) max = len; } return max; } int dfs(int key, int next, unordered_map<int, vector<bool>>& mp, unordered_map<int, bool>& visited){ visited[key] = true; if(!mp[key][next]) return 1; int nextKey = key + (next? 1: -1); return 1 + dfs(nextKey, next, mp, visited); } }; */
#include <bits/stdc++.h> using namespace std; int main(){ string s; cin >> s; reverse(s.begin(), s.end()); vector<string> v = {"dream", "dreamer", "erase", "eraser"}; for(int i=0; i<v.size(); i++) reverse(v[i].begin(), v[i].end()); string t = ""; for(int i=0; i<s.size(); i++){ for(int j=0; j<v.size(); j++){ int sz = v[j].size(); if((s.substr(i, sz)).size() < v[j].size()) continue; if(s.substr(i, sz) == v[j]){ i += sz - 1; t += v[j]; break; } } } if(s == t) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
#include "NTPClient.h" #include <PubSubClient.h> #include <ESP8266WiFi.h> #include <WiFiUdp.h> #include "esp8266.h" // WiFi objects IPAddress staticIP(192, 168, 0, 68); IPAddress gateway(192, 168, 0, 1); IPAddress subnet(255, 255, 255, 0); IPAddress primaryDNS(8, 8, 8, 8); IPAddress secondaryDNS(8, 8, 4, 4); IPAddress MQTTbroker(192, 168, 0, 189); // For timestamp char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; char GLOBAL_TIMESTAMP[60]; char DATE[10]; char TIME[15]; // Define NTP Client to get time WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org", UTC_OFFSET_SECONDS, UPDATE_INTERVAL); // Set up MQTT client WiFiClient espClient; PubSubClient MQTTclient(espClient); // Topic variables char TOPIC_MSG[MSG_BUFFER_SIZE]; char *TOPIC; char *TOPIC_DATA; void setup() { pinMode(ERR_LED, OUTPUT); /* configure LED on ESP8266 for debugging use */ digitalWrite(ERR_LED, HIGH); Serial.begin(9600); /* begin serial monitoring */ #ifdef DEBUG Serial.println("started serial monitor"); #endif setup_Wifi(); /* configure wifi settings */ timeClient.begin(); /* begin the NTP Client */ MQTTclient.setServer(MQTTbroker, 1883); /* start the MQTT client */ //MQTTclient.setCallback(callback); /* function to handle subscription updates */ digitalWrite(ERR_LED, LOW); Serial.print("done!\n"); } void loop() { timeClient.update(); /* updates the time based on an interval (see .h file for settings) */ if (!MQTTclient.connected()) /* connection broken? */ reconnect_to_broker(); MQTTclient.loop(); if (Serial.available() > 0) /* is data is available from Arduino? */ { char s_buff[100]; int bytes_read = Serial.readBytesUntil('\n', s_buff, 99); /* read arduino data from serial port */ s_buff[bytes_read] = '\0'; if (!strcmp(s_buff, TIMESTAMP_REQUEST)){ set_timestamp(); print_timestamp(); } else if (get_topic_and_topic_msg(s_buff)) /* topic name and data legible? */ { MQTTclient.publish(TOPIC, TOPIC_MSG); /* publish to topic */ } } // digitalWrite(ERR_LED, HIGH); // set_timestamp(); // print_timestamp(); // digitalWrite(ERR_LED, LOW); // delay(1000); } void setup_Wifi() { delay(3000); digitalWrite(ERR_LED, HIGH); WiFi.hostname(HOSTNAME); if (!WiFi.config(staticIP, gateway, subnet, primaryDNS, secondaryDNS)) { #ifdef DEBUG Serial.println("STA failed to configure"); #endif error_blink_leds(200); } #ifdef DEBUG Serial.print("Connecting..."); #endif WiFi.begin(SSID, SSID_PW); while (WiFi.status() != WL_CONNECTED) { delay(500); #ifdef DEBUG Serial.print("."); #endif } digitalWrite(ERR_LED, LOW); #ifdef DEBUG Serial.print("Connected!\nIP Address: "); Serial.println(WiFi.localIP()); #endif } /* function used to reconnect to MQTT broker in case of a lost cnxn */ void reconnect_to_broker() { // Loop until we're reconnected while (!MQTTclient.connected()) { // Create a random client ID (may want to keep this static, actually. a good ID could be the ESP8266's MAC address) #ifdef DEBUG Serial.print("Attempting MQTT connection..."); #endif char clientId[] = "ESP8266Client-1"; //int rand_id = random(0xffff), HEX); // replace with MAC address? // Attempt to connect if (MQTTclient.connect(clientId)) { #ifdef DEBUG Serial.println("connected"); #endif digitalWrite(ERR_LED, LOW); } else { #ifdef DEBUG Serial.print("failed, rc="); Serial.print(MQTTclient.state()); Serial.println(" try again in 5 seconds"); #endif error_blink_leds(400); // blink LEDS 4 times with 400ms as the delay } } } int get_topic_and_topic_msg(char *ser_data) { TOPIC = strtok(ser_data, " "); /* data comes in from arduino as "/DHN/<network #>/<node id>/<topic name> <data>"; delim is space */ if (TOPIC == NULL) return 0; TOPIC_DATA = strtok(NULL, " "); if (TOPIC_DATA == NULL) { #ifdef DEBUG Serial.print("Error: missing data point for topic "); Serial.print(TOPIC); Serial.println("\nPublishing terminated."); #endif return 0; } else { if (strcmp(TOPIC, "error_messages") == 0){ sprintf(TOPIC_MSG, "%s %s %s", ser_data, TIME, DATE); } else { sprintf(TOPIC_MSG, "%s %s %s", TOPIC_DATA, TIME, DATE); /* put a timestamp on data */ } return 1; } } void set_timestamp() { sprintf(TIME, "%s", timeClient.getFormattedTime().c_str()); sprintf(DATE, "%s", timeClient.getFormattedDate().c_str()); } void print_timestamp() { print_date(); print_time(); } void print_date(){ Serial.print(DATE); Serial.print('\n'); Serial.flush(); } void print_time(){ Serial.print(TIME); Serial.print('\n'); Serial.flush(); } void error_blink_leds(int ms) { digitalWrite(ERR_LED, HIGH); delay(ms); digitalWrite(ERR_LED, LOW); delay(ms); digitalWrite(ERR_LED, HIGH); delay(ms); digitalWrite(ERR_LED, LOW); delay(ms); digitalWrite(ERR_LED, HIGH); delay(ms); digitalWrite(ERR_LED, LOW); delay(ms); digitalWrite(ERR_LED, HIGH); delay(ms); digitalWrite(ERR_LED, LOW); delay(ms); digitalWrite(ERR_LED, HIGH); }
/** * Copyright (c) 2022, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "dump_internals.hh" #include "lnav.events.hh" #include "lnav.hh" #include "lnav_config.hh" #include "log_format_loader.hh" #include "sql_help.hh" #include "view_helpers.examples.hh" #include "yajlpp/yajlpp.hh" namespace lnav { void dump_internals(const char* internals_dir) { for (const auto* handlers : std::initializer_list<const json_path_container*>{ &lnav_config_handlers, &root_format_handler, &lnav::events::file::open::handlers, &lnav::events::file::format_detected::handlers, &lnav::events::log::msg_detected::handlers, &lnav::events::session::loaded::handlers, }) { dump_schema_to(*handlers, internals_dir); } execute_examples(); auto cmd_ref_path = ghc::filesystem::path(internals_dir) / "cmd-ref.rst"; auto cmd_file = std::unique_ptr<FILE, decltype(&fclose)>( fopen(cmd_ref_path.c_str(), "w+"), fclose); if (cmd_file != nullptr) { std::set<readline_context::command_t*> unique_cmds; for (auto& cmd : lnav_commands) { if (unique_cmds.find(cmd.second) != unique_cmds.end()) { continue; } unique_cmds.insert(cmd.second); format_help_text_for_rst( cmd.second->c_help, eval_example, cmd_file.get()); } } auto sql_ref_path = ghc::filesystem::path(internals_dir) / "sql-ref.rst"; auto sql_file = std::unique_ptr<FILE, decltype(&fclose)>( fopen(sql_ref_path.c_str(), "w+"), fclose); std::set<help_text*> unique_sql_help; if (sql_file != nullptr) { for (auto& sql : sqlite_function_help) { if (unique_sql_help.find(sql.second) != unique_sql_help.end()) { continue; } unique_sql_help.insert(sql.second); format_help_text_for_rst(*sql.second, eval_example, sql_file.get()); } } } } // namespace lnav
class names { public: wchar_t firstNames[2]; wchar_t lastNames[2]; names() { firstNames[2] = {L"Aaron", "Bob"}; } };
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_INTERFACE_GRAPHICSSERVICE_H_ #define BAJKA_INTERFACE_GRAPHICSSERVICE_H_ namespace Util { class Config; /** * */ class IGraphicsService { public: virtual ~IGraphicsService () {} virtual bool initDisplay (Util::Config *config) = 0; virtual void termDisplay () = 0; virtual void unbindSurfaceAndContext () = 0; /** * Zwraca true gdy powodzenie. */ virtual bool saveScreenDimensionsInConfig (Util::Config *config) = 0; virtual void swapBuffers () = 0; }; } #endif /* GRAPHICSSERVICE_H_ */
#pragma once #include <memory.h> typedef unsigned __int8 HSUInt8; typedef unsigned __int32 HSUInt32; enum HSBIT_STATE{ HSBIT_STATE_INVALID = -2, HSBIT_STATE_OVERACCESS, HSBIT_STATE_OFF, HSBIT_STATE_ON }; class CHSBits { private: HSUInt8 *pData; HSUInt32 m_NumberOfBytes; HSUInt32 m_NumberOfRestBits; public: CHSBits(void); ~CHSBits(void); bool Initialize(HSUInt32 NumberOfBits); bool Uninitialize(void); HSUInt32 GetAllocatedBitCount(void); HSUInt32 GetAllocatedByteCount(void); HSBIT_STATE SetBit(HSUInt32 IndexOfBits , HSBIT_STATE State); HSBIT_STATE GetBit(HSUInt32 IndexOfBits); bool SetBitByBoolean(HSUInt32 IndexOfBits , bool bState); bool GetBitByBoolean(HSUInt32 IndexOfBits); int SetBitByInteger(HSUInt32 IndexOfBits , int iState); int GetBitByInteger(HSUInt32 IndexOfBits); HSUInt32 CountBits(HSBIT_STATE State); bool FillBits(HSBIT_STATE State); void InvertBits(void); };
// Copyright (c) 2019-2020 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _WNT_HIDSpaceMouse_Header #define _WNT_HIDSpaceMouse_Header #include <Aspect_VKey.hxx> #include <Graphic3d_Vec.hxx> //! Wrapper over Space Mouse data chunk within WM_INPUT event (known also as Raw Input in WinAPI). //! This class predefines specific list of supported devices, which does not depend on 3rdparty library provided by mouse vendor. //! Supported input chunks: //! - Rotation (3 directions); //! - Translation (3 directions); //! - Pressed buttons. //! //! To use the class, register Raw Input device: //! @code //! Handle(WNT_Window) theWindow; //! RAWINPUTDEVICE aRawInDevList[1]; //! RAWINPUTDEVICE& aRawSpace = aRawInDevList[0]; //! aRawSpace.usUsagePage = HID_USAGE_PAGE_GENERIC; //! aRawSpace.usUsage = HID_USAGE_GENERIC_MULTI_AXIS_CONTROLLER; //! aRawSpace.dwFlags = 0; // RIDEV_DEVNOTIFY //! aRawSpace.hwndTarget = (HWND )theWindow->NativeHandle(); //! if (!::RegisterRawInputDevices (aRawInDevList, 1, sizeof(aRawInDevList[0]))) { Error; } //! @endcode //! //! Then handle WM_INPUT events within window message loop. //! @code //! AIS_ViewController theViewCtrl; //! case WM_INPUT: //! { //! UINT aSize = 0; //! ::GetRawInputData ((HRAWINPUT )theLParam, RID_INPUT, NULL, &aSize, sizeof(RAWINPUTHEADER)); //! NCollection_LocalArray<BYTE> aRawData (aSize); // receive Raw Input for any device and process known devices //! if (aSize == 0 || ::GetRawInputData ((HRAWINPUT )theLParam, RID_INPUT, aRawData, &aSize, sizeof(RAWINPUTHEADER)) != aSize) //! { //! break; //! } //! const RAWINPUT* aRawInput = (RAWINPUT* )(BYTE* )aRawData; //! if (aRawInput->header.dwType != RIM_TYPEHID) //! { //! break; //! } //! //! RID_DEVICE_INFO aDevInfo; aDevInfo.cbSize = sizeof(RID_DEVICE_INFO); //! UINT aDevInfoSize = sizeof(RID_DEVICE_INFO); //! if (::GetRawInputDeviceInfoW (aRawInput->header.hDevice, RIDI_DEVICEINFO, &aDevInfo, &aDevInfoSize) != sizeof(RID_DEVICE_INFO) //! || (aDevInfo.hid.dwVendorId != WNT_HIDSpaceMouse::VENDOR_ID_LOGITECH //! && aDevInfo.hid.dwVendorId != WNT_HIDSpaceMouse::VENDOR_ID_3DCONNEXION)) //! { //! break; //! } //! //! Aspect_VKeySet& aKeys = theViewCtrl.ChangeKeys(); //! const double aTimeStamp = theViewCtrl.EventTime(); //! WNT_HIDSpaceMouse aSpaceData (aDevInfo.hid.dwProductId, aRawInput->data.hid.bRawData, aRawInput->data.hid.dwSizeHid); //! if (aSpaceData.IsTranslation()) //! { //! // process translation input //! bool isIdle = true, isQuadric = true; //! const Graphic3d_Vec3d aTrans = aSpaceData.Translation (isIdle, isQuadric); //! aKeys.KeyFromAxis (Aspect_VKey_NavSlideLeft, Aspect_VKey_NavSlideRight, aTimeStamp, aTrans.x()); //! aKeys.KeyFromAxis (Aspect_VKey_NavForward, Aspect_VKey_NavBackward, aTimeStamp, aTrans.y()); //! aKeys.KeyFromAxis (Aspect_VKey_NavSlideUp, Aspect_VKey_NavSlideDown, aTimeStamp, aTrans.z()); //! } //! if (aSpaceData.IsRotation()) {} // process rotation input //! if (aSpaceData.IsKeyState()) {} // process keys input //! break; //! } //! @endcode class WNT_HIDSpaceMouse { public: //! Vendor HID identifier. enum { VENDOR_ID_LOGITECH = 0x46D, VENDOR_ID_3DCONNEXION = 0x256F }; //! Return if product id is known by this class. Standard_EXPORT static bool IsKnownProduct (unsigned long theProductId); public: //! Main constructor. Standard_EXPORT WNT_HIDSpaceMouse (unsigned long theProductId, const Standard_Byte* theData, Standard_Size theSize); //! Return the raw value range. int16_t RawValueRange() const { return myValueRange; } //! Set the raw value range. void SetRawValueRange (int16_t theRange) { myValueRange = theRange > myValueRange ? theRange : myValueRange; } //! Return TRUE if data chunk defines new translation values. bool IsTranslation() const { return myData[0] == SpaceRawInput_Translation && (mySize == 7 || mySize == 13); } //! Return new translation values. //! @param theIsIdle [out] flag indicating idle state (no translation) //! @param theIsQuadric [in] flag to apply non-linear scale factor //! @return vector of 3 elements defining translation values within [-1..1] range, 0 meaning idle, //! .x defining left/right slide, .y defining forward/backward and .z defining up/down slide. Standard_EXPORT Graphic3d_Vec3d Translation (bool& theIsIdle, bool theIsQuadric) const; //! Return TRUE if data chunk defines new rotation values. bool IsRotation() const { return (myData[0] == SpaceRawInput_Rotation && mySize == 7) || (myData[0] == SpaceRawInput_Translation && mySize == 13); } //! Return new rotation values. //! @param theIsIdle [out] flag indicating idle state (no rotation) //! @param theIsQuadric [in] flag to apply non-linear scale factor //! @return vector of 3 elements defining rotation values within [-1..1] range, 0 meaning idle, //! .x defining tilt, .y defining roll and .z defining spin. Standard_EXPORT Graphic3d_Vec3d Rotation (bool& theIsIdle, bool theIsQuadric) const; //! Return TRUE for key state data chunk. bool IsKeyState() const { return myData[0] == SpaceRawInput_KeyState; } //! Return new keystate. uint32_t KeyState() const { return *reinterpret_cast<const uint32_t*>(myData + 1); } //! Convert key state bit into virtual key. Standard_EXPORT Aspect_VKey HidToSpaceKey (unsigned short theKeyBit) const; private: //! Translate raw data chunk of 3 int16 values into normalized vec3. //! The values are considered within the range [-350; 350], with 0 as neutral state. Graphic3d_Vec3d fromRawVec3 (bool& theIsIdle, const Standard_Byte* theData, bool theIsTrans, bool theIsQuadric) const; //! Data chunk type. enum { SpaceRawInput_Translation = 0x01, //!< translation data chunk SpaceRawInput_Rotation = 0x02, //!< rotation data chunk SpaceRawInput_KeyState = 0x03, //!< keystate data chunk }; private: const Standard_Byte* myData; //!< RAW data chunk Standard_Size mySize; //!< size of RAW data chunk unsigned long myProductId; //!< product id mutable int16_t myValueRange; //!< RAW value range }; #endif // _WNT_HIDSpaceMouse_Header
#ifndef CSTATDATATOOL_H #define CSTATDATATOOL_H #include <vector> #include <string> #include "module_base_def.h" #include "configfile.h" struct cJSON; /** @struct * @brief 统计选择项,是否进行统计保存 */ typedef struct _StatRecordItem { public: _StatRecordItem() { rms[0] = rms[1] = true; ang[0] = ang[1] = true; pos_peak[0] = pos_peak[1] = true; neg_peak[0] = neg_peak[1] = true; harm_dc_rms[0] = harm_dc_rms[1] = true; harm_dc_per[0] = harm_dc_per[1] = true; harm_thd_rms[0] = harm_thd_rms[1] = true; harm_thd_per[0] = harm_thd_per[1] = true; for (int i = 0; i != HARM_MAX; i++) { harm_rms[0][i] = harm_rms[1][i] = true; harm_per[0][i] = harm_per[1][i] = true; harm_ang[0][i] = harm_ang[1][i] = true; harm_power[i] = true; } for (int i = 0; i != INTER_HARM_MAX; i++) { inter_harm_rms[0][i] = inter_harm_rms[1][i] = false; inter_harm_per[0][i] = inter_harm_per[1][i] = false; } for (int i = 0; i != HIGH_HARM_MAX; i++) { high_harm_rms[0][i] = high_harm_rms[1][i] = false; high_harm_per[0][i] = high_harm_per[1][i] = false; } active_power = reactive_power = \ apparent_power = power_factor = true; pos_value[0] = pos_value[1] = true; neg_value[0] = neg_value[1] = true; zero_value[0] = zero_value[1] = true; neg_unbalance[0] = neg_unbalance[1] = true; zero_unbalance[0] = zero_unbalance[1] = true; frequency = true; } bool rms[2]; bool ang[2]; bool pos_peak[2]; bool neg_peak[2]; bool harm_dc_rms[2]; bool harm_dc_per[2]; bool harm_thd_rms[2]; bool harm_thd_per[2]; bool harm_rms[2][HARM_MAX]; bool harm_per[2][HARM_MAX]; bool harm_ang[2][HARM_MAX]; bool harm_power[HARM_MAX]; bool inter_harm_rms[2][INTER_HARM_MAX]; bool inter_harm_per[2][INTER_HARM_MAX]; bool high_harm_rms[2][HIGH_HARM_MAX]; bool high_harm_per[2][HIGH_HARM_MAX]; bool active_power; bool reactive_power; bool apparent_power; bool power_factor; bool pos_value[2]; bool neg_value[2]; bool zero_value[2]; bool neg_unbalance[2]; bool zero_unbalance[2]; bool frequency; }StatRecordItem; /** @struct * @brief 统计保存信息 */ typedef struct _StatRecordInfo { DateTime startTime; // 统计开始时间 DateTime endTime; // 统计结束时间 DateTime firstTime; // 第一个统计数据的时间 int statCycle; // 统计间隔,秒数,-1位十周波统计间隔 int statTotalCnt; // 总统计点数 StatRecordItem recItem; // 统计选择项 MeasureConfig meaCfg; // 测量参数 }StatRecordInfo; typedef enum _StatFuncType { Stat_Func_None = 0, Stat_Func_Write, Stat_Func_Read }StatFuncType; typedef struct _StatOneData { std::vector<float> max_val; // 最大值 std::vector<float> min_val; // 最小值 std::vector<float> avg_val; // 平均值 std::vector<float> cp95_val; // 95%概率大值 }StatOneData; typedef std::vector<StatOneData> StatDatas; class CStatDataTool { public: CStatDataTool(); virtual ~CStatDataTool(); public: bool InitWriteFile(const std::string &fileName); bool WriteDataToFile(const StatDatas &dat); bool InitReadFile(const std::string &fileName, int datCount); bool ReadDataFromFile(int begIdx, int endIdx, StatDatas &dat); public: bool WriteInfoToFile(const std::string &fileName, const StatRecordInfo &info); bool ReadInfoFromFile(const std::string &fileName, StatRecordInfo &info); protected: /** @brief 保存统计信息文件 * @param[in] item 统计选择项 * @return Json格式对象 */ cJSON* _statRecItemToJson(const StatRecordItem &item); /** @brief 解析统计信息文件 * @param[in] node json节点 * @param[out] item 统计选择项 * @return Json格式对象 */ bool _jsonTostatRecItem(cJSON *node, StatRecordItem &item); /** @brief 从Json格式对象中获取测量参数 * @param[in] obj Json格式对象 * @param[out] cfg 测量参数 * @return true -- 获取成功 */ bool _jsonObjToMeasureCfg(cJSON *obj, MeasureConfig &cfg); /** @brief 将测量参数转为Json格式对象 * @param[in] cfg 需转化的测量参数 * @return Json格式对象 */ cJSON* _measureCfgToJsonObj(const MeasureConfig &cfg); protected: int m_funcType; // 读写StatDatas功能 int m_datCount; // StatOneData数据中vector的数组个数 std::string m_datFileName; }; #endif // CSTATDATATOOL_H
#ifndef _DISPATCH_H_ #define _DISPATCH_H_ #include "../FormDef.h" class CDispatch : public evwork::PHClass { public: DECLARE_FORM_MAP; // 通用协议处理 void onEnterRoomReply(evwork::Jpacket& packet, evwork::IConn* pConn); void onEnterRoomFail(evwork::Jpacket& packet, evwork::IConn* pConn); void onReadyReply(evwork::Jpacket& packet, evwork::IConn* pConn); void onReadyFail(evwork::Jpacket& packet, evwork::IConn* pConn); void onStartRound(evwork::Jpacket& packet, evwork::IConn* pConn); void onTableInfoReply(evwork::Jpacket& packet, evwork::IConn* pConn); void onNextRound(evwork::Jpacket& packet, evwork::IConn* pConn); void onChangeTableFail(evwork::Jpacket& packet, evwork::IConn* pConn); void onLogoutOK(evwork::Jpacket& packet, evwork::IConn* pConn); // 非通用协议处理 void onInitHandCards(evwork::Jpacket& packet, evwork::IConn* pConn); void onBankerLastCard(evwork::Jpacket& packet, evwork::IConn* pConn); void onNoticeOutCard(evwork::Jpacket& packet, evwork::IConn* pConn); void onSomeOneOutCard(evwork::Jpacket& packet, evwork::IConn* pConn); void onDoAction(evwork::Jpacket& packet, evwork::IConn* pConn); void onSomeOneEat(evwork::Jpacket& packet, evwork::IConn* pConn); void onOutCardOK(evwork::Jpacket& packet, evwork::IConn* pConn); void onSyncHandCards(evwork::Jpacket& packet, evwork::IConn* pConn); }; #endif
#pragma once #include "bricks/java/jobject.h" #include "bricks/java/jmethoddelegate.h" namespace Bricks { namespace Java { namespace Lang { BRICKS_JAVA_QUALIFIED_CLASS_START(ObjectClass, "java/lang/Object"); BRICKS_JAVA_QUALIFIED_CLASS_CONSTRUCTOR_END(); BRICKS_JAVA_QUALIFIED_CLASS_END(); BRICKS_JAVA_QUALIFIED_OBJECT_START(Object, ObjectClass); BRICKS_JAVA_QUALIFIED_OBJECT_CONSTRUCTOR_END(); BRICKS_JAVA_QUALIFIED_OBJECT_END(); } } } namespace Bricks { namespace Java { namespace Internal { template<> struct JSignature<JObject> { static String Signature() { return JSignature<Lang::Object>::Signature(); } }; } } }
#include "stdafx.h" #include "History.h" void History::makeUndoRecord(HistoryRecord record) { UndoStack.push(record); } void History::makeRedoRecord(HistoryRecord record) { RedoStack.push(record); } History::HistoryRecord History::makeUndo() { History::HistoryRecord undo = UndoStack.top(); UndoStack.pop(); return undo; } History::HistoryRecord History::makeRedo() { History::HistoryRecord redo = RedoStack.top(); RedoStack.pop(); return redo; } bool History::canUndo() { return !UndoStack.empty(); } bool History::canRedo() { return !RedoStack.empty(); } void History::flushHistory() { while(!UndoStack.empty()) { UndoStack.pop(); } while (!RedoStack.empty()) { RedoStack.pop(); } } void History::flushRedo() { while (!RedoStack.empty()) { RedoStack.pop(); } } void saveStack(MemoryFile& ar, stack<History::HistoryRecord> someStack) // Save reversed stack to ar // Stack on input will be emptied { stack<History::HistoryRecord> stackBuf; while (someStack.size()) { stackBuf.push(someStack.top()); someStack.pop(); } ar << stackBuf.size(); while (stackBuf.size()) { ar << stackBuf.top(); stackBuf.pop(); } } MemoryFile& operator << (MemoryFile& memFile, History history) { stack<History::HistoryRecord> undoStackBuf(history.UndoStack), redoStackBuf(history.RedoStack); saveStack(memFile, undoStackBuf); saveStack(memFile, redoStackBuf); return memFile; } MemoryFile& operator >> (MemoryFile& ar, History& history) { int undoStackElems; ar >> undoStackElems; for (int i = 0; i < undoStackElems; i++) { History::HistoryRecord historyBuf; ar >> historyBuf; history.UndoStack.push(historyBuf); } int redoStackElems; ar >> redoStackElems; for (int i = 0; i < redoStackElems; i++) { History::HistoryRecord historyBuf; ar >> historyBuf; history.RedoStack.push(historyBuf); } return ar; } MemoryFile& operator >> (MemoryFile& stream, History::HistoryRecord& record) { stream >> record.before >> record.after; return stream; } MemoryFile& operator << (MemoryFile& stream, const History::HistoryRecord record) { stream << record.before << record.after; return stream; } MemoryFile& operator >> (MemoryFile& stream, History::Cell& cell) { stream >> cell.x >> cell.y; return stream; } MemoryFile& operator << (MemoryFile& stream, const History::Cell cell) { stream << cell.x << cell.y; return stream; } int History::getSize() { return (RedoStack.size() + UndoStack.size() * sizeof(HistoryRecord)); } stack<History::HistoryRecord> History::getUndoStackReversedCopy(){ stack<History::HistoryRecord> undoCopy(UndoStack); stack<History::HistoryRecord> stackBuf; while (undoCopy.size()) { stackBuf.push(undoCopy.top()); undoCopy.pop(); } return stackBuf; }
#ifndef __Java_org_cocos2dx_lib_Cocos2dxGreePayment_H__ #define __Java_org_cocos2dx_lib_Cocos2dxGreePayment_H__ #include <string.h> #include "cocos2d.h" extern "C" { // PaymentItem jobject createPaymentItemJni(const char *itemId, const char* itemName, double unitPrice, int quantity); void setImageUrlJni(jobject obj, const char *url); void setDescriptionJni(jobject obj, const char *desc); std::string getItemIdJni(jobject obj); std::string getItemNameJni(jobject obj); double getUnitPriceJni(jobject obj); int getQuantityJni(jobject obj); std::string getImageUrlJni(jobject obj); std::string getDescriptionJni(jobject obj); // Payment jobject createPaymentJni(const char *message, cocos2d::CCArray *items); void setPaymentHandlerJni(jobject obj, void *delegate); void requestJni(jobject obj, void *delegate); void requestWithHandlerJni(jobject obj, void *delegate); void setCallbackUrlJni(jobject obj, const char *url); void verifyJni(const char *paymentId); } #endif
#include <iostream> #include <vector> #include <algorithm> /* * The book provides faster solutions for this * * The strings don't need to be sorted, they could just use an * unordered_map to check if two strings are anagrams * * The array doesn't need to be sorted. The anagrams just need to be * grouped together. * * I think we could get to a solution of O(n * s) * where n is the number of strings and s is the length * of the longest string * */ using namespace std; class SortedString { private: string orig; string sorted; public: SortedString(string& c_orig) :orig{c_orig}, sorted{c_orig} { sort(sorted.begin(), sorted.end()); }; string& get_original() { return orig; } string& get_sorted() { return sorted; } bool operator<(const SortedString& ss) { return sorted < ss.sorted; } }; void group_anagrams(vector<string>& vec) { vector<SortedString> ss_vec {}; for (auto& str : vec) { ss_vec.push_back({str}); } sort(ss_vec.begin(), ss_vec.end()); for (int i = 0; i < ss_vec.size(); i++) { vec.at(i) = ss_vec[i].get_original(); } } void run_group_anagrams(vector<string> vec) { group_anagrams(vec); for (auto& str : vec) { cout << str << ", "; } cout << "\n" << endl; } int main() { run_group_anagrams({"dog", "cat", "act", "bird", "god", "zebra"}); }
#include <iostream> using namespace std; int longitud(char *cadena) { int c=0; for(;*cadena!='\0';cadena++) { c++; } return c; } int main() { char *cadena= new char[100]; cout<<"Ingrese cadena:"<<endl; cin>>cadena; cout<<"LONGITUD DE CADENA ES=>"<<longitud(cadena); }
// // Collision.cpp // Project2 // // Created by William Meaton on 26/01/2016. // Copyright © 2016 WillMeaton.uk. All rights reserved. // #include "Collision.h" namespace Math { lineCollide::lineCollide(const Math::Vector2D &v1, const Math::Vector2D &v2){ this->v1 = v1; this->v2 = v2; } Math::Vector2D lineCollisionCheckX(const Math::Vector2D &originalPosition, const Math::Vector2D &proposedMovement, const lineCollide &lc){ if(originalPosition.x < lc.v1.x && proposedMovement.x > lc.v1.x){ return Math::Vector2D(lc.v1.x, proposedMovement.y); } return proposedMovement; } Math::Vector2D lineCollisionCheckY(const Math::Vector2D &originalPosition, const Math::Vector2D &proposedMovement, const lineCollide &lc){ if(originalPosition.y < lc.v1.y && proposedMovement.y > lc.v1.y){ return Math::Vector2D(proposedMovement.x, lc.v1.y); } return proposedMovement; } //returns if v3 is inside of v1-v2 bool isInsideQuad(const Vector2D &point, const Vector2D &v1, const Vector2D &v2){ return Math::isInsideQuad(point.x, point.y, v1.x, v1.y, v2.x, v2.y); } bool isInsideQuad(const Vector2D &point, const Vector2D &v, float w, float h){ return Math::isInsideQuad(point.x, point.y, v.x, v.y, w, h); } bool isInsideQuad(const Vector2D &point, const Graphics::Rect &r){ return Math::isInsideQuad(point.x, point.y, r.getX(), r.getY(), r.getWidth(), r.getHeight()); } bool isInsideQuad(const float &x1, const float &y1, const float &x2, const float &y2, const float &x3, const float &y3){ if(x1 > x2 && x1 < x3 && y1 > y2 && x3 < y3){ return true; } return false; } float signVector(float x1, float y1, float x2, float y2, float x3, float y3){ return signVector(Vector2D(x1, y1), Vector2D(x2, y2), Vector2D(x3, y3)); } float signVector(const Vector2D &v1, const Vector2D &v2, const Vector2D &v3){ float det = 0.0f; det = ((v1.x - v3.x) * (v2.y - v3.y)) - ((v2.x - v3.x) * (v1.y - v3.y)); return (det / 2.0f); } float signVector(const Graphics::Triangle &t){ return signVector(t.getV1(), t.getV2(), t.getV3()); } bool isInsideTriangle(const Vector2D &point, const Vector2D &v1, const Vector2D &v2, const Vector2D &v3){ bool b1, b2, b3; b1 = signVector(point, v1, v2) < 0.0f; b2 = signVector(point, v2, v3) < 0.0f; b3 = signVector(point, v3, v1) < 0.0f; return ((b1 == b2) && (b2 == b3)); } bool isInsideTriangle(const Vector2D &point, const Graphics::Triangle &t){ return isInsideTriangle(point, t.getV1(), t.getV2(), t.getV3()); } bool isInsideEllipse(const Vector2D &point, const Vector2D &cp, float xR, float yR) { //(((x-cp.x)^2)/rX^2 + ((y-cp.y)^2)/rY^2) <= 1 return ( (pow((point.x-cp.x),2)/pow(xR,2)) + (pow((point.y-cp.y),2)/pow(yR,2)) ) <=1; } bool isInsideEllipse(const Vector2D &point, const Graphics::Ellipse &e) { //(((x-cp.x)^2)/rX^2 + ((y-cp.y)^2)/rY^2) <= 1 return ( (pow((point.x-e.getVec().x),2)/pow(e.getXR(),2)) + (pow((point.y-e.getVec().y),2)/pow(e.getYR(),2)) ) <=1; } bool isInsideEllipse(const Vector2D &point, const Vector2D &cp, float r) { return isInsideEllipse(point, cp, r, r); } float vectorDistance(const Vector2D& v1, const Vector2D& v2){ return sqrt((v1.x-v2.x)*(v1.x-v2.x)+(v1.y-v2.y)*(v1.y-v2.y)); } float vectorDistance(float x1, float y1, float x2, float y2){ return vectorDistance(Vector2D(x1, y1), Vector2D(x2, y2)); } }
#include "Loc.cpp" using namespace std; int main(){ Loc ob1(10,20), ob2; Loc ob3 = ob1; cout << "Enter a location coordinates (a,b) : " << endl; cin >> ob2; cout << "ob1 " << ob1 << endl; cout << "ob2 " << ob2 << endl; cout << "ob3 " << ob3 << endl; ++ob1; // incrementing latitude cout << "ob1 " << ob1 << endl; ob2++; // incrementing longitude cout << "ob2 " << ob2 << endl; Loc ob4 = ob2; cout << "ob4 " << ob4 << endl; ob4 = ob4 + 20; // adding to longitude cout << "ob4 " << ob4 << endl; ob3 = 30 + ob3; // adding to latitude cout << "ob3 " << ob3 << endl; ob3 = ob4 + ob2; // adding both locations cout << "ob3 " << ob3 << endl; }
#include<vector> using std::vector; #include<iostream> #include<algorithm> #include<memory> using std::shared_ptr; #include<string> using std::string; #include<stack> using std::stack; #include<queue> using std::priority_queue; #include<unordered_map> using std::unordered_map; #include<list> using std::list; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode * rotateRight(ListNode* head, int k) { if (head == nullptr)return head; ListNode* slow; ListNode* fast; if (k == 0)return head; slow = fast = head; int count = 0; while (k--) { if (fast == nullptr) { fast = head; k = k % count; } fast = fast->next; count++; }; if (fast == nullptr)return head; while (fast->next != nullptr) { slow = slow->next; fast = fast->next; } ListNode* ans = slow->next; slow->next = fast->next; fast->next = head; return ans; } }; int main() { Solution s; s.generateMatrix(4); }
/* * entity.hpp * * @author Jeremy Elkayam */ #pragma once #include "entity.hpp" #include <iostream> class Sword : public Entity { private: bool active; public: Sword(float xcor, float ycor, sf::Texture &texture, float warrior_width, sf::Color color); //void set_active(bool active){this->active = active;} void unsheath(){this->active = true; } void sheath(){this->active = false; } void draw(sf::RenderWindow &window, ColorGrid &grid) const override {if(active) Entity::draw(window,grid);} void update(float xcor, float ycor, float angle); void update(float xcor, float ycor){sprite.setPosition(xcor,ycor);}; bool is_active() const {return active;} };
#include <iostream> #include <vector> #include <queue> #define x first #define y second using namespace std; int n, cmd; vector<pair<int, int>> checkPoint; queue<int> q; bool isAvailable(int curCP, int tarCP, int dist){ /* 현재 체크포인트에서 해당 체크 포인트 갈 수 있나 검사 */ /* 1. 그냥 걸어서 도달한다. 2. 걸어서 목표 체크포인트의 x좌표나 y 좌표로 간다. - 부스터를 쓴다 */ int curX = checkPoint[curCP].x; int curY = checkPoint[curCP].y; int tarX = checkPoint[tarCP].x; int tarY = checkPoint[tarCP].y; int minX = curX - dist; int maxX = curX + dist; int minY = curY - dist; int maxY = curY + dist; /* tarX 나 tarY 중 하나만 범위 사이에 있으면 된다 */ if((tarX >= minX && tarX <= maxX) || (tarY >= minY && tarY <= maxY)){ return true; } return false; } bool simulate(int cp1, int cp2, int mHp, bool visited[]){ /* 현재 체크포인트에서 도달 할 수 있는 체크포인트들을 기준으로 BFS 를 수행한다. */ int checkSize = checkPoint.size(); q.push(cp1); visited[cp1] = true; bool ret = false; while(!q.empty()){ int curCh = q.front(); q.pop(); for(int i = 1; i < checkSize; i++){ if(!visited[i] && isAvailable(curCh, i, mHp)){ /* 방문 안했고 도달 가능하면 방문 */ q.push(i); visited[i] = true; if(i == cp2){ ret = true; while(!q.empty()){ q.pop(); } break; } } } } return ret; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); /* empty check for index count */ checkPoint.push_back(make_pair(0, 0)); cin >> n >> cmd; while(n--){ int _x, _y; cin >> _x >> _y; checkPoint.push_back(make_pair(_x, _y)); } while(cmd--){ /* 방문 기록 초기화 */ bool visit[250001] = {false, }; int check1, check2, maxHp; cin >> check1 >> check2 >> maxHp; if(simulate(check1, check2, maxHp, visit)){ cout << "YES" << '\n'; }else{ cout << "NO" << '\n'; } } return 0; }
#include<bits/stdc++.h> using namespace std; int main() { int n, index; int arr[1000]; cin>>n; for(int i=0;i<n;i++) { cin>>arr[i]; } index = min_element(arr, arr+n)-arr; cout<<"Menor valor: "<<arr[index]<<"\n"; cout<<"Posicao: "<<index<<"\n"; return 0; }
#include <core/macro/try.h> #include <core/match.h> #include <core/net/uri/Path.h> #include <core/operator==.h> #include <core/sequence/count.h> #include <core/to.h> #include <launcher/extends/core/Parse.h> namespace core { Result< launcher::cli::Options, Union< launcher::cli::error::BatOption, launcher::cli::error::NotEnoughArguments > > Parse<launcher::cli::Options, For<cli::Arguments>>::operator()(cli::Arguments a) const noexcept { using net::uri::Path; using sequence::count; using launcher::cli::Options; using launcher::cli::error::BatOption; using launcher::cli::error::NotEnoughArguments; using CliError = Union< launcher::cli::error::BatOption, launcher::cli::error::NotEnoughArguments >; using encoding::Utf8; using encoding::Utf32; decltype(auto) options = Options { false, U"/etc/launcher/launcher.json", U"/etc/launcher/launcher.css" }; for (decltype(auto) i = Size {1}; i < count(a); i += 1) { core_macro_try(decltype(auto) x, match(parse<Utf32>(a(i)), [] (Error<Unit>) { return Error<CliError> {BatOption {}}; } )); if (x == U"-h" || x == U"--help") { options.help = true; return OK<Options> {options}; } else if (x == U"-c" || x == U"--config") { if ((i += 1) == count(a)) { return Error<CliError> {NotEnoughArguments {to<Utf8>(x)}}; } else { core_macro_try(decltype(auto) y, match(parse<encoding::Utf32>(a(i)), [&] (Error<Unit>) { return Error<CliError> {BatOption {to<Utf8>(x)}}; } )); core_macro_try(decltype(auto) p, match(parse<Path>(y), [&] (Error<Unit>) { return Error<CliError> {BatOption {to<Utf8>(x)}}; } )); options.config_path = p; } } else if (x == U"-s" || x == U"--stylesheet") { if ((i += 1) == count(a)) { return Error<CliError> {NotEnoughArguments {to<Utf8>(x)}}; } else { core_macro_try(decltype(auto) y, match(parse<Utf32>(a(i)), [&] (Error<Unit>) { return Error<CliError> {BatOption {to<Utf8>(x)}}; } )); core_macro_try(decltype(auto) p, match(parse<Path>(y), [&] (Error<Unit>) { return Error<CliError> {BatOption {to<Utf8>(x)}}; } )); options.style_sheet_path = p; } } else { return Error<CliError> {BatOption {to<Utf8>(x)}}; } } return OK<Options> {options}; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Alexander Remen (alexr@opera.com) * */ #include "core/pch.h" #ifdef M2_SUPPORT #include "adjunct/desktop_pi/DesktopOpSystemInfo.h" #include "adjunct/m2_ui/util/AttachmentOpener.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/controller/SimpleDialogController.h" #include "adjunct/quick/dialogs/DownloadDialog.h" #include "modules/locale/oplanguagemanager.h" #include "modules/url/url2.h" #include "modules/viewers/viewers.h" #include "modules/windowcommander/src/TransferManagerDownload.h" class ExecuteAttachmentDialog : public SimpleDialogController { public: ExecuteAttachmentDialog() : SimpleDialogController(TYPE_OK_CANCEL, IMAGE_WARNING, WINDOW_NAME_EXECUTE_ATTACHMENT, Str::S_WARNING_RUN_ATTACHMENT,Str::SI_IDSTR_MSG_MAILFREPFS_INVALID_SETTINGS_CAP) { } OP_STATUS Init(const uni_char * a_handler, const uni_char * a_attachment) { RETURN_IF_ERROR(m_handler.Set(a_handler)); return m_attachment.Set(a_attachment); } virtual void OnOk() { g_desktop_op_system_info->OpenFileInApplication(m_handler.CStr(), m_attachment.CStr()); SimpleDialogController::OnOk(); } private: OpString m_handler; OpString m_attachment; }; BOOL AttachmentOpener::OpenAttachment(URL* url, DesktopFileChooser* chooser, DesktopWindow* parent_window) { if (!url) return TRUE; // [Security Issue] rfz 2006-4-20: // If Opera is handling the resource, it would be a security issue // to move the attachment from cache to the temporary download folder. //Get mimetype so that the viewer can be found: const char* mimetype = url->GetAttribute(URL::KMIME_Type).CStr(); OpString mime_type; mime_type.Set(mimetype); // The handler that will open the file OpString handler; // Consult viewer on how the mimetype should be handled: Viewer *viewer = g_viewers->FindViewerByMimeType(mime_type); if(viewer) { ViewAction view_action = viewer->GetAction(); if(view_action == VIEWER_OPERA || view_action == VIEWER_PLUGIN) { OpString url_name; if (OpStatus::IsSuccess(url->GetAttribute(URL::KUniName_Username_Password_Hidden, url_name)) && url_name.HasContent()) { g_application->GoToPage(url_name.CStr(), TRUE, FALSE, FALSE, 0, url->GetContextId()); } return TRUE; } else if(view_action == VIEWER_APPLICATION) { // Use the user configured handler RETURN_VALUE_IF_ERROR(handler.Set(viewer->GetApplicationToOpenWith()), TRUE); } } // If opera is not handling the resource: // First make sure that we open from temporary download folder // not from cache. OpString openfrom_filename; OpString tmp_storage; openfrom_filename.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_TEMPDOWNLOAD_FOLDER, tmp_storage)); if( openfrom_filename.Length() > 0 && openfrom_filename[openfrom_filename.Length()-1] != PATHSEPCHAR ) openfrom_filename.Append(PATHSEP); OpString fname; TRAPD(err, url->GetAttributeL(URL::KSuggestedFileName_L, fname, TRUE)); openfrom_filename.Append(fname); url->LoadToFile(openfrom_filename.CStr()); // If the user did not configure a handler then use the default handler from the system if(handler.IsEmpty()) g_op_system_info->GetFileHandler(&openfrom_filename, mime_type, handler); if(handler.HasContent()) { if(g_op_system_info->GetIsExecutable(&openfrom_filename)) { ExecuteAttachmentDialog * ead = OP_NEW(ExecuteAttachmentDialog, ()); RETURN_VALUE_IF_NULL(ead, TRUE); RETURN_VALUE_IF_ERROR(ead->Init(handler.CStr(), openfrom_filename.CStr()), TRUE); RETURN_VALUE_IF_ERROR(ShowDialog(ead, g_global_ui_context, parent_window), TRUE); } else { g_desktop_op_system_info->OpenFileInApplication(handler.CStr(), openfrom_filename.CStr()); } } else { ViewActionFlag view_action_flag; TransferManagerDownloadCallback * download_callback = OP_NEW(TransferManagerDownloadCallback, (NULL, *url, NULL, view_action_flag)); if (!chooser) RETURN_VALUE_IF_ERROR(DesktopFileChooser::Create(&chooser), TRUE); DownloadItem * di = OP_NEW(DownloadItem, (download_callback, chooser, TRUE)); if (di) { DownloadDialog* dialog = OP_NEW(DownloadDialog, (di)); if (dialog) dialog->Init(parent_window); else OP_DELETE(di); } } return TRUE; } #endif // M2_SUPPORT
// #include <boost/multiprecision/cpp_int.hpp> // using boost::multiprecision::cpp_int; #include <bits/stdc++.h> using namespace std; // ¯\_(ツ)_/¯ #define f first #define s second #define p push #define mp make_pair #define pb push_back #define eb emplace_back #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define foi(i, a, n) for (i = (a); i < (n); ++i) #define foii(i, a, n) for (i = (a); i <= (n); ++i) #define fod(i, a, n) for (i = (a); i > (n); --i) #define fodd(i, a, n) for (i = (a); i >= (n); --i) #define debug(x) cout << '>' << #x << ':' << x << endl; #define all(v) v.begin(), v.end() #define sz(x) ((int)(x).size()) #define endl " \n" #define newl cout<<"\n" #define MAXN 100005 #define MOD 1000000007LL #define EPS 1e-13 #define INFI 1000000000 // 10^9 #define INFLL 1000000000000000000ll //10^18 // ¯\_(ツ)_/¯ #define l long int #define d double #define ll long long int #define ull unsigned long long int #define ld long double #define vi vector<int> #define vll vector<long long> #define vvi vector<vector<int>> #define vvll vector<vll> //vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns, with value 500. #define mii map<int, int> #define mll map<long long, long long> #define pii pair<int, int> #define pll pair<long long, long long> #define fast_io() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); ll tc, n, m, k; // ll ans = 0, c = 0; // ll i, j; // ll a, b; // ll x, y; struct Point { int x, y; Point(int a, int b): x(a), y(b) {} }; // 0 for collinear // 1 for clockwise // -1 for anticlockwise int orientation(Point a, Point b, Point c) { int res = (b.y - a.y)*(c.x-b.x) - (b.x - a.x)*(c.y - b.y); if(res == 0) return 0; if(res > 0) return 1; if(res < 0) return -1; } void jarvis(vector<Point>& parr, vector<Point>& hull) { if(n < 3) return; // left most point int j = 0; rep(i, 1, sz(parr)) { if(parr[i].x < parr[j].x) j = i; } int curr = j, next; do { hull.pb(parr[curr]); // point 'next', such that all points 'x' is counterclockwise for (curr, x, next); next = (curr+1)%n; rep(i, 0, sz(parr)) { if(orientation(parr[curr], parr[i], parr[next]) == -1) next = i; } curr = next; } while(curr != j); } bool customcompare(Point& a, Point& b) { if(a.x == b.x) return a.y < b.y; return a.x < b.x; } int main() { fast_io(); #ifndef ONLINE_JUDGE freopen("../input.txt", "r", stdin); freopen("../output.txt", "w", stdout); #endif cin>>tc; while(tc--) { cin>>n; vector<Point> parr; map<pair<int, int>, bool> hm; rep(i, 0, n) { int u, v; cin>>u>>v; auto newpoint = Point(u, v); if(hm.find(mp(u, v)) == hm.end()) { parr.pb(newpoint); auto pr = mp(u, v); hm[pr] = true; } } vector<Point> hull; jarvis(parr, hull); if(sz(parr) < 3) { cout<<"-1"; } else { sort(all(hull), customcompare); rep(i, 0, sz(hull)) { cout<<hull[i].x<<" "<<hull[i].y; newl; if(i != sz(hull)-1) { cout<<", "; } } } newl; } return 0; }
#pragma once #include "ViewportCapturer.h" void UViewportCapturer::BeginDestroy() { Super::BeginDestroy(); ReleaseFrameGrabber(); } bool UViewportCapturer::ReleaseFrameGrabber() { if (FrameGrabber.IsValid()) { FrameGrabber->Shutdown(); FrameGrabber = nullptr; } return true; } bool UViewportCapturer::StartFrameGrab() { // (Inpired by RemoteHost plugin) #if WITH_EDITOR if (GIsEditor) { for (const FWorldContext& Context : GEngine->GetWorldContexts()) { if (Context.WorldType == EWorldType::PIE) { FSlatePlayInEditorInfo* SlatePlayInEditorSession = GEditor->SlatePlayInEditorMap.Find(Context.ContextHandle); if (SlatePlayInEditorSession) { if (SlatePlayInEditorSession->DestinationSlateViewport.IsValid()) { TSharedPtr<IAssetViewport> AssetViewport = SlatePlayInEditorSession->DestinationSlateViewport.Pin(); SceneViewport = AssetViewport->GetSharedActiveViewport(); } else if (SlatePlayInEditorSession->SlatePlayInEditorWindowViewport.IsValid()) { SceneViewport = SlatePlayInEditorSession->SlatePlayInEditorWindowViewport; } } } } } else #endif { UGameEngine* GameEngine = Cast<UGameEngine>(GEngine); SceneViewport = GameEngine->SceneViewport; } if (!SceneViewport.IsValid()) { return false; } // Capture Start ReleaseFrameGrabber(); FrameGrabber = MakeShared<FFrameGrabber>(SceneViewport.Pin().ToSharedRef(), SceneViewport.Pin()->GetSize()); FrameGrabber->StartCapturingFrames(); return true; } bool UViewportCapturer::CompressImage( const void* InUncompressedData, const int64 RawSize, const int32 InWidth, const int32 InHeight, TArray<uint8>& OutCompressedData, ERGBFormat ColFormat, EImageFormat ImgFormat) { OutCompressedData.Reset(); if (RawSize > 0) { IImageWrapperModule& ImgWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper")); TSharedPtr<IImageWrapper> ImageWrapper = ImgWrapperModule.CreateImageWrapper(ImgFormat); if (ImageWrapper.IsValid() && ImageWrapper->SetRaw(InUncompressedData, RawSize, InWidth, InHeight, ColFormat, 8)) { OutCompressedData = ImageWrapper->GetCompressed(); return true; } } return false; } bool UViewportCapturer::CompressImageScaled(const void* InUncompressedData, const int64 RawSize, const FIntPoint BufferSize, TArray<uint8>& OutCompressedData, ERGBFormat ColFormat, EImageFormat ImgFormat) { int32 Width = BufferSize.X; int32 Height = BufferSize.Y; return CompressImage(InUncompressedData, RawSize, Width, Height, OutCompressedData, ColFormat, ImgFormat); } bool UViewportCapturer::CompressImageGray(const TArray<FColor>& ColorData, const FIntPoint Size, TArray<uint8>& OutData) { TArray<uint8> Grayscale; int32 ImgWidth = Size.X; int32 ImgHeight = Size.Y; int32 Area = ImgWidth * ImgHeight; Grayscale.AddUninitialized(Area); for (int32 i = 0; i < Area; i++) { const FColor& Color = ColorData[i]; Grayscale[i] = (uint8)(Color.R * 0.299 + Color.G * 0.587 + Color.B * 0.114); } return CompressImageScaled(&Grayscale[0], Grayscale.Num(), Size, OutData, ERGBFormat::Gray, EImageFormat::PNG); } bool UViewportCapturer::CompressImageRGBA(const TArray<FColor>& InData, const FIntPoint BufferSize, TArray<uint8>& OutData) { return CompressImageScaled(InData.GetData(), InData.GetAllocatedSize(), BufferSize, OutData, ERGBFormat::BGRA, EImageFormat::PNG); } bool UViewportCapturer::TickGrab() { if (FrameGrabber.IsValid()) { FrameGrabber->CaptureThisFrame(FFramePayloadPtr()); TArray<FCapturedFrameData> Frames = FrameGrabber->GetCapturedFrames(); if (Frames.Num()) { const double ElapsedFrameTime = (FPlatformTime::Seconds() - PrevCaptureTime) * 1000; const int32 TargetFrameTime = 1000 / Properties.FrameRate; if (ElapsedFrameTime >= TargetFrameTime) { FCapturedFrameData& LastFrame = Frames.Last(); TArray<FColor> ColorData = MoveTemp(LastFrame.ColorBuffer); FIntPoint Size = LastFrame.BufferSize; // Run compression on another thread to prevent lag AsyncTask(ENamedThreads::AnyHiPriThreadHiPriTask, [this, Size, ColorData = MoveTemp(ColorData)]() mutable { TArray<uint8> CompressedColor; if (Properties.ColorFormatCompression == EColorFormat::GRAY) { if (CompressImageGray(ColorData, Size, CompressedColor)) { OnImageReady.Broadcast(CompressedColor); } } else if (Properties.ColorFormatCompression == EColorFormat::RGBA) { if (CompressImageRGBA(ColorData, Size, CompressedColor)) { OnImageReady.Broadcast(CompressedColor); } } }); PrevCaptureTime = FPlatformTime::Seconds(); } } } return true; }
/*#include<iostream> using namespace std; int main() { char input, alphabet=65; int i, j; cout << "enter the upper character" << endl; cin >> input; for (int i = 1; i <= (input-65 + 1); i++) { for (int j = 1;j <= i;j++) { cout << alphabet << " "; } alphabet++; cout << "\n"; } return 0; }*/ /*#include<conio.h> using namespace std; void main() { int i, j, n; cout << "Enter the value of n : "<< endl; cin >> n; cout << "The number triangle :" << endl; for (i = 1;i <= n;i++) { for (j = 1;j <= i;j++) { cout << j << " "; } cout << endl; } } */
#include "components/ai/aidsl.hpp" #include "components/position.hpp" #include "components/ai/pathai.hpp" namespace ai { struct DoAtAI : AIScript { private: enum class State { travel, activity }; public: DoAtAI(point p, AI::timer_t d, AI::timer_t w, std::string s) : state(State::travel), dest(p), duration(d), walkrate(w), desc(std::move(s)) {} virtual AI::timer_t start(AI* ai) override { return update(ai); } virtual void suspend(AI*) override { // Lose all progress towards the activity goal state = State::travel; } virtual AI::timer_t update(AI* ai) override { auto c = ai->parent; auto pos = c->assert_get<Position>(); if (pos->as_point().as_point() != dest) { state = State::travel; return ai->push_script(make_pathai(dest, walkrate)); } else { if (state == State::travel) { state = State::activity; return duration; } else if (state == State::activity) { return ai->pop_script(); } else { assert(false); return 0; } } } virtual const std::string& description() const override { return desc; } private: State state; point dest; timer_t duration; timer_t walkrate; std::string desc; }; AI::script_ptr make_do_at(point p, int duration, std::string description, int walkrate) { return make_shared<DoAtAI>(p, duration, walkrate, description); } }
//Libraries #include <stdio.h> #include <iostream> #include <unistd.h> // usleep #include <ucg.hpp> //Main function int main() { //Print logo print_uclogo(100000); //Wait some secs usleep(1000000); //Lauch rocket fly_rocket(300000); return 0; }
#ifndef MORSE_TRANSLATION_H #define MORSE_TRANSLATION_H #include <string> #include <cstdlib> #include <iostream> #include <vector> #include <queue> using namespace std; class MorseElement { public: char alpha; string code; char getAlpha() const {return alpha;}; string getCode() const {return code;}; // void setAlpha(char a) {alpha = a;}; // void setCode(int c) {code = c;}; friend ostream& operator<< (ostream& ostr, const MorseElement& rhs); }; class MorseTable { private: MorseElement table[37]; public: MorseTable(); string hashToMorse(char key); // char hashToAlpha(string msg); void printTable(); queue<string> stream(string msg); //char charCertify(char key); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) Opera Software ASA 2004 - 2011 * * Web server implementation -- overall server logic */ #include "core/pch.h" #ifdef WEBSERVER_SUPPORT #include "modules/webserver/src/webservercore/webserver_connection_listener.h" #include "modules/webserver/webserver-api.h" #include "modules/webserver/webserver_resources.h" #include "modules/doc/frm_doc.h" #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/prefs/prefsmanager/collections/pc_webserver.h" #include "modules/prefsfile/prefsfile.h" #include "modules/prefsfile/prefssection.h" #include "modules/util/opfile/opfolder.h" #include "modules/webserver/src/resources/webserver_file.h" #include "modules/webserver/src/resources/webserver_auth.h" #include "modules/ecmascript_utils/essched.h" #include "modules/stdlib/util/opdate.h" #include "modules/url/url_socket_wrapper.h" #include "modules/webserver/src/webservercore/webserver_private_global_data.h" #ifdef WEBSERVER_DIRECT_SOCKET_SUPPORT #include "modules/webserver/webserver_direct_socket.h" #endif #ifdef GADGET_SUPPORT #include "modules/xmlutils/xmlfragment.h" #include "modules/xmlutils/xmlnames.h" #endif #ifdef WEBSERVER_RENDEZVOUS_SUPPORT #include "modules/webserver/src/rendezvous/webserver_rendezvous.h" #endif WebServerConnectionListener::WebServerConnectionListener(UPNP_PARAM(UPnP *upnp)) : m_backlog(0) , m_rootSubServer(NULL) , m_uploadRate(0) , m_currentWindowSize(0) , m_bytesSentThisSample(0) , m_prevClockCheck(0) , m_nowThrottling(FALSE) , m_kBpsUp(0) , m_listening_socket_local(NULL) , m_listeningMode(WEBSERVER_LISTEN_LOCAL) , m_prefered_listening_port(0) , m_real_listening_port(0) , public_port(0) , m_hasPostedSetupListeningsocketMessage(FALSE) , m_webserverEventListener(NULL) #ifdef WEBSERVER_RENDEZVOUS_SUPPORT , m_listening_socket_rendezvous(NULL) #endif // WEBSERVER_RENDEZVOUS_SUPPORT #ifdef UPNP_SUPPORT , m_upnp_port_opener(NULL) , m_upnp(upnp) , m_opened_port(0) , m_opened_device(NULL) , m_port_checking_enabled(FALSE) #endif , upnp_advertised(FALSE) { #if defined(UPNP_SUPPORT) && defined(UPNP_SERVICE_DISCOVERY) ref_obj_lsn.EnableDelete(FALSE); advertisement_enabled=FALSE; #endif // defined(UPNP_SUPPORT) && defined(UPNP_SERVICE_DISCOVERY) } /* static */ OP_STATUS WebServerConnectionListener::Make(WebServerConnectionListener *&connection_listener, WebserverListeningMode listeningMode, WebServer *eventListener, #ifdef WEBSERVER_RENDEZVOUS_SUPPORT const char *shared_secret, #endif // WEBSERVER_RENDEZVOUS_SUPPORT unsigned int port, unsigned int backlog, int uploadRate UPNP_PARAM_COMMA(UPnP *upnp), const char *upnpDeviceType, const uni_char *upnpDeviceIcon, const uni_char *upnpPayload ) { OP_ASSERT(eventListener); connection_listener = NULL; WebServerConnectionListener *temp_connection_listener = OP_NEW(WebServerConnectionListener, (UPNP_PARAM(upnp))); if (temp_connection_listener == 0 ) { return OpStatus::ERR_NO_MEMORY; } RETURN_IF_ERROR(temp_connection_listener->m_upnpSearchType.Set(upnpDeviceType)); OpAutoPtr<WebServerConnectionListener> connection_listener_anchor(temp_connection_listener); #ifdef WEBSERVER_RENDEZVOUS_SUPPORT RETURN_IF_ERROR(temp_connection_listener->m_shared_secret.Set(shared_secret)); temp_connection_listener->m_shared_secret.Strip(); RETURN_IF_ERROR(g_main_message_handler->SetCallBack(temp_connection_listener, MSG_WEBSERVER_DELETE_RENDESVOUZ_CONNECTION, 0)); #endif temp_connection_listener->m_listeningMode = listeningMode; temp_connection_listener->m_webserverEventListener = eventListener; temp_connection_listener->m_real_listening_port = port; temp_connection_listener->m_prefered_listening_port = port; temp_connection_listener->m_backlog = backlog; temp_connection_listener->m_uploadRate = uploadRate; RETURN_IF_ERROR(g_main_message_handler->SetCallBack(temp_connection_listener, MSG_WEBSERVER_DELETE_CONNECTION, 0)); RETURN_IF_ERROR(g_main_message_handler->SetCallBack(temp_connection_listener, MSG_WEBSERVER_SET_UP_LISTENING_SOCKET, 0)); #ifdef NATIVE_ROOT_SERVICE_SUPPORT RETURN_IF_ERROR(temp_connection_listener->InstallNativeRootService(eventListener)); #endif //NATIVE_ROOT_SERVICE_SUPPORT RETURN_IF_LEAVE(g_pcwebserver->RegisterListenerL(temp_connection_listener)); g_main_message_handler->PostMessage(MSG_WEBSERVER_SET_UP_LISTENING_SOCKET, 0, 0); #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) // Initialize the device description RETURN_IF_ERROR(temp_connection_listener->temp_service.Construct()); RETURN_IF_ERROR(temp_connection_listener->UPnPServicesProvider::Construct()); RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(DEVICE_TYPE, upnpDeviceType ? upnpDeviceType : UPNP_DISCOVERY_OPERA_SEARCH_TYPE)); RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(MANUFACTURER, "Opera Software ASA")); RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(MANUFACTURER_URL, "http://www.opera.com/")); OpString str_temp; RETURN_IF_ERROR(str_temp.AppendFormat(UNI_L("Opera Unite Version %s"), VER_NUM_STR_UNI)); // In debug, also add the build number /*#if defined(_DEBUG) RETURN_IF_ERROR(str_temp.AppendFormat(UNI_L(" - build %s"), VER_BUILD_IDENTIFIER_UNI)); #endif*/ RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(MODEL_DESCRIPTION, str_temp.CStr())); RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(MODEL_NAME, "Opera Unite")); RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(MODEL_NUMBER, VER_NUM_STR_UNI)); if(upnpDeviceIcon) RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(DEVICE_ICON_RESOURCE, upnpDeviceIcon)); if(upnpPayload) RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(PAYLOAD, upnpPayload)); RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(MODEL_URL, "http://www.opera.com/")); //OpString uuid; OpString user; OpString dev; OpString proxy; OpString friendly; // Generate an unique UUID; to better support IP change and takeover, the Unique ID basically is the Unite address of the user, //int rnd=op_rand(); RETURN_IF_ERROR(user.Set(g_pcwebserver->GetStringPref(PrefsCollectionWebserver::WebserverUser))); RETURN_IF_ERROR(dev.Set(g_pcwebserver->GetStringPref(PrefsCollectionWebserver::WebserverDevice))); RETURN_IF_ERROR(proxy.Set(g_pcwebserver->GetStringPref(PrefsCollectionWebserver::WebserverProxyHost))); //RETURN_IF_ERROR(uuid.AppendFormat(UNI_L("uuid:opera-unite-1-%d-%s-%s"), rnd, user.CStr(), dev.CStr())); //RETURN_IF_ERROR(uuid.AppendFormat(UNI_L("uuid:opera-unite-1-%s-%s-%s"), dev.CStr(), user.CStr(), proxy.CStr())); RETURN_IF_ERROR(friendly.AppendFormat(UNI_L("Opera Unite - %s @ %s"), user.CStr(), dev.CStr())); RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(FRIENDLY_NAME, friendly.CStr())); OpString8 tmp_uuid; RETURN_IF_ERROR(tmp_uuid.AppendFormat("uuid:%s", (eventListener)?eventListener->GetUUID():NULL)); RETURN_IF_ERROR(temp_connection_listener->SetAttributeValue(UDN, tmp_uuid.CStr())); //RETURN_IF_ERROR(temp_connection_listener->upnp->AddServicesProvider(ptr)); #endif // defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) connection_listener = connection_listener_anchor.release(); return OpStatus::OK; } #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) OP_STATUS WebServerConnectionListener::RetrieveService(int index, UPnPService *&service) { WebSubServer *wss=m_webserverEventListener->GetSubServerAtIndex(index); if(!wss) return OpStatus::ERR_NO_SUCH_RESOURCE; temp_service.ResetAttributesValue(); const uni_char *virtual_path=wss->GetSubServerVirtualPath().CStr(); OpString8 temp_type; OpString8 temp_id; OpString path_url; OpString path_scpd; OpString8 service_name; if(!virtual_path || virtual_path[0]=='_' || !wss->IsVisibleUPNP()) temp_service.SetVisible(FALSE); else temp_service.SetVisible(TRUE); path_url.AppendFormat(UNI_L("/%s"), virtual_path); path_scpd.AppendFormat(UNI_L("/_upnp/scpd"), virtual_path); RETURN_IF_ERROR(service_name.Set(wss->GetSubServerName().CStr())); //RETURN_IF_ERROR(temp_type.AppendFormat("urn:opera-com:service:%s%d:1", "OperaUniteService", index+1)); RETURN_IF_ERROR(temp_type.AppendFormat("urn:opera-com:service:%s:1", service_name.CStr())); //RETURN_IF_ERROR(temp_id.AppendFormat("urn:opera-com:serviceId:OperaUniteService%d", index+1)); RETURN_IF_ERROR(temp_id.AppendFormat("urn:opera-com:serviceId:%s-%d", service_name.CStr(), index+1)); RETURN_IF_ERROR(temp_service.SetAttributeValue(UPnPService::SERVICE_TYPE, temp_type.CStr())); RETURN_IF_ERROR(temp_service.SetAttributeValue(UPnPService::SERVICE_ID, temp_id.CStr())); RETURN_IF_ERROR(temp_service.SetAttributeValue(UPnPService::SCPD_URL, path_scpd.CStr())); RETURN_IF_ERROR(temp_service.SetAttributeValue(UPnPService::CONTROL_URL, path_url.CStr())); RETURN_IF_ERROR(temp_service.SetAttributeValue(UPnPService::EVENT_URL, "/event")); RETURN_IF_ERROR(temp_service.SetAttributeValue(UPnPService::NAME, wss->GetSubServerName().CStr())); RETURN_IF_ERROR(temp_service.SetAttributeValue(UPnPService::DESCRIPTION, wss->GetSubServerDescription().CStr())); service=&temp_service; return OpStatus::OK; } UINT32 WebServerConnectionListener::GetNumberOfServices() { return m_webserverEventListener->GetSubServerCount(); } OP_STATUS WebServerConnectionListener::UpdateValues(OpString8 &challenge) { OpStringC user = g_pcwebserver->GetStringPref(PrefsCollectionWebserver::WebserverUser); OpStringC dev = g_pcwebserver->GetStringPref(PrefsCollectionWebserver::WebserverDevice); RETURN_IF_ERROR(SetAttributeValue(UNITE_USER, user.CStr())); RETURN_IF_ERROR(SetAttributeValue(UNITE_DEVICE, dev.CStr())); if(challenge.Length()>0) { OpString8 expected; OpString8 pk; // First authentication: "Opera" RETURN_IF_ERROR(pk.Set(UPNP_OPERA_PRIVATE_KEY)); RETURN_IF_ERROR(UPnP::Encrypt(challenge, pk, expected)); // MD5(PK+nonce1) RETURN_IF_ERROR(SetAttributeValue(CHALLENGE_RESPONSE, expected.CStr())); // Second authentication: shared secret OpString8 pk2; OpString8 nonce2; OpString8 expected2; RETURN_IF_ERROR(pk2.AppendFormat("%s%s", m_shared_secret.CStr(), challenge.CStr())); RETURN_IF_ERROR(nonce2.AppendFormat("%u", (UINT32)op_rand())); RETURN_IF_ERROR(UPnP::Encrypt(nonce2, pk2, expected2)); // MD5(SharedSecret+nonce1+nonce2) RETURN_IF_ERROR(SetAttributeValue(CHALLENGE_RESPONSE_AUTH, expected2.CStr())); RETURN_IF_ERROR(SetAttributeValue(NONCE_AUTH, nonce2.CStr())); } else RETURN_IF_ERROR(SetAttributeValue(CHALLENGE_RESPONSE, "")); return OpStatus::OK; } OP_STATUS WebServerConnectionListener::UpdateDescriptionURL(OpSocketAddress *addr) { // Updte the description URL OpString addr_str; OpString desc_url; OP_ASSERT(addr); if(addr) RETURN_IF_ERROR(addr->ToString(&addr_str)); RETURN_IF_ERROR(desc_url.AppendFormat(UNI_L("http://%s:%d"), addr_str.CStr(), m_real_listening_port)); RETURN_IF_ERROR(SetAttributeValue(PRESENTATION_URL, desc_url.CStr())); RETURN_IF_ERROR(desc_url.AppendFormat(UNI_L("/_upnp/desc"))); return SetDescriptionURL(desc_url); } #endif // defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) #ifdef WEBSERVER_RENDEZVOUS_SUPPORT OP_STATUS WebServerConnectionListener::ReconnectProxy(const char *shared_secret) { #ifdef WEBSERVER_RENDEZVOUS_SUPPORT RETURN_IF_ERROR(m_shared_secret.Set(shared_secret)); m_shared_secret.Strip(); #endif OP_DELETE(m_listening_socket_rendezvous); m_listening_socket_rendezvous = NULL; m_listeningMode |= WEBSERVER_LISTEN_PROXY; if (m_hasPostedSetupListeningsocketMessage == FALSE) { g_main_message_handler->PostDelayedMessage(MSG_WEBSERVER_SET_UP_LISTENING_SOCKET, 0, 0, 5000); m_hasPostedSetupListeningsocketMessage = TRUE; } return OpStatus::OK; } void WebServerConnectionListener::StopListeningProxy() { if (m_listening_socket_rendezvous && m_listening_socket_rendezvous->IsConnected()) m_webserverEventListener->OnProxyDisconnected(PROXY_CONNECTION_LOGGED_OUT_BY_CALLER, FALSE); OP_DELETE(m_listening_socket_rendezvous); m_listening_socket_rendezvous = NULL; m_listeningMode &= ~((unsigned int)WEBSERVER_LISTEN_PROXY); } #endif //WEBSERVER_RENDEZVOUS_SUPPORT OP_STATUS WebServerConnectionListener::ReconnectLocalImmediately() { OP_STATUS status; m_hasPostedSetupListeningsocketMessage = FALSE; if (OpStatus::IsError(status = SetUpListenerSocket())) { if (OpStatus::IsMemoryError(status)) { g_webserverPrivateGlobalData->SignalOOM(); } } return status; } OP_STATUS WebServerConnectionListener::ReconnectLocal(unsigned int port, BOOL reconnect_immediately) { OP_DELETE(m_listening_socket_local); m_listening_socket_local = NULL; if (port != 0) { m_real_listening_port = port; m_prefered_listening_port = port; } m_listeningMode |= WEBSERVER_LISTEN_LOCAL; if(reconnect_immediately) return ReconnectLocalImmediately(); else { if (m_hasPostedSetupListeningsocketMessage == FALSE) { g_main_message_handler->PostDelayedMessage(MSG_WEBSERVER_SET_UP_LISTENING_SOCKET, 0, 0, 5000); m_hasPostedSetupListeningsocketMessage = TRUE; } } return OpStatus::OK; } void WebServerConnectionListener::StopListeningLocal() { BOOL was_listening = m_listening_socket_local ? TRUE : FALSE; OP_DELETE(m_listening_socket_local); m_listening_socket_local = NULL; m_listeningMode &= ~((unsigned int)WEBSERVER_LISTEN_LOCAL); m_listeningMode &= ~((unsigned int)WEBSERVER_LISTEN_OPEN_PORT); if (was_listening) m_webserverEventListener->OnWebserverListenLocalStopped(); /*FIXME: Must close port here */ } void WebServerConnectionListener::StartListeningDirectMemorySocket() { m_listeningMode |= WEBSERVER_LISTEN_DIRECT; } void WebServerConnectionListener::StopListeningDirectMemorySocket() { m_listeningMode &= ~((unsigned int)WEBSERVER_LISTEN_DIRECT); } WebserverListeningMode WebServerConnectionListener::GetCurrentMode() { WebserverListeningMode mode = WEBSERVER_LISTEN_NONE; #ifdef WEBSERVER_RENDEZVOUS_SUPPORT if (m_listening_socket_rendezvous && m_listening_socket_rendezvous->IsConnected()) { mode |= WEBSERVER_LISTEN_PROXY; } #endif // WEBSERVER_RENDEZVOUS_SUPPORT if (m_listening_socket_local) { mode |= WEBSERVER_LISTEN_LOCAL; } if (m_listeningMode & WEBSERVER_LISTEN_DIRECT) { mode |= WEBSERVER_LISTEN_DIRECT; } return mode; } #if defined(WEBSERVER_DIRECT_SOCKET_SUPPORT) void WebServerConnectionListener::OnSocketDirectConnectionRequest(WebserverDirectClientSocket* listening_socket, BOOL is_owner) { if (!(m_listeningMode & WEBSERVER_LISTEN_DIRECT)) { listening_socket->OnSocketConnectError(OpSocket::CONNECTION_FAILED); return; } WebserverDirectServerSocket *server_socket = NULL; WebServerConnection *http_connection = OP_NEW(WebServerConnection, ()); OP_STATUS status = OpStatus::ERR_NO_MEMORY; if ( http_connection == NULL || OpStatus::IsError(status = WebserverDirectServerSocket::CreateDirectServerSocket(&server_socket)) || OpStatus::IsError(status = listening_socket->Accept(server_socket)) || OpStatus::IsError(status = http_connection->Construct(server_socket, this, is_owner, TRUE #ifdef WEBSERVER_RENDEZVOUS_SUPPORT , FALSE, "127.0.0.1")) /* Takes over server_socket */ #endif ) { OP_DELETE(http_connection); OP_DELETE(server_socket); if (OpStatus::IsMemoryError(status)) g_webserverPrivateGlobalData->SignalOOM(); return; } /*We must put the new WebServerConnection into a list*/ http_connection->Into(&m_connectionList); server_socket->SetListener(http_connection); return; } #endif void WebServerConnectionListener::PrefChanged(enum OpPrefsCollection::Collections id, int pref, int newvalue) { if (OpPrefsCollection::Webserver == id && PrefsCollectionWebserver::WebserverUploadRate == pref) { m_uploadRate = newvalue; } } #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) OP_STATUS WebServerConnectionListener::EnableUPnPServicesDiscovery() { OP_ASSERT(m_upnp); RETURN_IF_ERROR(UPnP::CreateUniteDiscoveryObject(m_upnp, this)); //UPnP::SetDOMUPnpObject(m_upnp); return OpStatus::OK; } #endif // defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) OP_STATUS WebServerConnectionListener::SetUpListenerSocket() { OP_STATUS status = OpStatus::OK; #ifdef UPNP_SUPPORT if (m_listeningMode & WEBSERVER_LISTEN_OPEN_PORT && m_listeningMode & WEBSERVER_LISTEN_LOCAL ) { OP_ASSERT(m_upnp); if (!m_upnp_port_opener) { if (OpStatus::IsError(status = UPnP::CreatePortOpeningObject(m_upnp, m_upnp_port_opener, m_prefered_listening_port, m_prefered_listening_port + 40))) { //OP_DELETE(m_upnp); //m_upnp = NULL; m_upnp_port_opener = NULL; //Owned and deleted by m_upnp; return status; } m_upnp_port_opener->SetPolicy(UPnPPortOpening::UPNP_CARDS_OPEN_FIRST); if (OpStatus::IsSuccess(m_upnp_port_opener->StartPortOpening())) { OpStatus::Ignore(m_upnp_port_opener->AddListener(this)); } } } else { DisableUPnPPortForwarding(); } #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) if(m_listeningMode & WEBSERVER_LISTEN_UPNP_DISCOVERY) EnableUPnPServicesDiscovery(); #endif // defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) #endif // UPNP_SUPPORT //if (!(m_listeningMode & WEBSERVER_LISTEN_OPEN_PORT)) { OP_STATUS local_socket_status = OpStatus::OK; OP_STATUS rendezvous_status = OpStatus::OK; if (m_listeningMode & WEBSERVER_LISTEN_LOCAL) // Needs to wait with local listening until port opening is done. { if (m_listening_socket_local == NULL && !(m_listeningMode & WEBSERVER_LISTEN_OPEN_PORT)) local_socket_status = StartListening(); } else { OP_DELETE(m_listening_socket_local); m_listening_socket_local = NULL; } if (m_listeningMode & WEBSERVER_LISTEN_PROXY) rendezvous_status = StartListeningRendezvous(); if ( OpStatus::IsError(status = local_socket_status) #ifdef WEBSERVER_RENDEZVOUS_SUPPORT || OpStatus::IsError(status = rendezvous_status) #endif ) { if (m_hasPostedSetupListeningsocketMessage == FALSE) { g_main_message_handler->PostDelayedMessage(MSG_WEBSERVER_SET_UP_LISTENING_SOCKET, 0, 0, 4000); m_hasPostedSetupListeningsocketMessage = TRUE; } } } return status; } OP_STATUS WebServerConnectionListener::StartListening() { // Advertising here is a mistake. We need to wait the end of the UPnP process // The first time, advertise UPnP /*if(!upnp_advertised) { upnp_advertised=TRUE; #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) advertisement_enabled=TRUE; #endif AdvertiseUPnP(TRUE); }*/ OP_STATUS local_socket_status = OpStatus::OK; OpSocketAddress *socket_address = NULL; if ( m_listening_socket_local == NULL && OpStatus::IsError(local_socket_status = OpSocketAddress::Create(&socket_address)) || ( !socket_address || // shut up Coverity ((GetWebServer()->GetAlwaysListenToAllNetworks() || g_pcwebserver->GetIntegerPref(PrefsCollectionWebserver::WebserverListenToAllNetworks) || OpStatus::IsSuccess(socket_address->FromString(UNI_L("127.0.0.1"))), FALSE) || (socket_address->SetPort(m_real_listening_port), FALSE)) ) || OpStatus::IsError(local_socket_status = SocketWrapper::CreateTCPSocket(&(m_listening_socket_local), this, SocketWrapper::NO_WRAPPERS)) || ( !m_listening_socket_local || // shut up Coverity OpStatus::IsError(local_socket_status = m_listening_socket_local->Listen(socket_address, m_backlog)) ) ) { if (!OpStatus::IsMemoryError(local_socket_status)) { m_webserverEventListener->OnWebserverListenLocalFailed(WEBSERVER_ERROR_LISTENING_SOCKET_TAKEN); m_real_listening_port++; } else if(OpStatus::IsSuccess(local_socket_status)) local_socket_status = OpStatus::ERR; OP_DELETE(m_listening_socket_local); m_listening_socket_local = NULL; } else if (m_listening_socket_local) { #ifdef UPNP_SUPPORT if (m_listening_socket_rendezvous && m_port_checking_enabled) m_listening_socket_rendezvous->CheckPort(m_real_listening_port); #endif m_webserverEventListener->OnWebserverListenLocalStarted(m_real_listening_port); } OP_DELETE(socket_address); OP_ASSERT((m_listening_socket_local && OpStatus::IsSuccess(local_socket_status)) || (!m_listening_socket_local && OpStatus::IsError(local_socket_status))); RETURN_IF_ERROR(StartListeningRendezvous()); return local_socket_status; } #ifdef WEBSERVER_RENDEZVOUS_SUPPORT OP_STATUS WebServerConnectionListener::StartListeningRendezvous() { // Advertising when the connection with the proxy is available, is a mistake // We really need a local listener or it will not work, above all if we advertise a transtional port // The first time, advertise UPnP /*if(!upnp_advertised) { upnp_advertised=TRUE; #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) advertisement_enabled=TRUE; #endif AdvertiseUPnP(TRUE); }*/ OP_STATUS rendezvous_status = OpStatus::OK; if (m_listeningMode & WEBSERVER_LISTEN_PROXY) { if (m_listening_socket_rendezvous == NULL) { if (WebserverRendezvous::IsConfigured() == FALSE) { m_webserverEventListener->OnProxyConnectionFailed(PROXY_CONNECTION_DEVICE_NOT_CONFIGURED, FALSE); } else if ( OpStatus::IsError(rendezvous_status = WebserverRendezvous::Create(&m_listening_socket_rendezvous, this, m_shared_secret.Strip().CStr(), m_real_listening_port)) || OpStatus::IsError(rendezvous_status = m_listening_socket_rendezvous->Listen(NULL, m_backlog)) ) { OP_DELETE(m_listening_socket_rendezvous); m_listening_socket_rendezvous = NULL; } } } else { OP_DELETE(m_listening_socket_rendezvous); m_listening_socket_rendezvous = NULL; } return rendezvous_status; } #endif // WEBSERVER_RENDEZVOUS_SUPPORT WebServerConnectionListener::~WebServerConnectionListener() { #if defined(UPNP_SUPPORT) && defined(UPNP_SERVICE_DISCOVERY) if(m_upnp && (m_listeningMode & WEBSERVER_LISTEN_UPNP_DISCOVERY)) m_upnp->SendByeBye(this); #endif // defined(UPNP_SUPPORT) && defined(UPNP_SERVICE_DISCOVERY) g_main_message_handler->RemoveCallBacks(this, 0); g_pcwebserver->UnregisterListener(this); OP_DELETE(m_listening_socket_local); #ifdef WEBSERVER_RENDEZVOUS_SUPPORT OP_DELETE(m_listening_socket_rendezvous); #endif #ifdef UPNP_SUPPORT if (m_upnp_port_opener) { OpStatus::Ignore(m_upnp_port_opener->RemoveListener(this)); OP_DELETE(m_upnp_port_opener); m_upnp_port_opener=NULL; } //OP_DELETE(m_upnp); // m_upnp in NOT owned by the Connection Listener #endif // UPNP_SUPPORT OP_DELETE(m_rootSubServer); // Can't rely on auto-delete of m_subServers, because it does not remove // entries while deleting, and when deleting the second, we may access the // first (deleted) WebSubServer through a long chain of calls starting from // g_webserver->CloseAllConnectionsToSubServer(...) while (m_subServers.GetCount() != 0) { WebSubServer *wss=m_subServers.Remove(0); OP_DELETE(wss); } } OpAutoVector<WebSubServer> *WebServerConnectionListener::GetWebSubServers() { return &m_subServers; } void WebServerConnectionListener::CloseAllConnectionsToSubServer(WebSubServer *subserver) { if (subserver == NULL) return; if (m_connectionList.Cardinal()>0) { for (WebServerConnection * connection = (WebServerConnection *) m_connectionList.First(); connection; connection = (WebServerConnection *) connection->Suc()) { if (subserver == connection->GetCurrentSubServer()) { connection->KillService(); /*This will post a message back to this class to clean up meassages and kill the connection*/ } } } } void WebServerConnectionListener::CloseAllConnections() { for (WebServerConnection * connection = (WebServerConnection *) m_connectionList.First(); connection; connection = (WebServerConnection *) connection->Suc()) { connection->KillService(); /*This will post a message back to this class to clean up meassages and kill the connection*/ } } void WebServerConnectionListener::CloseAllConnectionsToWindow(unsigned int windowId) { if (m_connectionList.Cardinal()>0) { for (WebServerConnection * connection = (WebServerConnection *) m_connectionList.First(); connection; connection = (WebServerConnection *) connection->Suc()) { WebSubServer *subserver = connection->GetCurrentSubServer(); if (subserver && subserver->GetWindowId() == windowId) { connection->KillService(); /*This will post a message back to this class to clean up meassages and kill the connection*/ } } } } int WebServerConnectionListener::NumberOfConnectionsToSubServer(WebSubServer *subserver) { if (subserver == NULL) return 0; int numberOfConnections = 0; if (m_connectionList.Cardinal() > 0) { for (WebServerConnection * connection = (WebServerConnection *) m_connectionList.First(); connection; connection = (WebServerConnection *) connection->Suc()) { if (subserver == connection->GetCurrentSubServer()) { numberOfConnections++; } } } return numberOfConnections; } int WebServerConnectionListener::NumberOfConnectionsInWindow(unsigned int windowId) { int numberOfConnections = 0; if (m_connectionList.Cardinal() > 0) { for (WebServerConnection * connection = (WebServerConnection *) m_connectionList.First(); connection; connection = (WebServerConnection *) connection->Suc()) { WebSubServer *subserver = connection->GetCurrentSubServer(); if (subserver && subserver->GetWindowId() == windowId) { numberOfConnections++; } } } return numberOfConnections; } int WebServerConnectionListener::NumberOfConnectionsWithRequests() { int numberOfConnections = 0; if (m_connectionList.Cardinal() > 0) { for (WebServerConnection * connection = (WebServerConnection *) m_connectionList.First(); connection; connection = (WebServerConnection *) connection->Suc()) { if (connection->GetCurrentRequest() && !connection->ClientIsOwner()) { numberOfConnections++; } } } return numberOfConnections; } void WebServerConnectionListener::windowClosed(unsigned long windowId) { CloseAllConnectionsToWindow(windowId); #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) BOOL b=advertisement_enabled; advertisement_enabled=FALSE; #endif if (OpStatus::IsMemoryError(RemoveSubServers(windowId))) { g_webserverPrivateGlobalData->SignalOOM(); } #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) advertisement_enabled=b; #endif } WebSubServer *WebServerConnectionListener::WindowHasWebserverAssociation(unsigned long windowId) { if (windowId != NO_WINDOW_ID) { if (m_rootSubServer && windowId == m_rootSubServer->GetWindowId() && m_rootSubServer->AllowEcmaScriptSupport() == TRUE) { return m_rootSubServer; } int n = m_subServers.GetCount(); for (int i =0; i < n; i++) { WebSubServer *subServer = m_subServers.Get(i); if (subServer && windowId == subServer->GetWindowId() && subServer->AllowEcmaScriptSupport() == TRUE ) { return subServer; } } } return NULL; } #if defined UPNP_SUPPORT && defined UPNP_SERVICE_DISCOVERY void WebServerConnectionListener::AdvertiseUPnP(BOOL delay) { if(m_upnp && (m_listeningMode & WEBSERVER_LISTEN_UPNP_DISCOVERY) && advertisement_enabled) { OpStatus::Ignore(m_upnp->AdvertiseServicesProvider(this, TRUE, delay)); // Updates are now disabled. When a control point will request a description (WebResource_UPnP_Service_Discovery::Make()), then they // will be actuvated again; this should reduce the number of messages generated advertisement_enabled=FALSE; } upnp_advertised = TRUE; } #endif OP_STATUS WebServerConnectionListener::AddSubServer(WebSubServer *subServer, BOOL notify_upnp) { /* FixMe : here we should check if a subserver with the same name (and window Id?) already exists */ if (subServer == NULL) return OpStatus::ERR; if (subServer->GetSubServerVirtualPath().Compare("_", 1) == 0 && subServer->GetSubServerVirtualPath().Compare("_upnp") != 0 && subServer->GetSubServerVirtualPath().Compare("_asd") != 0) return OpStatus::ERR; RETURN_IF_ERROR(m_subServers.Add(subServer)); m_webserverEventListener->last_service_change=WebLogAccess::GetSystemTime(); m_webserverEventListener->OnWebserverServiceStarted(subServer->GetSubServerName().CStr(), subServer->GetSubServerVirtualPath().CStr()); if(notify_upnp && upnp_advertised) // The first notify is very critical, so we need to wait for it to be sent AdvertiseUPnP(TRUE); return OpStatus::OK; } #ifdef NATIVE_ROOT_SERVICE_SUPPORT OP_STATUS WebServerConnectionListener::InstallNativeRootService(WebServer *server) { if (m_rootSubServer != NULL) { RETURN_IF_ERROR(RemoveSubServer(m_rootSubServer)); } OpString webserver_private; RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_WEBSERVER_FOLDER, webserver_private)); RETURN_IF_ERROR(webserver_private.Append("/resources/_root/")); WebSubServer *subserver = NULL; OP_STATUS status; if (OpStatus::IsError(status = WebSubServer::Make(subserver, server, NO_WINDOW_ID, webserver_private, UNI_L("/"), UNI_L("Native Root Service"), UNI_L(""), UNI_L("My Server"), UNI_L(""), FALSE, FALSE))) { OP_DELETE(subserver); return status; } subserver->m_serviceType = WebSubServer::SERVICE_TYPE_BUILT_IN_ROOT_SERVICE; if (OpStatus::IsError(status = SetRootSubServer(subserver))) { OP_DELETE(subserver); return status; } return OpStatus::OK; } #endif //NATIVE_ROOT_SERVICE_SUPPORT OP_STATUS WebServerConnectionListener::SetRootSubServer(WebSubServer *root_service) { if (m_rootSubServer) { m_webserverEventListener->OnWebserverServiceStopped(m_rootSubServer->GetSubServerName().CStr(), m_rootSubServer->GetSubServerVirtualPath().CStr(), TRUE); OP_DELETE(m_rootSubServer); m_rootSubServer = NULL; } RETURN_IF_ERROR(root_service->m_subServerVirtualPath.Set("_root")); /* we force the root service to have _root as uri-path (virtual path) */ m_rootSubServer = root_service; if (root_service->m_serviceType == WebSubServer::SERVICE_TYPE_SERVICE) { root_service->m_serviceType = WebSubServer::SERVICE_TYPE_CUSTOM_ROOT_SERVICE; } WebserverResourceDescriptor_AccessControl *authElement; RETURN_IF_ERROR(WebserverResourceDescriptor_AccessControl::Make(authElement, UNI_L("authresource"), UNI_L("Authentication needed"), FALSE)); if (authElement == NULL || root_service->AddSubServerAccessControlResource(authElement) != OpBoolean::IS_FALSE) { OP_DELETE(authElement); return OpStatus::ERR; } m_webserverEventListener->OnWebserverServiceStarted(root_service->GetSubServerName().CStr(), root_service->GetSubServerVirtualPath().CStr(), TRUE); return OpStatus::OK; } OP_STATUS WebServerConnectionListener::RemoveSubServer(WebSubServer *subServer, BOOL notify_upnp) { if (subServer == NULL) { return OpStatus::ERR; } else if (subServer == m_rootSubServer) { #ifdef NATIVE_ROOT_SERVICE_SUPPORT if (m_rootSubServer->GetServiceType() == WebSubServer::SERVICE_TYPE_BUILT_IN_ROOT_SERVICE) /* Don't remove the default native */ { return OpStatus::OK; } #endif //NATIVE_ROOT_SERVICE_SUPPORT m_webserverEventListener->last_service_change=WebLogAccess::GetSystemTime(); m_webserverEventListener->OnWebserverServiceStopped(m_rootSubServer->GetSubServerName().CStr(), m_rootSubServer->GetSubServerVirtualPath().CStr(), TRUE); OP_DELETE(m_rootSubServer); m_rootSubServer = NULL; #ifdef NATIVE_ROOT_SERVICE_SUPPORT return InstallNativeRootService(subServer->m_webserver); #else return OpStatus::OK; #endif //NATIVE_ROOT_SERVICE_SUPPORT } else { OpString subserver_name; OpString subserver_virtual_path; RETURN_IF_ERROR(subserver_name.Set(subServer->GetSubServerName())); RETURN_IF_ERROR(subserver_virtual_path.Set(subServer->GetSubServerVirtualPath())); RETURN_IF_ERROR(m_subServers.Delete(subServer)); m_webserverEventListener->last_service_change=WebLogAccess::GetSystemTime(); m_webserverEventListener->OnWebserverServiceStopped(subserver_name.CStr(), subserver_virtual_path.CStr()); if(notify_upnp && upnp_advertised) // Wait the first notification, to avoid triggering the anti-flood protection AdvertiseUPnP(TRUE); return OpStatus::OK; } } OP_STATUS WebServerConnectionListener::RemoveSubServers(unsigned long windowId) { #ifdef NATIVE_ROOT_SERVICE_SUPPORT if (m_rootSubServer && m_rootSubServer->GetServiceType() != WebSubServer::SERVICE_TYPE_BUILT_IN_ROOT_SERVICE) /* Don't remove the default native */ #endif //NATIVE_ROOT_SERVICE_SUPPORT { if (m_rootSubServer && windowId == m_rootSubServer->GetWindowId()) { m_webserverEventListener->last_service_change=WebLogAccess::GetSystemTime(); m_webserverEventListener->OnWebserverServiceStopped(m_rootSubServer->GetSubServerName().CStr(), m_rootSubServer->GetSubServerVirtualPath().CStr(), TRUE); OP_DELETE(m_rootSubServer); m_rootSubServer = NULL; } } int i = 0; WebSubServer *subServer = m_subServers.Get(0); WebSubServer *nextSubServer; while (subServer) { nextSubServer = m_subServers.Get(i+1); if (windowId == subServer->GetWindowId()) { OpStatus::Ignore(RemoveSubServer(subServer, FALSE)); // Only one UPnP notification } else { i++; } subServer = nextSubServer; } if(upnp_advertised) AdvertiseUPnP(TRUE); #ifdef NATIVE_ROOT_SERVICE_SUPPORT /*if (m_rootSubServer == NULL) { return InstallNativeRootService(); }*/ #endif //NATIVE_ROOT_SERVICE_SUPPORT return OpStatus::OK; } void WebServerConnectionListener::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { WebServerConnection *connection; switch (msg) { case MSG_WEBSERVER_DELETE_CONNECTION: { /*We find and delete the connection given by par2*/ OP_ASSERT( par1 == (INTPTR)this); connection = FindConnectionById(par2); if (connection) { connection->Out(); OP_DELETE(connection); } break; } #ifdef WEBSERVER_RENDEZVOUS_SUPPORT case MSG_WEBSERVER_DELETE_RENDESVOUZ_CONNECTION: { StopListeningProxy(); break; } #endif //WEBSERVER_RENDEZVOUS_SUPPORT case MSG_WEBSERVER_SET_UP_LISTENING_SOCKET: { OpStatus::Ignore(ReconnectLocalImmediately()); break; } default: OP_ASSERT(!"We do not listen to this"); break; } } WebServerConnection *WebServerConnectionListener::FindConnectionById(INTPTR connectionId) { for (WebServerConnection * connection = (WebServerConnection *) m_connectionList.First(); connection; connection= (WebServerConnection *) connection->Suc()) { if(connection->Id() == connectionId) return connection; } return 0; } OP_STATUS WebServerConnectionListener::CreateNewService(OpSocket *listening_socket) { OP_STATUS status; WebServerConnection *http_connection = OP_NEW(WebServerConnection, ()); if (http_connection == NULL) { return OpStatus::ERR_NO_MEMORY; } OpSocket *socket = NULL; if (listening_socket == m_listening_socket_local) { RETURN_IF_ERROR(SocketWrapper::CreateTCPSocket(&(socket), http_connection, SocketWrapper::NO_WRAPPERS)); if (OpStatus::IsError(status = m_listening_socket_local->Accept(socket))) { OP_DELETE(http_connection); OP_DELETE(socket); return status; } } if (OpStatus::IsError(status = http_connection->Construct(socket, this))) { OP_DELETE(http_connection); OP_DELETE(socket); return status; } /*We must put the new WebServerConnection into a list*/ http_connection->Into(&m_connectionList); return status; } #ifdef WEBSERVER_RENDEZVOUS_SUPPORT /*virtual*/ void WebServerConnectionListener::OnRendezvousConnected(WebserverRendezvous *socket) { m_webserverEventListener->OnProxyConnected(); } /*virtual*/ void WebServerConnectionListener::OnRendezvousConnectError(WebserverRendezvous *socket, RendezvousStatus status, BOOL retry) { WebserverStatus webserverStatus; switch (status) { case RENDEZVOUS_PROXY_CONNECTION_ERROR_DEVICE_ALREADY_REGISTERED: webserverStatus = PROXY_CONNECTION_ERROR_DEVICE_ALREADY_REGISTERED; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_AUTH_FAILURE: webserverStatus = PROXY_CONNECTION_ERROR_AUTH_FAILURE; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_MEMORY: webserverStatus = WEBSERVER_ERROR_MEMORY; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_PROXY_NOT_REACHABLE: webserverStatus = PROXY_CONNECTION_ERROR_PROXY_NOT_REACHABLE; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_NETWORK: webserverStatus = PROXY_CONNECTION_ERROR_NETWORK; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_PROXY_DOWN: webserverStatus = PROXY_CONNECTION_ERROR_PROXY_DOWN; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_PROXY_ADDRESS_UNKOWN: webserverStatus = PROXY_CONNECTION_ERROR_PROXY_ADDRESS_UNKOWN; break; default: webserverStatus = PROXY_CONNECTION_ERROR_NETWORK; } if (retry == FALSE) /* Rendezvous will try again */ { g_main_message_handler->PostMessage(MSG_WEBSERVER_DELETE_RENDESVOUZ_CONNECTION, 0, 0); } m_webserverEventListener->OnProxyConnectionFailed(webserverStatus, retry); } /* virtual */ void WebServerConnectionListener::OnRendezvousConnectionProblem(WebserverRendezvous *socket, RendezvousStatus status, BOOL retry) { WebserverStatus webserverStatus; switch (status) { case RENDEZVOUS_PROXY_CONNECTION_ERROR_NETWORK: webserverStatus = PROXY_CONNECTION_ERROR_NETWORK; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_MEMORY: webserverStatus = WEBSERVER_ERROR_MEMORY; break; default: webserverStatus = PROXY_CONNECTION_ERROR_NETWORK; } m_webserverEventListener->OnProxyConnectionProblem(webserverStatus, retry); } /*virtual*/ void WebServerConnectionListener::OnRendezvousConnectionRequest(WebserverRendezvous *listening_socket) { OP_ASSERT(listening_socket == m_listening_socket_rendezvous); OpSocket *socket = NULL; WebServerConnection *http_connection = OP_NEW(WebServerConnection, ()); if (http_connection == NULL) { g_webserverPrivateGlobalData->SignalOOM(); return; } OP_STATUS status; OpString8 socket_ip; if (OpStatus::IsError(status = m_listening_socket_rendezvous->Accept(&socket, http_connection, socket_ip))) { OP_DELETE(http_connection); OP_DELETE(socket); socket = NULL; g_webserverPrivateGlobalData->SignalOOM(); return; } if (OpStatus::IsError(status = http_connection->Construct(socket, this #ifdef WEBSERVER_DIRECT_SOCKET_SUPPORT , FALSE , FALSE #endif , TRUE, socket_ip) ) ) { OP_DELETE(http_connection); OP_DELETE(socket); g_webserverPrivateGlobalData->SignalOOM(); return; } /*We must put the new WebServerConnection into a list*/ http_connection->Into(&m_connectionList); } /*virtual*/ void WebServerConnectionListener::OnRendezvousClosed(WebserverRendezvous *socket, RendezvousStatus status, BOOL retry, int code) { OP_ASSERT(socket == m_listening_socket_rendezvous); if (socket == m_listening_socket_rendezvous) { WebserverStatus webserverStatus; switch (status) { case RENDEZVOUS_PROXY_CONNECTION_LOGGED_OUT: webserverStatus = PROXY_CONNECTION_LOGGED_OUT; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_PROTOCOL_WRONG_VERSION: webserverStatus = PROXY_CONNECTION_ERROR_PROTOCOL_WRONG_VERSION; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_UNSECURE_SERVER_VERSION: webserverStatus = PROXY_CONNECTION_ERROR_UNSECURE_SERVER_VERSION; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_NETWORK: webserverStatus = PROXY_CONNECTION_ERROR_NETWORK; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_MEMORY: webserverStatus = WEBSERVER_ERROR_MEMORY; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_DENIED: webserverStatus = PROXY_CONNECTION_ERROR_DENIED; break; case RENDEZVOUS_PROXY_CONNECTION_ERROR_PROTOCOL: webserverStatus = PROXY_CONNECTION_ERROR_PROTOCOL; break; default: OP_ASSERT(!"UKNOWN ERROR CODE"); webserverStatus = WEBSERVER_ERROR; break; } if (retry == FALSE) /* Rendezvous will not try again */ { g_main_message_handler->PostMessage(MSG_WEBSERVER_DELETE_RENDESVOUZ_CONNECTION, 0, 0); } m_webserverEventListener->OnProxyDisconnected(webserverStatus, retry); } }; /* virtual */ void WebServerConnectionListener::OnDirectAccessStateChanged(BOOL direct_access, const char* direct_access_address) { const char *separator=NULL; // direct_access_address is in the format address:port. We look for the last ':' to support also IPv6 addresses if(direct_access && (separator=op_strrchr(direct_access_address, ':'))!=NULL) { public_ip.Set(direct_access_address, separator-direct_access_address); public_port=op_atoi(separator+1); } else { public_ip.Empty(); public_port=0; } m_webserverEventListener->OnDirectAccessStateChanged(direct_access, direct_access_address); } #endif // WEBSERVER_RENDEZVOUS_SUPPORT void WebServerConnectionListener::OnSocketConnectionRequest(OpSocket* socket) { if (OpStatus::IsMemoryError(CreateNewService(socket))) { g_webserverPrivateGlobalData->SignalOOM(); } } void WebServerConnectionListener::OnSocketDataReady(OpSocket* socket) { OP_ASSERT(!"This is the connection listener. The listener should not receive this method"); } void WebServerConnectionListener::OnSocketDataSent(OpSocket* socket, UINT32 bytesSent) { OP_ASSERT(!"This is the connection listener. The listener should not receive this method"); } void WebServerConnectionListener::OnSocketClosed(OpSocket* socket) { OP_DELETE(m_listening_socket_local); m_listening_socket_local = NULL; if (m_connectionList.Cardinal()>0) { for (WebServerConnection * connection = (WebServerConnection *) m_connectionList.First(); connection; connection= (WebServerConnection *) connection->Suc()) { connection->KillService(); /*This will post a message back to this class to clean up meassages and kill the connection*/ } } if (m_hasPostedSetupListeningsocketMessage == FALSE) { g_main_message_handler->PostDelayedMessage(MSG_WEBSERVER_SET_UP_LISTENING_SOCKET, 0, 0, 4000); m_hasPostedSetupListeningsocketMessage = TRUE; } } void WebServerConnectionListener::OnSocketReceiveError(OpSocket* socket, OpSocket::Error socketErr) { OP_ASSERT(!"This is the connection listener. The listener should not receive this method"); } void WebServerConnectionListener::OnSocketSendError(OpSocket* socket, OpSocket::Error socketErr) { OP_ASSERT(!"This is the connection listener. The listener should not receive this method"); } void WebServerConnectionListener::OnSocketCloseError(OpSocket* socket, OpSocket::Error socketErr) { OP_ASSERT(!"should not have been here"); } void WebServerConnectionListener::OnSocketDataSendProgressUpdate(OpSocket* socket, UINT32 bytesSent) { OP_ASSERT(!"should not have been here"); } void WebServerConnectionListener::OnSocketConnected(OpSocket* socket) { OP_ASSERT(!"should not have been here"); } void WebServerConnectionListener::OnSocketListenError(OpSocket* socket, OpSocket::Error error) { OP_ASSERT(m_listening_socket_local == socket); if (m_listening_socket_local == socket) { g_webserver->OnWebserverListenLocalFailed(WEBSERVER_ERROR_LISTENING_SOCKET_TAKEN); } } void WebServerConnectionListener::OnSocketConnectError(OpSocket* socket, OpSocket::Error socketErr) { OP_ASSERT(!"Should not have been here"); } #ifdef UPNP_SUPPORT OP_STATUS WebServerConnectionListener::CloseUPnPPort() { if(m_upnp_port_opener && m_opened_port) { RETURN_IF_ERROR(ReEnableUPnPPortForwarding()); return m_upnp_port_opener->QueryDisablePort(m_opened_device, m_opened_port); } return OpStatus::ERR_NULL_POINTER; } void WebServerConnectionListener::DisableUPnPPortForwarding() { if (m_upnp_port_opener) { OpStatus::Ignore(m_upnp_port_opener->RemoveListener(this)); m_upnp_port_opener->Disable(); //OP_DELETE(m_upnp_port_opener); //m_upnp_port_opener = NULL; } } OP_STATUS WebServerConnectionListener::ReEnableUPnPPortForwarding() { if (m_upnp_port_opener) { OpStatus::Ignore(m_upnp_port_opener->AddListener(this)); return m_upnp_port_opener->ReEnable(); } return OpStatus::ERR_NULL_POINTER; } OP_STATUS WebServerConnectionListener::Failure(UPnP *upnp, UPnPDevice *device, UPnPLogic *logic) { /// There was a failure during the process, on the specified device // We want to disable UPnP port forwarding without removing UPnP Service discovery OP_ASSERT(upnp && m_upnp==upnp); m_port_checking_enabled=TRUE; if (m_real_listening_port != m_prefered_listening_port) { m_real_listening_port = m_prefered_listening_port; OP_DELETE(m_listening_socket_local); m_listening_socket_local = NULL; } m_listeningMode &= ~((unsigned int)(WEBSERVER_LISTEN_OPEN_PORT)); // Turn off WEBSERVER_LISTEN_OPEN_PORT; DisableUPnPPortForwarding(); //if(m_upnp) // m_upnp->SetSelfDelete(TRUE); //m_upnp = NULL; // Deleted later by SetSelfDelete() //m_upnp_port_opener = NULL; // Deleted by m_upnp if(!upnp_advertised) { upnp_advertised=TRUE; #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) advertisement_enabled=TRUE; #endif AdvertiseUPnP(TRUE); } //if (m_listening_socket_rendezvous) // m_listening_socket_rendezvous->CheckPort(m_real_listening_port); g_main_message_handler->PostDelayedMessage(MSG_WEBSERVER_SET_UP_LISTENING_SOCKET, 0, 0, 0); return OpStatus::OK; } /// It was possible to open the specified external port OP_STATUS WebServerConnectionListener::Success(UPnP *upnp, UPnPDevice *device, UPnPLogic *logic, UINT16 internal_port, UINT16 external_port) { /* At this point the webserver is listening on the port m_real_listening_port and UPnP is working */ m_port_checking_enabled=TRUE; m_opened_device=device; m_opened_port=internal_port; DisableUPnPPortForwarding(); // Stop trying to open more ports... if(m_webserverEventListener) m_webserverEventListener->OnPortOpened(device, internal_port, external_port); if(!upnp_advertised) { upnp_advertised=TRUE; #if defined(UPNP_SUPPORT) && defined (UPNP_SERVICE_DISCOVERY) advertisement_enabled=TRUE; #endif AdvertiseUPnP(TRUE); } OP_ASSERT(m_real_listening_port==m_opened_port); if (m_listening_socket_rendezvous) m_listening_socket_rendezvous->CheckPort(m_opened_port); return StartListeningRendezvous(); } OP_STATUS WebServerConnectionListener::ArePortsAcceptable(UPnP *upnp, UPnPDevice *device, UPnPLogic *logic, UINT16 internal_port, UINT16 external_port, BOOL &ports_acceptable) { m_real_listening_port = internal_port; OP_STATUS ops = OpStatus::OK; if (m_listening_socket_local != NULL) { if (GetLocalListeningPort() != internal_port) { StopListeningLocal(); // Immediate reconnection, to allocate the port ops = ReconnectLocal(internal_port, TRUE); } } else { ops = StartListening(); } // Listening: port acceptabled if(OpStatus::IsSuccess(ops)) { OP_ASSERT(m_listening_socket_local); ports_acceptable=TRUE; return OpStatus::OK; } ports_acceptable=FALSE; // Memory error: stop the port opening process if(OpStatus::IsMemoryError(ops)) return ops; // Other errors (usually port already in use): continue the process return OpStatus::OK; } OP_STATUS WebServerConnectionListener::PortClosed(UPnP *upnp, UPnPDevice *device, UPnPLogic *logic, UINT16 port, BOOL success) { DisableUPnPPortForwarding(); OP_ASSERT(port==m_opened_port); if(port==m_opened_port) m_opened_port=0; if (m_listening_socket_local) m_webserverEventListener->OnWebserverUPnPPortsClosed(port); return OpStatus::OK; } OP_STATUS WebServerConnectionListener::PortsRefused(UPnP *upnp, UPnPDevice *device, UPnPLogic *logic, UINT16 internal_port, UINT16 external_port) { //RETURN_IF_ERROR(StartListeningRendezvous());/* Connect to proxy even if port wasn't open */ if(m_listening_socket_local) { m_listening_socket_local->Close(); OP_DELETE(m_listening_socket_local); m_listening_socket_local=NULL; } return OpStatus::OK; } #endif // UPNP_SUPPORT #endif //WEBSERVER_SUPPORT
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "modules/logdoc/logdoc_module.h" #include "modules/logdoc/html5namemapper.h" #include "modules/logdoc/src/html5/html5base.h" #include "modules/logdoc/src/html5/elementnames.h" #include "modules/logdoc/src/html5/attrnames.h" HTML5NameMapper::~HTML5NameMapper() { for (unsigned i = 0; i < HTML5_TAG_HASH_SIZE; i++) { HTML5HashEntry *next = m_tag_hash_map[i]; while (next) { HTML5HashEntry *to_delete = next; next = next->m_next; OP_DELETE(to_delete); } } for (unsigned i = 0; i < HTML5_ATTR_HASH_SIZE; i++) { HTML5HashEntry *next = m_attr_hash_map[i]; while (next) { HTML5HashEntry *to_delete = next; next = next->m_next; OP_DELETE(to_delete); } } } void HTML5NameMapper::InitL() { // reset pointers for (unsigned i = 0; i < HTML5_TAG_HASH_SIZE; i++) m_tag_hash_map[i] = NULL; for (unsigned i = 0; i < HTML5_ATTR_HASH_SIZE; i++) m_attr_hash_map[i] = NULL; for (unsigned i = Markup::HTE_FIRST; i < Markup::HTE_LAST; i++) AddTagL(reinterpret_cast<const NameMetaData*>(&g_html5_tag_names[g_html5_tag_indices[i - Markup::HTE_FIRST]]), i); for (unsigned i = Markup::HA_FIRST; i < Markup::HA_LAST; i++) AddAttrL(reinterpret_cast<const NameMetaData*>(&g_html5_attr_names[g_html5_attr_indices[i - Markup::HA_FIRST]]), i); } Markup::Type HTML5NameMapper::GetTypeFromName(const uni_char *tag_name, unsigned tag_len, BOOL case_sensitive, Markup::Ns ns) { unsigned hashval = HTML5_TAG_HASH_BASE; HashString(tag_name, tag_len, hashval); HTML5HashEntry *entry = m_tag_hash_map[hashval % HTML5_TAG_HASH_SIZE]; if (entry) { if (EntryMatches(entry->m_key, tag_name, tag_len, case_sensitive, ns)) return static_cast<Markup::Type>(entry->m_data); entry = entry->m_next; if (entry && EntryMatches(entry->m_key, tag_name, tag_len, case_sensitive, ns)) return static_cast<Markup::Type>(entry->m_data); } return Markup::HTE_UNKNOWN; } Markup::Type HTML5NameMapper::GetTypeFromName(const uni_char *tag_name, BOOL case_sensitive, Markup::Ns ns) { unsigned hashval = HTML5_TAG_HASH_BASE; HashString(tag_name, hashval); HTML5HashEntry *entry = m_tag_hash_map[hashval % HTML5_TAG_HASH_SIZE]; if (entry) { if (EntryMatches(entry->m_key, tag_name, case_sensitive, ns)) return static_cast<Markup::Type>(entry->m_data); entry = entry->m_next; if (entry && EntryMatches(entry->m_key, tag_name, case_sensitive, ns)) return static_cast<Markup::Type>(entry->m_data); } return Markup::HTE_UNKNOWN; } Markup::Type HTML5NameMapper::GetTypeFromNameAmbiguous(const uni_char *tag_name, BOOL case_sensitive) { unsigned hashval = HTML5_TAG_HASH_BASE; HashString(tag_name, hashval); HTML5HashEntry *entry = m_tag_hash_map[hashval % HTML5_TAG_HASH_SIZE]; if (entry) { // First check if the entry has different cased versions of the string if (entry->m_key->m_offset != 0) { // If it does, check case-insensitively that it is in fact a matching entry if (uni_stri_eq(entry->m_key->m_name, tag_name)) return Markup::HTE_UNKNOWN; // If not, this is the wrong hash entry, move to next entry. } else if (case_sensitive) { // only one string representation, and we care about character // case so check if it matches exactly. if (uni_strcmp(entry->m_key->m_name, tag_name) == 0) return static_cast<Markup::Type>(entry->m_data); // If not, this is the wrong hash entry, move to next entry. } else if (uni_stri_eq(entry->m_key->m_name, tag_name)) // only one string representation, check if it matches insensitively return static_cast<Markup::Type>(entry->m_data); entry = entry->m_next; // Do the same for the next entry. if (entry) { if (entry->m_key->m_offset != 0) { if (uni_stri_eq(entry->m_key->m_name, tag_name)) return Markup::HTE_UNKNOWN; } else if (case_sensitive) { if (uni_strcmp(entry->m_key->m_name, tag_name) == 0) return static_cast<Markup::Type>(entry->m_data); } else if (uni_stri_eq(entry->m_key->m_name, tag_name)) return static_cast<Markup::Type>(entry->m_data); } } return Markup::HTE_UNKNOWN; } const uni_char* HTML5NameMapper::GetNameFromType(Markup::Type type, Markup::Ns ns, BOOL uppercase) { if (!Markup::HasNameEntry(type)) return NULL; if (uppercase) return g_html5_tag_names_upper[type - Markup::HTE_FIRST]; else { unsigned name_idx = g_html5_tag_indices[type - Markup::HTE_FIRST]; const NameMetaData *meta_data = reinterpret_cast<const NameMetaData*>(&g_html5_tag_names[name_idx]); const uni_char *tag_name = meta_data->m_name; if (meta_data->m_offset != 0 && ns != meta_data->m_ns) tag_name += meta_data->m_offset; return tag_name; } } Markup::AttrType HTML5NameMapper::GetAttrTypeFromName(const uni_char *attr_name, unsigned attr_len, BOOL case_sensitive, Markup::Ns ns) { if (!attr_name) return Markup::HA_XML; unsigned hashval = HTML5_ATTR_HASH_BASE; HashString(attr_name, attr_len, hashval); HTML5HashEntry *entry = m_attr_hash_map[hashval % HTML5_ATTR_HASH_SIZE]; if (entry) { if (EntryMatches(entry->m_key, attr_name, attr_len, case_sensitive, ns)) return static_cast<Markup::AttrType>(entry->m_data); entry = entry->m_next; if (entry && EntryMatches(entry->m_key, attr_name, attr_len, case_sensitive, ns)) return static_cast<Markup::AttrType>(entry->m_data); } return Markup::HA_XML; } Markup::AttrType HTML5NameMapper::GetAttrTypeFromName(const uni_char *attr_name, BOOL case_sensitive, Markup::Ns ns) { if (!attr_name) return Markup::HA_XML; unsigned hashval = HTML5_ATTR_HASH_BASE; HashString(attr_name, hashval); HTML5HashEntry *entry = m_attr_hash_map[hashval % HTML5_ATTR_HASH_SIZE]; if (entry) { if (EntryMatches(entry->m_key, attr_name, case_sensitive, ns)) return static_cast<Markup::AttrType>(entry->m_data); entry = entry->m_next; if (entry && EntryMatches(entry->m_key, attr_name, case_sensitive, ns)) return static_cast<Markup::AttrType>(entry->m_data); } return Markup::HA_XML; } const uni_char* HTML5NameMapper::GetAttrNameFromType(Markup::AttrType type, Markup::Ns ns, BOOL uppercase) { if (!Markup::HasAttrNameEntry(type)) return NULL; if (uppercase) return g_html5_attr_names_upper[type - Markup::HA_FIRST]; else { unsigned name_idx = g_html5_attr_indices[type - Markup::HA_FIRST]; const NameMetaData *meta_data = reinterpret_cast<const NameMetaData*>(&g_html5_attr_names[name_idx]); const uni_char *attr_name = meta_data->m_name; if (meta_data->m_offset != 0 && ns != meta_data->m_ns) attr_name += meta_data->m_offset; return attr_name; } } BOOL HTML5NameMapper::HasAmbiguousName(Markup::Type type) { if (Markup::HasNameEntry(type)) { unsigned name_idx = g_html5_tag_indices[type - Markup::HTE_FIRST]; const NameMetaData *meta_data = reinterpret_cast<const NameMetaData*>(&g_html5_tag_names[name_idx]); if (meta_data->m_offset != 0) return TRUE; } return FALSE; } void HTML5NameMapper::HashString(const uni_char *name, unsigned &hashval) { while (*name) { HTML5_HASH_FUNCTION(hashval, *name); name++; } } void HTML5NameMapper::HashString(const uni_char *name, unsigned name_len, unsigned &hashval) { while (name_len && *name) { HTML5_HASH_FUNCTION(hashval, *name); name++; name_len--; } } void HTML5NameMapper::AddTagL(const NameMetaData *meta_data, unsigned code) { unsigned position = HTML5_TAG_HASH_BASE; HashString(meta_data->m_name, position); position = position % HTML5_TAG_HASH_SIZE; if (m_tag_hash_map[position]) // collision { OP_ASSERT(!m_tag_hash_map[position]->m_next); m_tag_hash_map[position]->m_next = OP_NEW_L(HTML5HashEntry, (meta_data, code)); } else m_tag_hash_map[position] = OP_NEW_L(HTML5HashEntry, (meta_data, code)); } void HTML5NameMapper::AddAttrL(const NameMetaData *meta_data, unsigned code) { unsigned position = HTML5_ATTR_HASH_BASE; HashString(meta_data->m_name, position); position = position % HTML5_ATTR_HASH_SIZE; if (m_attr_hash_map[position]) // collision { OP_ASSERT(!m_attr_hash_map[position]->m_next); m_attr_hash_map[position]->m_next = OP_NEW_L(HTML5HashEntry, (meta_data, code)); } else m_attr_hash_map[position] = OP_NEW_L(HTML5HashEntry, (meta_data, code)); } BOOL HTML5NameMapper::EntryMatches(const NameMetaData *data, const uni_char *name, unsigned name_len, BOOL case_sensitive, Markup::Ns ns) { if (case_sensitive) { if (data->m_offset != 0 && data->m_ns != ns) return uni_strncmp(data->m_name + data->m_offset, name, name_len) == 0; return uni_strncmp(data->m_name, name, name_len) == 0; } return uni_strni_eq(data->m_name, name, name_len); } BOOL HTML5NameMapper::EntryMatches(const NameMetaData *data, const uni_char *name, BOOL case_sensitive, Markup::Ns ns) { if (case_sensitive) { if (data->m_offset != 0 && ns != data->m_ns) return uni_strcmp(data->m_name + data->m_offset, name) == 0; return uni_strcmp(data->m_name, name) == 0; } return uni_stri_eq(data->m_name, name); }
//objmodel.cpp //Handles storage and rendering of OBJ format models. //Created by Lewis Hosie //29-11-11 #include "objmodel.hpp" #include "renderer.hpp" //FIXME: Shouldn't use GL commands #include "glrenderer.hpp" fvec3 calculateflatnormal(tripoly& thepoly, fvec3* thevecs){ fvec3 a = (thevecs[thepoly.vec[1]]-thevecs[thepoly.vec[0]]).normalize(); fvec3 b = (thevecs[thepoly.vec[2]]-thevecs[thepoly.vec[0]]).normalize(); return(cross(a,b)); } const vertexbuffer& objmodel::loadmodel(std::string thefile, renderer &therenderer){ std::ifstream filereader(thefile.c_str()); std::istringstream line; std::string temp; std::string temp2; fvec3 *flatnorms; //Polygon normals float *normsums; fvec3 *norms; fvec3 *vecs; //Just a hack until I can jam it all into a VBO tripoly *polies; int novecs=0; int nopolies=0; int nonorms=0; if(!filereader.is_open()) //FIXME: ...? return therenderer.buildinvalidvertexbuffer(); //////////////////////////////////////////// // First pass // // Count the number of vertices and such. // //////////////////////////////////////////// while(!filereader.eof()){ temp2=""; std::getline(filereader,temp); line.str(temp); line.clear(); line >> temp2; if(temp2=="v") novecs++; if(temp2=="vn") nonorms++; if(temp2=="f") nopolies++; } //Allocate space vecs = new fvec3[novecs]; norms = new fvec3[novecs]; normsums = new sreal[novecs]; flatnorms = new fvec3[nopolies]; polies = new tripoly[nopolies]; //Go back to the start of the file filereader.seekg(0,std::ios::beg); filereader.clear(); nopolies=novecs=nonorms=0; //////////////////////////////////////////// // Second pass // // Load in the actual data. // //////////////////////////////////////////// while(!filereader.eof()){ temp2=""; std::getline(filereader,temp); line.str(temp); line.clear(); line >> temp2; if(temp2=="v"){ line >> vecs[novecs].x >> vecs[novecs].y >> vecs[novecs].z; novecs++; } if(temp2=="vn"){ //line >> norms[nonorms].x >> norms[nonorms].y >> norms[nonorms].z; nonorms++; } if(temp2=="f"){ //FIXME: Replace this one line with half a fucking page of C++ compliant code //THANK YOU, STRINGSTREAMS! unsigned short dummy; sscanf(line.str().c_str(),"f %hu//%hu %hu//%hu %hu//%hu", &polies[nopolies].vec[0], &dummy, &polies[nopolies].vec[1], &dummy, &polies[nopolies].vec[2], &dummy); polies[nopolies].vec[0]--; polies[nopolies].vec[1]--; polies[nopolies].vec[2]--; nopolies++; } } //Make 0 the bottom of the model float lowestpoint=99999.0f; for(int i=0; i<novecs; i++) if(vecs[i].y<lowestpoint) lowestpoint=vecs[i].y; for(int i=0; i<novecs; i++) vecs[i].y-=lowestpoint; //Make flat normals for(int i=0; i<nopolies; i++) flatnorms[i] = calculateflatnormal(polies[i],vecs); //Make smooth normals for(int i=0; i<novecs; i++){ normsums[i]=0.0f; norms[i]=fvec3(0.0f,0.0f,0.0f); } for(int i=0; i<nopolies; i++) for(int i2=0; i2<3; i2++){ norms[polies[i].vec[i2]]= norms[polies[i].vec[i2]]+flatnorms[i]; normsums[polies[i].vec[i2]] += 1.0f; } for(int i=0; i<novecs; i++) norms[i]=norms[i]/normsums[i]; //Copy to the video card const vertexbuffer& m = therenderer.buildvertexbuffer(vecs, novecs, polies, nopolies, norms, nonorms); //Delete the CPU copy delete[] vecs; delete[] norms; delete[] polies; //And we're out of here filereader.close(); return m; } objmodel::objmodel(std::string thefile, renderer& therenderer) : thevbo(loadmodel(thefile, therenderer)){ } const ragdoll& objmodel::getragdoll() const{ return theragdoll; } void objmodel::draw(const ragdollinstance& shape, renderer& therenderer) const{ if(thevbo.valid){ therenderer.pushmatrix(); therenderer.matrixtranslate(shape.getpos().x,shape.getpos().y,shape.getpos().z); therenderer.matrixscale(0.0015f,0.0015f,0.0015f); thevbo.draw(); therenderer.popmatrix(); } }
#include <iostream> #include <fstream> #include <string> using namespace std; typedef struct Date{ Date(){}; Date(int _year, int _month, int _day):year(_year),month(_month),day(_day){}; int year; int month; int day; inline void setYear(int _year){ year = _year;}; inline void setMonth(int _month){ month = _month;}; inline void setDay(int _day){day = _day;}; inline int getYear(){ return year; }; inline int getMonth(){ return month; }; inline int getDay(){ return day; }; }Date; class GISRecord{ public: GISRecord(); GISRecord(string _featureId,//1 string _featureName,//2 string _featureClass,//3 string _stateAlpha,//4 string _stateNumeric,//5 string _countryName,//6 string _countryNumeric, //7 string _primeLatDms, //8 string _primeLongDms, //9 string _primeLatDec, //10 string _primeLongDec, //11 string _sourceLatDms, //12 string _souceLongDms, //13 string _sourceLatDec, //14 string _sourceLongDec, //15 string _elevInM, //16 string _elevInFt, //17 string _mapName, //18 string _dateCreated, //19 string _dateEdited): featureId(_featureId), featureName(_featureName), featureClass(_featureClass), stateAlpha( _stateAlpha), stateNumeric(_stateNumeric), countryName(_countryName), countryNumeric(_countryNumeric), primeLatDms(_primeLatDms), primeLongDms(_primeLongDms), primeLatDec( _primeLatDec), primeLongDec(_primeLongDec), sourceLatDms(_sourceLatDms), sourceLongDms(_souceLongDms), sourceLatDec(_sourceLatDec), sourceLongDec(_sourceLongDec), elevInM(_elevInM), elevInFt(_elevInFt), mapName(_mapName), dateCreated(_dateCreated), dateEdited(_dateEdited){}; ~GISRecord(); string getFeatureId(); string getFeatureName(); string getFeatureClass(); string getStateAlpha(); string getStateNumeric(); string getCountryName(); string getCountryNumeric (); string getPrimeLongDms(); string getPrimeLatDms(); string getPrimeLongDec(); string getPrimeLatDec (); string getSourceLatDms (); string getSourceLongDms (); string getSourceLatDec (); string getSourceLongDec (); string getElevInM (); string getElevInFt(); string getMapName(); string getDateCreated(); string getDateEdited (); void setFeatureId(string _featureId); void setFeatureName(string _featureName); void setFeatureClass(string _featureClass); void setStateAlpha(string _stateAlpha); void setStateNumeric(string _stateNumeric); void setCountryName(string _countryName); void setCountryNumeric(string _countryNumeric); void setPrimeLongDms( string _primeLongDms); void setPrimeLatDms(string _primeLatDms) ; void setPrimeLongDec(string _primeLongDec); void setPrimeLatDec(string _primeLatDec); void setSourceLatDms(string _sourceLatDms); void setSourceLongDms(string _sourceLongDms); void setSourceLatDec(string _sourceLatDec); void setSourceLongDec(string _sourceLongDec) ; void setElevInM(string _elevInM); void setElevInFt(string _elevInFt); void setMapName(string _mapName) ; void setDateCreated(string _dateCreated); void setDateEdited(string _dateEdited) ; private: string featureId; // 1. FEATURE_ID string featureName;//2. FEATURE_NAME string featureClass; //3. FEATURE_CLASS string stateAlpha; //4. sTATE_ALPHA string stateNumeric; //5. sTATE_NUMERIC string countryName; //6. COUNTY_NAME string countryNumeric;//7. COUNTY_NUMERIC string primeLatDms; //8. |PRIMARY_LAT_DMS string primeLongDms; //9. PRIM_LONG_DMS string primeLatDec; //10. PRIM_LAT_DEC string primeLongDec; //11. PRIM_LONG_DEC string sourceLatDms; //12. SOURCE_LAT_DMS string sourceLongDms; //13. SOURCE_LONG_DMS string sourceLatDec; //14. SOURCE_LAT_DEC string sourceLongDec; //15. SOURCE_LONG_DEC string elevInM; //16. ELEV_IN_M string elevInFt; //17. ELEV_IN_FT string mapName; //18. MAP_NAME string dateCreated; //19. DATE_CREATED string dateEdited; //20. DATE_EDITED };
#ifndef GNANIMATION_H #define GNANIMATION_H class Gn2DMeshObject; GnSmartPointer(GnAnimation); class GnAnimation : public GnObject { GnDeclareFlags(gushort); GnDeclareRTTI; GnDeclareAbstractStream; public: enum { MASK_CREATEDATA = 0x000001, MASK_MESHSTREAM = 0x000002, }; class AniInfo : public GnSmartObject { GnDeclareDataStream; protected: float mStartTime; float mEndTime; public: inline float GetStartTime() { return mStartTime; } inline void SetStartTime(float val) { mStartTime = val; } inline float GetEndTime() { return mEndTime; } inline void SetEndTime(float val) { mEndTime = val; } }; typedef GnPointer<AniInfo> AniInfoPtr; protected: GnTObjectArray<AniInfoPtr> mInfos; GnObjectForm* mpTarget; bool mIsMeshStream; float mAniSpeed; public: GnAnimation(); virtual ~GnAnimation(){}; virtual bool CreateData() = 0; virtual void RemoveData() = 0; virtual void SetTarget(GnObjectForm* pObject); virtual void Start(float fTime){ GnAssert( false ); } virtual void Stop(){ GnAssert( false ); } virtual void SetAniInfo(gtuint uiIndex, AniInfo* pInfo) { GnAssert( pInfo ); mInfos.SetAt( uiIndex, pInfo ); } inline gtuint GetAniInfoCount() { return mInfos.GetSize(); } inline AniInfo* GetAniInfo(gtuint uiIndex) { return mInfos.GetAt( uiIndex ); } inline float GetAniSpeed() { return mAniSpeed; } inline void SetAniSpeed(float val) { mAniSpeed = val; } inline bool IsMeshStream() { return GetBit( MASK_MESHSTREAM ); } inline void SetMeshStream(bool val) { SetBit( val, MASK_MESHSTREAM ); } bool IsCreateData() { return GetBit( MASK_CREATEDATA ); } void SetCreateData( bool val ) { SetBit( val, MASK_CREATEDATA ); } // 툴을 위한 함수들 사용하게 되면 위험함 public: inline GnTObjectArray<AniInfoPtr>* GetAniInfos() { return &mInfos; } inline void AddAniInfo(AniInfo* pAniInfo) { mInfos.Add( pAniInfo ); } }; #endif // GNANIMATION_H
int left,right,brake; void setup() { Serial.begin(9600); pinMode(left,INPUT); pinMode(right,INPUT); pinMode(brake,INPUT); } void loop() { left=digitalRead(8); right=digitalRead(9); brake=digitalRead(10); if(left==1) Serial.println('1'); //Serial.print(","); if(right==1) Serial.println('2'); //Serial.print(","); if(brake==1) Serial.println('3'); delay(250); }
#include <windows.h> #include "test_world.h" #include "object.h" #include "world.h" #include "renderer_direct3d.h" #include "mesh.h" #include "obj.h" #include "file.h" #include "memory.h" static Object create_scaled_box(Renderer* renderer, const Mesh& m, const Vector3& scale, const Vector3& pos, const Color& color, unsigned id, bool is_light) { Vertex* scaled_vertices = m.vertices.clone_raw(); memcpy(scaled_vertices, m.vertices.data, m.vertices.num * sizeof(Vertex)); for (unsigned i = 0; i < m.vertices.num; ++i) { scaled_vertices[i].position = scaled_vertices[i].position * scale; scaled_vertices[i].color = color; } RRHandle box_geometry_handle = renderer->load_geometry(scaled_vertices, m.vertices.num, m.indices.data, m.indices.num); Object obj = {}; obj.geometry_handle = box_geometry_handle; obj.world_transform = matrix4x4_identity(); obj.id = id; obj.is_light = is_light; memcpy(&obj.world_transform.w.x, &pos.x, sizeof(Vector3)); { static char lightmap_filename[256]; wsprintf(lightmap_filename, "%d.data", id); Allocator ta = create_temp_allocator(); LoadedFile f = file_load(&ta, lightmap_filename); if (f.valid) { RRHandle lightmap_handle = renderer->load_texture(f.file.data, PixelFormat::R8G8B8A8_UINT_NORM, 64, 64); if (IsValidRRHandle(lightmap_handle)) obj.lightmap_handle = lightmap_handle; } } return obj; } void create_test_world(World* world, Renderer* renderer) { Allocator ta = create_temp_allocator(); LoadedMesh lm = obj_load(&ta, "box.wobj"); if (!lm.valid) return; float floor_width = 6; float floor_depth = 8; float floor_thickness = 0.3f; float floor_to_cieling = 2; float pillar_width = 0.4f; world->objects.add(create_scaled_box(renderer, lm.mesh, {floor_width, floor_thickness, floor_depth}, {0, 0, 0}, color_random(), 4, false)); world->objects.add(create_scaled_box(renderer, lm.mesh, {pillar_width, floor_to_cieling, pillar_width}, {-1, (floor_thickness + floor_to_cieling) / 2, 1}, color_random(), 12, false)); world->objects.add(create_scaled_box(renderer, lm.mesh, {pillar_width, floor_to_cieling, pillar_width}, {-1, (floor_thickness + floor_to_cieling) / 2, -1}, color_random(), 123, false)); world->objects.add(create_scaled_box(renderer, lm.mesh, {floor_width, floor_thickness, floor_depth}, {0, floor_thickness + floor_to_cieling, 0}, color_random(), 145, false)); //world->objects.add(create_scaled_box(renderer, lm.mesh, {floor_width, floor_thickness, floor_depth}, {0, floor_thickness + floor_to_cieling - 15, 0}, color::random(), 12333)) //world->objects.add(create_scaled_box(renderer, lm.mesh, {2,2,2}, {0, 0, 0}, color::random(), 145, false)); //world->objects.add(create_scaled_box(renderer, lm.mesh, {1,1,1}, vector3::lookdir * 5, color::random(), 145)); //world::add_object(world, create_scaled_box(renderer, lm.mesh, {1, 1, 1}, {-10, 0, 0}, color::random())); if (lm.valid) { world->objects.add(create_scaled_box(renderer, lm.mesh, {10, 10, 10}, {-20, 25, -19}, {1,1,1,1}, 10000, true)); } }
#ifndef TF_SYNTHESIZER_H_ #define TF_SYNTHESIZER_H_ #include <memory> #include <string> #include <vector> namespace tts { class TensorflowSynthesizer { public: TensorflowSynthesizer(); ~TensorflowSynthesizer(); void init(int argc, char* argv[]); /// /// Load's pretrained TF model. /// bool load(const std::string& graph_filename, const std::string& inp_layer, const std::string& out_layer); /// /// Synthesize speech. /// /// @param[in] input_sequence Input sequence. Shape = [N, T_in]. /// @param[in] input_lengths Tensor with shape = [N], where N is batch size /// and values are the lengths /// of each sequence in inputs. /// @param[out] output Output audio data(floating point) /// bool synthesize(const std::vector<int32_t>& input_sequence, const std::vector<int32_t> &input_lengths, std::vector<float> *output); private: class Impl; std::unique_ptr<Impl> impl; }; } // namespace tts #endif // TF_SYNTHESIZER_H_
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) for(auto i: x){cout << i << " ";} #define showm(m) for(auto i: m){cout << m.x << " ";} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} int main() { int n, m; cin >> n >> m; priority_queue<int, vector<int>> a; rep(i, n){ int tmp; cin >> tmp; a.push(tmp);} rep(i, m){ int price = a.top(); a.pop(); price /= 2; a.push(price); } ll sum = 0; while(!a.empty()) { sum += a.top(); a.pop(); } cout << sum << endl; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #ifdef _SSL_USE_OPENSSL_ #include "modules/libssl/sslbase.h" #include "modules/libssl/options/sslopt.h" #include "modules/libssl/ssl_api.h" #include "modules/libssl/external/openssl/eayhead.h" #include "modules/libssl/external/openssl/sslhash.h" #include "modules/libssl/methods/sslnull.h" #include "modules/libssl/methods/sslmd5sha.h" #include "modules/url/tools/arrays.h" typedef const EVP_MD* (*EVP_MD_CB)(); struct SSL_Digest_and_NID { SSL_HashAlgorithmType digest_type; int hmac; SSL_HashAlgorithmType hmac_digest_type; int nid; EVP_MD_CB func; }; #define MD_ENTRY(typ, hmac_typ, is_hmac, digest_name) \ CONST_ENTRY_START(digest_type, typ) \ CONST_ENTRY_SINGLE(hmac, is_hmac)\ CONST_ENTRY_SINGLE(hmac_digest_type, hmac_typ)\ CONST_ENTRY_SINGLE(nid, NID_##digest_name)\ CONST_ENTRY_SINGLE( func, EVP_##digest_name )\ CONST_ENTRY_END // param2 "name" will be expanded to NID_name and EVP_name PREFIX_CONST_ARRAY(static, SSL_Digest_and_NID, SSL_Digest_map, libssl) MD_ENTRY(SSL_MD5, SSL_HMAC_MD5, FALSE, md5) MD_ENTRY(SSL_SHA, SSL_HMAC_SHA, FALSE, sha1) MD_ENTRY(SSL_SHA_256, SSL_HMAC_SHA_256, FALSE, sha256) MD_ENTRY(SSL_SHA_384, SSL_HMAC_SHA_384, FALSE, sha384) MD_ENTRY(SSL_SHA_512, SSL_HMAC_SHA_512, FALSE, sha512) MD_ENTRY(SSL_HMAC_SHA, SSL_HMAC_SHA, TRUE, sha1) MD_ENTRY(SSL_HMAC_SHA_256, SSL_HMAC_SHA_256, TRUE, sha256) MD_ENTRY(SSL_HMAC_SHA_384, SSL_HMAC_SHA_384, TRUE, sha384) MD_ENTRY(SSL_HMAC_SHA_512, SSL_HMAC_SHA_512, TRUE, sha512) MD_ENTRY(SSL_HMAC_MD5, SSL_HMAC_MD5, TRUE, md5) MD_ENTRY(SSL_HMAC_SHA_256, SSL_HMAC_SHA_256, TRUE, sha256) MD_ENTRY(SSL_SHA_224, SSL_HMAC_SHA_224, FALSE, sha224) MD_ENTRY(SSL_HMAC_SHA_224, SSL_HMAC_SHA_224, TRUE, sha224) #ifndef OPENSSL_NO_RIPEMD MD_ENTRY(SSL_RIPEMD160, SSL_HMAC_RIPEMD160, FALSE, ripemd160) MD_ENTRY(SSL_HMAC_RIPEMD160, SSL_HMAC_RIPEMD160, TRUE, ripemd160) #endif CONST_END(SSL_Digest_map) static const SSL_Digest_and_NID *GetSpecFromAlgorithm(SSL_HashAlgorithmType digest) { size_t i; for(i = 0; i<CONST_ARRAY_SIZE(libssl, SSL_Digest_map); i++) { if(g_SSL_Digest_map[i].digest_type == digest) { return &g_SSL_Digest_map[i]; } } return NULL; } const EVP_MD *GetMD_From_Algorithm(SSL_HashAlgorithmType digest) { const SSL_Digest_and_NID *spec = GetSpecFromAlgorithm(digest); return (spec ? spec->func() : NULL); } SSL_Hash *SSL_API::CreateMessageDigest(SSL_HashAlgorithmType digest, OP_STATUS &op_err) { op_err = OpStatus::OK; OpAutoPtr<SSL_Hash> hasher(NULL); switch(digest) { case SSL_NoHash: hasher.reset(OP_NEW(SSL_Null_Hash, ())); if(hasher.get() == NULL) { op_err = OpStatus::ERR_NO_MEMORY; } break; case SSL_MD5_SHA: hasher.reset(OP_NEW(SSL_MD5_SHA_Hash, ())); if(hasher.get() == NULL) { op_err = OpStatus::ERR_NO_MEMORY; } break; default: { const SSL_Digest_and_NID *alg_spec = GetSpecFromAlgorithm(digest); if(alg_spec == NULL) { #ifdef EXTERNAL_DIGEST_API extern SSL_Hash *GetExternalDigestMethod(SSL_HashAlgorithmType digest, OP_STATUS &op_err); return GetExternalDigestMethod(digest, op_err); #else op_err = OpStatus::ERR_OUT_OF_RANGE; return NULL; #endif } hasher.reset(alg_spec->hmac ? (SSL_Hash *) OP_NEW(SSLEAY_HMAC_Hash, (alg_spec)) : (SSL_Hash *) OP_NEW(SSLEAY_Hash, (alg_spec))); if(hasher.get() == NULL) { op_err = OpStatus::ERR_NO_MEMORY; } else if(hasher->Error()) { op_err = hasher->GetOPStatus(); hasher.reset(); } else hasher->InitHash(); } } return hasher.release(); } SSLEAY_Hash_Base::SSLEAY_Hash_Base(const SSL_Digest_and_NID *spec) : alg_spec(spec), md_spec(NULL) { OP_ASSERT(alg_spec); if(alg_spec) { md_spec = spec->func(); hash_alg = alg_spec->digest_type; hash_size = md_spec->md_size; } } SSLEAY_Hash_Base::~SSLEAY_Hash_Base() { alg_spec = NULL; md_spec = NULL; } BOOL SSLEAY_Hash_Base::Valid(SSL_Alert *msg) const { if(Error(msg)) return FALSE; if (md_spec == NULL) { if(msg != NULL) msg->Set(SSL_Internal,SSL_InternalError); return FALSE; } return TRUE; } void SSLEAY_CheckError(SSL_Error_Status *target); void SSLEAY_Hash_Base::CheckError() { SSLEAY_CheckError(this); } /* static SSLEAY_Hash md5(EVP_md5()); static SSLEAY_Hash sha(EVP_sha1()); SSL_Hash *SSL_Master_Hash_md5 = &md5; SSL_Hash *SSL_Master_Hash_sha = &sha; */ SSLEAY_Hash::SSLEAY_Hash(const SSL_Digest_and_NID *spec) : SSLEAY_Hash_Base(spec) { EVP_MD_CTX_init(&md_status); InitHash(); } /* Unref YNP SSLEAY_Hash::SSLEAY_Hash(const SSLEAY_Hash &old) : md_spec(old.alg_spec) { if(md_spec != NULL){ memset(&md_status,0,sizeof(md_status)); } // InitHash(); } */ SSLEAY_Hash::SSLEAY_Hash(const SSLEAY_Hash *old) : SSLEAY_Hash_Base(old ? old->alg_spec : NULL) { OP_ASSERT(old); EVP_MD_CTX_init(&md_status); if(old) { ERR_clear_error(); if (!EVP_MD_CTX_copy(&md_status, &old->md_status)) CheckError(); } else InitHash(); } SSLEAY_Hash::~SSLEAY_Hash() { EVP_MD_CTX_cleanup(&md_status); } void SSLEAY_Hash::InitHash() { if(md_spec != NULL) { ERR_clear_error(); EVP_MD_CTX_cleanup(&md_status); EVP_DigestInit(&md_status,md_spec); CheckError(); } } const byte *SSLEAY_Hash::CalculateHash(const byte *source,uint32 len) { #ifdef TST_DUMP PrintfTofile("sslhash.txt", "SSLEAY_Hash::CalculateHash %p", this); DumpTofile(source, len, "SSLEAY_Hash::CalculateHash","sslhash.txt"); #endif ERR_clear_error(); EVP_DigestUpdate(&md_status, source,(size_t) len); CheckError(); return source+len; } byte *SSLEAY_Hash::ExtractHash(byte *target) { EVP_MD_CTX temp; ERR_clear_error(); if (EVP_MD_CTX_copy(&temp, &md_status)) EVP_DigestFinal(&temp,target,NULL); CheckError(); #ifdef TST_DUMP PrintfTofile("sslhash.txt", "SSLEAY_Hash::ExtractHash %p", this); DumpTofile(target, md_spec->md_size, "SSLEAY_Hash::ExtractHash","sslhash.txt"); #endif return target + md_spec->md_size; } #endif SSL_Hash *SSLEAY_Hash::Fork() const { SSLEAY_Hash *temp; temp = OP_NEW(SSLEAY_Hash, (this)); return temp; } // HMAC implementation int HMAC_CTX_copy(HMAC_CTX *ctx, const HMAC_CTX *ctx_old) { ctx->md = ctx_old->md; if (!EVP_MD_CTX_copy(&ctx->i_ctx, &ctx_old->i_ctx)) return 0; if (!EVP_MD_CTX_copy(&ctx->o_ctx, &ctx_old->o_ctx)) return 0; if (!EVP_MD_CTX_copy(&ctx->md_ctx, &ctx_old->md_ctx)) return 0; ctx->key_length = ctx_old->key_length; op_memcpy(ctx->key, ctx_old->key, ctx_old->key_length); return 1; } SSLEAY_HMAC_Hash::SSLEAY_HMAC_Hash(const SSL_Digest_and_NID *spec) : SSLEAY_Hash_Base(spec) { HMAC_CTX_init(&md_status); md_status.key_length = 0; InitHash(); } SSLEAY_HMAC_Hash::SSLEAY_HMAC_Hash(const SSLEAY_HMAC_Hash *old) : SSLEAY_Hash_Base(old ? old->alg_spec : NULL) { OP_ASSERT(old); HMAC_CTX_init(&md_status); md_status.key_length = 0; if(old) { ERR_clear_error(); if (!HMAC_CTX_copy(&md_status, &old->md_status)) CheckError(); } else InitHash(); } SSLEAY_HMAC_Hash::~SSLEAY_HMAC_Hash() { HMAC_CTX_cleanup(&md_status); } void SSLEAY_HMAC_Hash::InitHash() { if(md_spec != NULL) { ERR_clear_error(); //HMAC_CTX_cleanup(&md_status); HMAC_Init_ex(&md_status,NULL, 0, md_spec, NULL); CheckError(); } } const byte *SSLEAY_HMAC_Hash::LoadSecret(const byte *source, uint32 len) { if(md_spec) { if(source == NULL) { source = (const byte *) g_memory_manager->GetTempBuf2k(); len = 0; } HMAC_Init_ex(&md_status, source, len, md_spec, NULL); if(source) source += len; } return source; } const byte *SSLEAY_HMAC_Hash::CalculateHash(const byte *source,uint32 len) { if(source && len) { ERR_clear_error(); HMAC_Update(&md_status, source,(size_t) len); CheckError(); source += len; } return source; } byte *SSLEAY_HMAC_Hash::ExtractHash(byte *target) { HMAC_CTX temp; ERR_clear_error(); HMAC_CTX_init(&temp); if (HMAC_CTX_copy(&temp, &md_status)) HMAC_Final(&temp,target,NULL); HMAC_CTX_cleanup(&temp); CheckError(); return target + md_spec->md_size; } SSL_Hash *SSLEAY_HMAC_Hash::Fork() const { SSLEAY_HMAC_Hash *temp; temp = OP_NEW(SSLEAY_HMAC_Hash, (this)); return temp; } #endif
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #ifndef HASH_H #define HASH_H #include "modules/util/OpHashTable.h" #include "adjunct/desktop_util/string/hash-literal.inc" namespace Hash { /** Create a 32-bit hash for a string * @param string String to hash * @return 32-bit hash calculated using djbhash */ inline unsigned String(const char* string) { return OpGenericString8HashTable::HashString(string, TRUE); } inline unsigned String(const uni_char* string) { return OpGenericStringHashTable::HashString(string, TRUE); } /** Create a 32-bit hash for a string of known length * @param string String to hash * @param length Amount of characters in string to consider in hashing (first length characters) * @return 32-bit hash calculated using djbhash */ inline unsigned String(const char* string, unsigned length) { return OpGenericString8HashTable::HashString(string, length, TRUE); } inline unsigned String(const uni_char* string, unsigned length) { return OpGenericStringHashTable::HashString(string, length, TRUE); } }; /** Create a 32-bit hash for a string literal * @note this macro will calculate a hash value at compile-time. Only use it for string literals. * @note HASH_LITERAL(x) == Hash::String(x) * @example unsigned hash = HASH_LITERAL("example"); * * @param string String to hash * @return 32-bit hash calculated using djbhash */ #define HASH_LITERAL(string) DJBHASH_LITERAL(string) #endif // HASH_H
#ifndef _ERROR_AERO_H_ #define _ERROR_AERO_H_ #include "../../Toolbox/Toolbox.h" #include "../Log/Log.h" #include <assert.h> namespace ae { namespace priv { /// \ingroup debugging /// <summary> /// Set of function to check standard error /// (HResult, errno_t, OpenGL errors, ...) and /// log an error if the error retrieve is not ok. /// </summary> /// <param name="_Error">Value to check.</param> /// <returns>True if the value was ok, False otherwise.</returns> class AERO_CORE_EXPORT Error { public: /// <summary>Check an HResult value value to see if it is ok.</summary> /// <param name="_Result">Value to check.</param> /// <returns>True if the value was ok, False otherwise.</returns> static Bool CheckHResult( const Uint32 _Result ); /// <summary>Check an errno_t value to see if it is ok.</summary> /// <param name="_Error">Value to check.</param> /// <returns>True if the value was ok, False otherwise.</returns> static Bool CheckErrno( const Uint32 _Error ); /// <summary>Check an OpenGL error value to see if it is ok.</summary> /// <param name="_glError">Value to check.</param> /// <returns>True if the value was ok, False otherwise.</returns> static Bool CheckOpenGLError( const Uint32 _glError ); /// <summary>Convert a HResult error value to a Win32 error value.</summary> /// <param name="_ErrorCode">HResult value to convert.</param> /// <returns>HResult error value converted.</returns> static Uint32 Win32FromHResult( Uint32 _ErrorCode ); /// <summary>Reset "buffer" of the errno_t value.</summary> static void ResetErrno(); }; } // priv } // ae /** @file Error.h */ /** * @addtogroup debugging * * @{ */ /// <summary>Check an HResult value to see if it is ok.</summary> /// <param name="_Result">Value to check.</param> /// <returns>True if the value was ok, False otherwise.</returns> #define AE_ErrorCheckHResult(_Result) ( ae::priv::Error::CheckHResult( _Result ) ) /// <summary>Check an errno_t value to see if it is ok.</summary> /// <param name="_Error">Value to check.</param> /// <returns>True if the value was ok, False otherwise.</returns> #define AE_ErrorCheckErrno(_Error) ( ae::priv::Error::CheckErrno( _Error ) ) /// <summary>Check an OpenGL error value to see if it is ok.</summary> /// <returns>True if the value was ok, False otherwise.</returns> #define AE_ErrorCheckOpenGLError() ( ae::priv::Error::CheckOpenGLError( glGetError() ) ) /// <summary> /// Check a condition and if the condition fail, the message is log and an assert is rose. /// </summary> /// <param name="_ConditionToVerify">Condition to check. If this condition is not valid, the program will stop.</param> /// <param name="_Message">The message to log.</param> #define AE_Assert(_ConditionToVerify, _Message) \ if(!(_ConditionToVerify)) \ { \ AE_LogError( _Message ); \ assert( _ConditionToVerify ); \ } /** @} */ #endif // _ERROR_AERO_H_
#ifndef ACTIONWIDGET_H #define ACTIONWIDGET_H #include <QDialog> class actionWidget : public QDialog { Q_OBJECT public: explicit actionWidget(QWidget *parent = nullptr); void setWindowTitleAndShowThis(const QString &titleName); signals: public slots: }; #endif // ACTIONWIDGET_H
#include "GnGamePCH.h" #include "GStateUILayer.h" #include "GStateItem.h"
//: C10:InitializerDefs.cpp {O} // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Definicje dla pliku Initializer.h #include "Initializer.h" // Statyczna inicjalizacja spowoduje // wyzerowanie wartosci ponizszych zmiennych: int x; int y; int Initializer::initCount; ///:~
#include <stdlib.h> #include <stdio.h> #define WEAK __attribute__ ((weak)) // #include "uart.hpp" // #include "gpio.hpp" #include "LPC17xx.h" // #include "lpc17xx_nvic.h" void *operator new(size_t size) throw() { return malloc(size); } void operator delete(void *p) throw() { return free(p); } // UART *dbg = 0; // GPIO **leds = 0; // // void _dbg_init() { // if (dbg == 0) { // dbg = new UART(0, 230400); // } // } // // void _dbgled_init() { // if (leds == 0) { // // TODO: BOARD SPECIFIC // #define N_LEDS 4 // leds = (GPIO **) malloc(sizeof(void *) * N_LEDS); // leds[0] = new GPIO(1, 20); // leds[1] = new GPIO(1, 25); // leds[2] = new GPIO(1, 29); // leds[3] = new GPIO(0, 10); // for (int i = 0; i < N_LEDS; i++) { // leds[i]->output(); // } // } // } // // uint8_t _cansend() { // return dbg->cansend(); // } extern "C" { // void init_nvic() { // NVIC_DeInit(); // NVIC_SCBDeInit(); // extern void* __cs3_interrupt_vector_cortex_m; // NVIC_SetVTOR((uint32_t) &__cs3_interrupt_vector_cortex_m); // } // // uint8_t cansend() { // return _cansend(); // } // // void dbgled(int l) { // _dbgled_init(); // for (int i = 0; i < N_LEDS; i++) { // leds[i]->write(l & 1); // l >>= 1; // } // } void WEAK _exit(int i) { while (1); } int WEAK _kill(int pid, int signal) { return 0; } int WEAK _getpid() { return 0; } int WEAK __aeabi_atexit(void *object, void (*destructor)(void *), void *dso_handle) { return 0; } int WEAK _write(int fd, uint8_t *buf, size_t buflen) { // _dbg_init(); // dbg->send((uint8_t *) buf, buflen); return buflen; } int WEAK _close(int fd) { return 0; } int WEAK _lseek(int file, int ptr, int dir) { return ptr; } int WEAK _read(int file, char *buf, int len) { // _dbg_init(); // return dbg->recv((uint8_t *) buf, len); return 0; } void* WEAK _sbrk(int incr) { extern char _ebss; // Defined by the linker static char *heap_end; char *prev_heap_end; if (heap_end == 0) { heap_end = &_ebss; } prev_heap_end = heap_end; char * stack = (char*) __get_MSP(); if (heap_end + incr > stack) { //_write (STDERR_FILENO, "Heap and stack collision\n", 25); //errno = ENOMEM; return (void *) -1; //abort (); } heap_end += incr; return prev_heap_end; } int WEAK _fstat(int file, void *st) { return 0; } int WEAK _isatty(int fd) { if (fd <= 2) return 1; return 0; } }
#include "sender.h" Sender::Sender() { setupUi(this); /******************************* UDP *****************************************/ socket = new QUdpSocket(this); connect(socket, SIGNAL(readyRead()), this, SLOT(donneesRecues())); tailleMessage = 0; } void Sender::on_btnbind_clicked() { textEdit->append(tr("<em>Bind attempt in progress...</em>")); socket->bind(QHostAddress(IPadress->text()), portsource->value()); textEdit->append(tr("<em>Ok</em>")); } void Sender::on_command_returnPressed() { QByteArray Data; message = command->text(); message = message + "\n"; Data.append( message.toStdString().c_str()); socket->writeDatagram(Data, QHostAddress(IPadress->text()), portdestination->value()); if(root == 0){ message = tr("<strong>") + "User : " +tr("</strong> ") + message; textEdit->append(message);} textEdit->ensureCursorVisible(); command->clear(); // On vide la zone d'écriture du message command->setFocus(); // Et on remet le curseur à l'intérieur } void Sender::donneesRecues() { // when data comes in QByteArray buffer; buffer.resize(socket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; socket->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort); portdestination->setValue(senderPort); //qDebug() << "Message: " << buffer; if( buffer == "\n"){ textEdit->setFontWeight(QFont::Bold); textEdit->insertPlainText(tr("M580 : ")); textEdit->setFontWeight(QFont::Normal); } else textEdit->insertPlainText(buffer); textEdit->ensureCursorVisible(); } Sender::~Sender(){} void Sender::WriteText(QString text) { textEdit->append(text); } void Sender::setroot(bool c) { root = c; } bool Sender::getroot() { return root; }
/* * ThreeDObject.cpp * 02564_Framework * * Created by J. Andreas Bærentzen on 02/02/10. * Copyright 2010 __MyCompanyName__. All rights reserved. * */ #include <CGLA/Quatf.h> #include <CGLA/Mat4x4f.h> #include "ThreeDObject.h" using namespace CGLA; using namespace Mesh; using namespace std; namespace GLGraphics { bool ThreeDObject::init(std::string filename){ return mesh.load(filename, true); } void ThreeDObject::display(ShaderProgramDraw& shader_prog) { Quatf q; q.make_rot(rotation_angle*M_PI/180.0, rotation_axis); Mat4x4f M = translation_Mat4x4f(translation_vector) *q.get_Mat4x4f() *scaling_Mat4x4f(scaling_factors); shader_prog.set_model_matrix(M); mesh.render(shader_prog); } }
#include<iostream> #include<set> #include<vector> #include<cmath> #define FOR(i,n) for(i=0;i<n;i++) using namespace std; int main() { set<vector<int>>s; set<vector<int>>::iterator it; vector<int>v; string input,tmp; int i,j,ni=0,qnum,period,t,k; while(1) { getline(cin,input); if(input=="#")break; tmp.clear();v.clear(); j=9; while(input[j]!=' '){tmp+=input[j];j++;}j++; qnum=stoi(tmp); tmp.clear(); for(;j<input.length();j++){tmp+=input[j];} period=stoi(tmp); v.push_back(period);v.push_back(qnum);v.push_back(period); s.insert(v); } cin>>k; FOR(i,k) { it=s.begin(); cout<<(*it)[1]<<endl; v.clear(); v.push_back((*it)[0]+(*it)[2]);v.push_back((*it)[1]);v.push_back((*it)[2]); s.insert(v); s.erase(it); } return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/Actor.h" #include "Grid.generated.h" UCLASS() class MEMORYMATRIXPROVA_API AGrid : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AGrid(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; void NovoLevel(); void Verificar(class ASquares* Click); void GameOver(); private: UPROPERTY(EditAnywhere) USceneComponent* Root; TSubclassOf<class ASquares> Quad; TSubclassOf<class UUserWidget> GameOverWidget; TArray<class ASquares*> Quadrados; TArray<int> Posicao; float LocationX = 0.0f; float LocationZ = 0.0f; int Sequencia = 3; int NumCLicks; int MatrixCol = 3; int MatrixRow = 3; int LevelCont = 1; void Tabuleiro(); void ViraQuadrado(); //void NovoLevel(); FTimerHandle ClickTempo; };
// // Created by heyhey on 20/03/2018. // #include "ExpressionUnaire.h" ExpressionUnaire::ExpressionUnaire() {} ExpressionUnaire::~ExpressionUnaire() { } ostream &operator<<(ostream &os, const ExpressionUnaire &unaire) { os << static_cast<const Expression &>(unaire); os << endl; return os; } ExpressionUnaire::Operateur ExpressionUnaire::getOperateur() const { return operateur; } void ExpressionUnaire::setOperateur(ExpressionUnaire::Operateur operateur) { ExpressionUnaire::operateur = operateur; } void ExpressionUnaire::setExpression (Expression* expression){ ExpressionUnaire::expression = expression; } Expression* ExpressionUnaire::getExpression () const{ return expression; }
//所用算法:DFS+回溯 ,记忆化搜索 //使用maxx数组存从当前点开始化的最大距离 //然后套dfs模板,并存以各点为起点的最长距离 #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int n,m; int a[110][110];//存图 bool use[110][110];//是否用过 int maxx[110][110];//记忆距离 int ax[5]={1,-1,0,0}; int ay[5]={0,0,1,-1}; int ans=-1; int dfs(int,int); int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++)//输入 for(int j=1;j<=m;j++) scanf("%d",&a[i][j]); for(int i=1;i<=n;i++)//依次枚举各点作为起点 for(int j=1;j<=n;j++) if(!use[i][j]) { use[i][j]=1; int tot1=dfs(i,j);//计算以此点为起点的距离 maxx[i][j]=tot1; use[i][j]=0; if(tot1>ans) ans=tot1;//记录最大值 } printf("%d",ans); } int dfs(int x,int y) { if(maxx[x][y])//如果被记录,就直接返回 return maxx[x][y]; int tot2=0; for(int i=0;i<4;i++) { int xx=x+ax[i]; int yy=y+ay[i]; if(!use[xx][yy] && xx>=1 && yy>=1 && xx<=n && yy<=m) if(a[xx][yy] < a[x][y]) { use[xx][yy]=1; tot2=max( dfs(xx,yy),tot2 );//找到它能到达的点的最大距离 use[xx][yy]=0; } } return tot2+1;//返回能到达的点+此点的和 }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back // 昇順sort #define sorti(x) sort(x.begin(), x.end()) // 降順sort #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) /* 考察 スライムを捕まえる操作は一番短い時間で済むものにしたい xがスライムを捕まえる時間に比べて十分に短かったら 1 2 1 2 2 3 1 2 3 捕まえる時間が一番短いスライムを捕獲 -> 魔法 を繰り返せば良い xが大きい場合 小さいスライムを捕獲して,変色 基本指針 捕獲時間がx以下だったらまとめて変色 */ int main() { ll n,x; scanf("%lld %lld", &n, &x); vector<pair<ll,ll>> a(n); // a.first -> 捕獲時間,a.second -> スライムの番号 rep(i,n) { ll t; cin >> t; a[i] = make_pair(t,i); } sorti(a); int total = 0; ll ans = 0; vector<bool> check(n,false); vector<int> h,e; while (total != n) { ll tsum = 0; for (int i = 0; i < n; ++i) { if (check[a[i].second] == false) { tsum += a[i].first; if (tsum > x && h.size() != 0) { tsum -= a[i].first; } h.pb(i); } } ans += tsum; e.clear(); rep(i,n) check[i] = false; for (auto itr : h) { if (itr == n-1) { check[0] = true; e.pb(0); } else { check[itr + 1] = true; e.pb(itr+1); } } h.clear(); total = e.size(); if (total != h.size()) { ans += x; } } cout << ans << endl; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- // // Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Patricia Aas // #include "core/pch.h" #include "adjunct/desktop_util/handlers/PluginContainer.h" /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ PluginContainer::PluginContainer(OpString * plugin_path, OpString * plugin_description, OpString * plugin_name, OpBitmap * plugin_icon) : DownloadManager::Container(plugin_name, plugin_icon) { SetPath(plugin_path); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ const OpStringC& PluginContainer::GetPath() { return m_path; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ const OpStringC& PluginContainer::GetDescription() { return m_description; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void PluginContainer::SetPath(OpString * plugin_path) { if(plugin_path) m_path.Set(plugin_path->CStr()); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void PluginContainer::SetDescription(OpString * plugin_description) { if(plugin_description) m_description.Set(plugin_description->CStr()); }
#ifndef OFXCOMMANDPROCESSORTHREADH #define OFXCOMMANDPROCESSORTHREADH class ofxCommandProcessorThread { protected: //HANDLE thread_handle_; // bool thread_active_; public: /* ofxCommandProcessorThread() :thread_handle_() ,thread_active_(false) { } */ virtual bool start() = 0; /* thread_handle_ = (HANDLE)_beginthread(threadProc,0,this); return (thread_handle_ != NULL); } */ virtual void join() = 0; // if(thread_handle_) { // ::WaitForSingleObject(thread_handle_, INFINITE); // } // } virtual void sleep(int nMillis) = 0; //{ // if(thread_handle_) { // Sleep(nMillis); // } // } virtual void run() = 0; protected: // static void threadProc(void* lParam) { // ofxCommandProcessorThread* thread = (ofxCommandProcessorThread*)lParam; // if(thread != NULL) { // thread->thread_active_ = true; // thread->run(); // thread->thread_active_ = false; // } // _endthread(); // } }; #endif
#include <bits/stdc++.h> using namespace std; struct Job{ int d, p; Job(int d = 0, int p = 0) : d(d), p(p) {} bool operator < (const Job& rhs) const { return d < rhs.d; } Job operator + (const Job& rhs) const { return Job(d + rhs.d,p + rhs.p); } }; const int maxn = 1e5 + 10; Job jobs[maxn]; int maxv[maxn]; int n; int m; // //int query(int lo, int hi) { // int ans = 0; // for (lo += n - 1, hi += n + 1; lo ^ hi ^ 1; lo >>= 1, hi >>= 1) { // if (~lo & 1) ans = max(ans, st[lo ^ 1].p); // if (hi & 1) ans = max(ans, st[hi ^ 1].p); // } // return ans; //} int main() { scanf("%d %d", &n, &m); for (int i = 0; i < n; ++i) { scanf("%d %d", &jobs[i].d, &jobs[i].p); } sort(jobs, jobs + n); maxv[0] = jobs[0].p; for (int i = 1; i < n; ++i) { maxv[i] = max(maxv[i - 1], jobs[i].p); } for (int i = 0; i < m; ++i) { int temp; scanf("%d", &temp); for (int j = n - 1; j >= 0; --j) { if (jobs[j].d <= temp) { printf("%d\n", maxv[j]); break; } } } return 0; }
class FoodbeefCooked { weight = 0.25; }; class FoodmuttonCooked { weight = 0.25; }; class FoodchickenCooked { weight = 0.25; }; class FoodrabbitCooked { weight = 0.25; }; class FoodbaconCooked { weight = 0.25; }; class FoodGoatCooked { weight = 0.25; }; class FoodGoatRaw { weight = 0.25; }; class FoodmuttonRaw { weight = 0.25; }; class FoodchickenRaw { weight = 0.25; }; class FoodBaconRaw { weight = 0.25; }; class FoodRabbitRaw { weight = 0.25; }; class FoodbeefRaw { weight = 0.25; }; class FoodDogRaw { weight = 0.25; }; class FoodDogCooked { weight = 0.25; };
#include "string_util.h" namespace sloth { std::string loadStringFromFile(const char * filepath) { // 1. Retrieve the vertex/fragment source code from filePath std::string str; try { // Open files std::ifstream file(filepath); std::stringstream stream; // Read file's buffer contents into stream stream << file.rdbuf(); // close file handler file.close(); // Convert stream into string str = stream.str(); } catch (std::exception e) { std::cout << "ERROR::SHADER: Failed to read shader files" << std::endl; } return str; } void split(std::string & s, std::string & delim, std::vector<std::string>* ret) { size_t last = 0; size_t index = s.find_first_of(delim, last); while (index != std::string::npos) { ret->push_back(s.substr(last, index - last)); last = index + 1; index = s.find_first_of(delim, last); } if (index - last > 0) { ret->push_back(s.substr(last, index - last)); } } }
// Fill out your copyright notice in the Description page of Project Settings. #include "EditorGridTick.h" #include <string> using namespace std; // Sets default values AEditorGridTick::AEditorGridTick() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } //bool AEditorGridTick::ShouldTickIfViewportsOnly() const //{ // return true; //} // Called when the game starts or when spawned void AEditorGridTick::BeginPlay() { Super::BeginPlay(); } // Called every frame void AEditorGridTick::Tick(float DeltaTime) { //Super::Tick(DeltaTime); //EditorGridTickEvent(); //if (GEngine) //{ // GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, // TEXT("Some debug message!")); //} } //void AEditorGridTick::EditorGridTickEvent_Implementation() //{ //} //void AEditorGridTick::print_test() //{ // // //} //void AEditorGridTick::print_test() //{ // if (GEngine) // { // GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, // TEXT("Some debug message!")); // } //}
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef DOM_FEEDCONTENT_H #define DOM_FEEDCONTENT_H #ifdef WEBFEEDS_BACKEND_SUPPORT #include "modules/dom/src/domobj.h" class OpFeedContent; class DOM_Environment; class DOM_FeedContent : public DOM_Object { private: OpFeedContent* m_content; ///< The real feedcontent object from the WebFeed backend DOM_FeedContent() : m_content(NULL) {} public: static OP_STATUS Make(DOM_FeedContent *&out_content, OpFeedContent *content, DOM_Runtime *runtime); virtual ~DOM_FeedContent(); void OnDeleted(); virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual BOOL IsA(int type) { return type == DOM_TYPE_FEEDCONTENT || DOM_Object::IsA(type); } }; #endif // WEBFEEDS_BACKEND_SUPPORT #endif // DOM_FEEDCONTENT_H
#include<bits/stdc++.h> using namespace std; int a[1000]; int find(int k){ if(k==1) return a[1]; if(k==2) return a[2]; if(k%2 == 1) return find(k/2)*10 + 4; return find(k/2-1)*10 + 7; } int main(){ a[1] = 4; a[2] = 7; int k; cin >> k; cout << find(k); }
#include "Obstacle.h" #include "../CSC8503Common//StateTransition.h" #include "../CSC8503Common/StateMachine.h" #include "../CSC8503Common//State.h" //#include "../GameTech/TutorialGame.h" using namespace NCL; using namespace CSC8503; Obstacle::Obstacle() { float x = rand() % 20 - 10; float z = rand() % 5 + 1; float forceX = x / 20.0f; constForce = Vector3(forceX, -0.98, 2); } Obstacle::~Obstacle() { //delete stateMachine; } void Obstacle::Update(float dt) { //stateMachine->Update(dt); if (firstTime) { this->GetPhysicsObject()->GetInverseMass(); GetPhysicsObject()->AddTorque(constForce + Vector3(0, 600 / this->GetPhysicsObject()->GetInverseMass(), 0)); GetPhysicsObject()->AddForce(constForce + Vector3(0, 6000 / this->GetPhysicsObject()->GetInverseMass(), 0)); firstTime = false; } GetPhysicsObject()->AddForce(constForce * 50 / this->GetPhysicsObject()->GetInverseMass()); GetPhysicsObject()->AddTorque(Vector3(10, 0, 0) * 20 / this->GetPhysicsObject()->GetInverseMass()); } void Obstacle::MoveLeft(float dt) { GetPhysicsObject()->AddForce({ -10, 0, 0 }); counter += dt; } void Obstacle::MoveRight(float dt) { GetPhysicsObject()->AddForce({ 10, 0, 0 }); counter -= dt; }
#pragma once #include "color.h" #include "math.h" class PointLight { public: Vec3 pos; RGB color; PointLight( Vec3 p , RGB c ) : pos(p) , color(c) {}; }; class Directional { public: Vec3 dir; RGB color; Directional( Vec3 d , RGB c ) : dir(d) , color(c) {}; };
#ifndef DEMONSUMMON_H #define DEMONSUMMON_H #include <iostream> #include "Spell.h" #include "../units/Warlock.h" class DemonSummon : public Spell { private: int demonNumber; public: DemonSummon(int magicDamage = static_cast<int>(DEMONSUMMON::STANDARD), int cost = static_cast<int>(DEMONSUMMON::COST), const std::string& formula = castFormulas::DEMONSUMMON); virtual void action(Unit* enemy, Unit* attacker, int magicDamage) override; }; #endif // DEMONSUMMON_H
// // 8.cpp // REVIEW BAGUS // // Created by Mikha Yupikha on 16/10/2016. // Copyright © 2016 Mikha Yupikha. All rights reserved. // #include <iostream> using namespace std; int main() { string colour1, colour2; cout<<"Please enter two primary colours (red, blue or yellow): "; cin>>colour1>>colour2; if (colour1=="red" && colour2=="blue") cout<<"The mix of that two colour is purple."<<endl; else if (colour1=="blue" && colour2=="red") cout<<"The mix of that two colour is purple."<<endl; else if (colour1=="red" && colour2=="yellow") cout<<"The mix of that two colour is orange."<<endl; else if ( colour1=="yellow" && colour2=="red") cout<<"The colour of that two colours is orange."<<endl; else if (colour1=="blue" && colour2=="yellow") cout<<"The mix of that two colours is green."<<endl; else if ( colour1=="yellow" && colour2=="blue") cout<<"The mix of that two colours is green." <<endl; else cout<<"That are not primary colour."<<endl; return 0; }
#include "recorder.h" Recorder::Recorder(bool t, bool r, bool n, QWidget *parent, Qt::WFlags flags) { noPlot = n; record = r; trigger = t; QWidget *centralWidget = new QWidget(); QGridLayout *layout = new QGridLayout(); centralWidget->setLayout(layout); setCentralWidget(centralWidget); plotWidget = new MeanPlotWidget(this); cam = new QEye(); camThread = new QThread(); cam->moveToThread(camThread); camThread->start(); conv = new TiffConverter(this); imageLabel = new ImageLabel(this); imageLabel->setText(tr("bla")); layout->addWidget(imageLabel,0,0); recordButton = new QPushButton("Record"); recordButton->setCheckable(true); layout->addWidget(recordButton); triggerButton = new QPushButton("External Trigger"); triggerButton->setCheckable(true); layout->addWidget(triggerButton); createMenus(); makeConnections(); errors = 0; QTimer::singleShot(.1, this, SLOT(doThings())); } void Recorder::makeConnections() { connect(cam, SIGNAL(newImage(QImage *)), imageLabel, SLOT(setImage(QImage *))); //connect(cam, SIGNAL(errors(int)), this, SLOT(onError(int))); connect(cam, SIGNAL(transferCountersChanged(int, int, int)), this, SLOT(onCountersChanged(int, int, int))); connect(recordButton, SIGNAL(toggled(bool)), this, SLOT(onRecordButton(bool))); connect(triggerButton, SIGNAL(toggled(bool)), cam, SLOT(setExternalTrigger(bool))); connect(imageLabel, SIGNAL(mouseWheelSteps(int)), this, SLOT(onLabelMouseWheel(int))); connect(plotWidget, SIGNAL(closing()), this, SLOT(onPlotWidgetClosing())); connect(showPlot, SIGNAL(triggered()), this, SLOT(onShowPlot())); } void Recorder::createMenus() { showPlot = new QAction(tr("Show Plot"), this); showPlot->setCheckable(true); showPlot->setChecked(false); setMenuBar(new QMenuBar()); viewMenu = menuBar()->addMenu(tr("&View")); viewMenu->addAction(showPlot); } void Recorder::onShowPlot() { if(showPlot->isChecked()) { plotWidget->show(); connect(cam, SIGNAL(newMat(cv::Mat *)), plotWidget, SLOT(newMat(cv::Mat *))); connect(imageLabel, SIGNAL(newRoi(QRect)), plotWidget, SLOT(newRoi(QRect))); } else { plotWidget->hide(); disconnect(cam, SIGNAL(newMat(cv::Mat *)), plotWidget, SLOT(newMat(cv::Mat *))); } } Recorder::~Recorder() { } QSize Recorder::sizeHint() { return QSize(800, 600); } void Recorder::onRecordButton(bool checked) { if(checked) cam->startRecording(); else cam->stopRecording(); } void Recorder::doThings() { if(cam->init() != 0) { int camsFound = QEye::countFreeCams(); statusBar()->showMessage("Init failed"); QMessageBox noCamMsgBox(this); noCamMsgBox.setText(tr("There are %1 uEye cameras on this network. No free camera could be found. Check if the camera is already opened somewhere else and check the network connections. Then restart this program.").arg(camsFound)); noCamMsgBox.exec(); recordButton->setDisabled(true); return; } else { cam->startCapturing(); statusBar()->showMessage("Ready"); if(trigger) { cam->setExternalTrigger(true); } if(record) { recordButton->setChecked(true); cam->startRecording(); } } } void Recorder::closeEvent(QCloseEvent *event) { blockSignals(true); statusBar()->showMessage("Shutting down"); cam->exit(); plotWidget->close(); qDebug("recorder: this is the end"); } void Recorder::onLabelMouseWheel(int steps) { double exp = 0; exp = cam->getExposure(); cam->setExposure(exp + (double) steps/10); } void Recorder::onCountersChanged(int received, int recorded, int errors) { statusBar()->showMessage(tr("Images Received: %1, Errors: %2, Images Recorded: %3").arg(received).arg(recorded).arg(errors)); } void Recorder::onPlotWidgetClosing() { showPlot->setChecked(false); disconnect(cam, SIGNAL(newMat(cv::Mat *)), plotWidget, SLOT(newMat(cv::Mat *))); }
#include<bits/stdc++.h> using namespace std; vector<int>as; main() { int n, m; while(cin>>n>>m) { int x, i, j; for(x=0; x<m; x++) { cin>>i; as.push_back(i); cin>>j; as.push_back(j); } i=1; cout<<n-1<<endl; sort(as.begin(), as.end()); for(x=0; x<as.size(); x++) { if(as[x]==i)i++; } for(x=1; x<=n; x++) { if(x!=i)cout<<i<<" "<<x<<endl; } } return 0; }
// // Trigonometry.h // Odin.MacOSX // // Created by Daniel on 21/09/15. // Copyright (c) 2015 DG. All rights reserved. // #ifndef Odin_MacOSX_Trigonometry_h #define Odin_MacOSX_Trigonometry_h #include <cmath> #include "Vector2.h" #include "Vector3.h" #include "Vector4.h" namespace odin { namespace math { // ANGLE & TRIGONOMETRY FUNCTIONS F32 radians(F32 degrees); vec2 radians(const vec2& degrees); vec3 radians(const vec3& degrees); vec4 radians(const vec4& degrees); F32 degrees(F32 radians); vec2 degrees(const vec2& radians); vec3 degrees(const vec3& radians); vec4 degrees(const vec4& radians); F32 sin(F32 angle); vec2 sin(const vec2& angle); vec3 sin(const vec3& angle); vec4 sin(const vec4& angle); F32 cos(F32 angle); vec2 cos(const vec2& angle); vec3 cos(const vec3& angle); vec4 cos(const vec4& angle); F32 tan(F32 angle); vec2 tan(const vec2& angle); vec3 tan(const vec3& angle); vec4 tan(const vec4& angle); F32 asin(F32 x); vec2 asin(const vec2& x); vec3 asin(const vec3& x); vec4 asin(const vec4& x); F32 acos(F32 x); vec2 acos(const vec2& x); vec3 acos(const vec3& x); vec4 acos(const vec4& x); F32 atan(F32 y_over_x); vec2 atan(const vec2& y_over_x); vec3 atan(const vec3& y_over_x); vec4 atan(const vec4& y_over_x); F32 atan(F32 y, F32 x); vec2 atan(const vec2& y, const vec2& x); vec3 atan(const vec3& y, const vec3& x); vec4 atan(const vec4& y, const vec4& x); F32 sinh(F32 x); vec2 sinh(const vec2& x); vec3 sinh(const vec3& x); vec4 sinh(const vec4& x); F32 cosh(F32 x); vec2 cosh(const vec2& x); vec3 cosh(const vec3& x); vec4 cosh(const vec4& x); F32 tanh(F32 x); vec2 tanh(const vec2& x); vec3 tanh(const vec3& x); vec4 tanh(const vec4& x); F32 asinh(F32 x); vec2 asinh(const vec2& x); vec3 asinh(const vec3& x); vec4 asinh(const vec4& x); F32 acosh(F32 x); vec2 acosh(const vec2& x); vec3 acosh(const vec3& x); vec4 acosh(const vec4& x); F32 atanh(F32 x); vec2 atanh(const vec2& x); vec3 atanh(const vec3& x); vec4 atanh(const vec4& x); #include "Trigonometry.inl" } } #endif
#include "core.h" double* ArrayIn(int size) { double *array = new double[size]; for (int i = 0; i < size; i++) array[i] = EnterDouble(); return array; }
#include "sphere.h" bool Sphere::hit(const Ray& r, float t_min, float t_max, HitDesc& desc) const { glm::vec3 oc = r.origin - center; auto a = glm::dot(r.direction, r.direction); auto b = glm::dot(oc, r.direction); auto c = glm::dot(oc, oc) - radius * radius; float d = b * b - a * c; if (d > 0.0f) { float temp = (-b - glm::sqrt(b * b - a * c)) / a; if (temp < t_max && temp > t_min) { desc.t = temp; desc.p = r.point_at(temp); desc.normal = (desc.p - center) / radius; return true; } temp = (-b + glm::sqrt(b * b - a * c)) / a; if (temp < t_max && temp > t_min) { desc.t = temp; desc.p = r.point_at(temp); desc.normal = (desc.p - center) / radius; return true; } } return false; }
/* SegaCDI - Sega Dreamcast cdi image validator. DisjointCollection.h - Creates a copy of a collection and provides utilities for iterating and enumerating through the collection. Dec 30th, 2016 - Initial creation. */ #pragma once #include "../stdafx.h" #include <iterator> #include "FlatMemoryIterator.h" template<class T> class DisjointCollection : std::iterator<std::input_iterator_tag, T> { private: // Our collection pointer. T *m_pCollection; // Number of elements in the collection. size_t m_dwCount; public: DisjointCollection(T* pCollection, size_t dwCount) { // Allocate a new collection we can copy data to. this->m_dwCount = dwCount; this->m_pCollection = new T[this->m_dwCount]; // Loop through the collection and perform a deep copy using the copy constructor. It // is not the most reliable method but as long as we are careful what datatypes we consume // in this class it shouldn't be a problem. for (int i = 0; i < this->m_dwCount; i++) { // Copy the current element. this->m_pCollection[i] = T(pCollection[i]); } } DisjointCollection(const DisjointCollection &other) { // Allocate a new collection we can copy data to. this->m_dwCount = other.m_dwCount; this->m_pCollection = new T[this->m_dwCount]; // Loop through the collection and perform a deep copy using the copy constructor. It // is not the most reliable method but as long as we are careful what datatypes we consume // in this class it shouldn't be a problem. for (int i = 0; i < this->m_dwCount; i++) { // Copy the current element. this->m_pCollection[i] = T(other.m_pCollection[i]); } } ~DisjointCollection() { // Free the collection we allocated. delete[] this->m_pCollection; } size_t size() { // Return the number of elements in the collection. return this->m_dwCount; } T* operator[](int index) { // Check to make sure the index is valud. if (index < 0 || index >= this->m_dwCount) return nullptr; // Return a constant reference to the element at the specified index. return &this->m_pCollection[index]; } T* get(int index) { // Use the indexer operator to get the object. return this->operator[](index); } FlatMemoryIterator<T>* CreateIterator() { // Create a new FlatMemoryIterator with the current collection and return it. return new FlatMemoryIterator<T>(this->m_pCollection, this->m_dwCount); } };
#include <stdio.h> #include <iostream> #include <cstdio> #include <ctime> #include "brick_servo.h" #include "bricklet_joystick.h" #include "ip_connection.h" #define HOST "localhost" #define PORT 4223 #define UID_SERVO "6CRBxX" #define UID_JOYSTICK "w6J" std::clock_t start_count; // Timer std::clock_t s_timer_1; std::clock_t s_timer_2; std::clock_t s_timer_3; double dur_1, dur_2, dur_3 = 0; // END bool start; Servo servo; Joystick jstick; int16_t presses = 0; int16_t servo_oben_pos = 0; int16_t servo_unten_pos = 300; // Geschwindigkeit für den unteren Motor in pos. Richtung int16_t servo_unten_neg = -300; // Geschwindigkeit für den unteren Motor in neg. Richtung // Callbacks void cb_pressed(void *user_data); void cb_position(int16_t x, int16_t y, void *user_data); void cb_change_position(int16_t x, int16_t y, void *user_data); // Funktionen void rotate_servo(int16_t servo_num, double speed); void calibrate_motor(double seconds, double speed); void wait(double time); int main(void) { IPConnection ipcon; ipcon_create(&ipcon); int16_t x, y; joystick_create(&jstick, UID_JOYSTICK, &ipcon); servo_create(&servo, UID_SERVO, &ipcon); // Stellt Verbindung zu den Bausteinen her if (ipcon_connect(&ipcon, HOST, PORT) < 0) { fprintf(stderr, "Could not connect\n"); return 1; } // setzen der Spannung für die Servo-Motoren servo_set_output_voltage(&servo, 5500); // Grundlegende Einstellungen Servo-0 servo_set_degree(&servo, 0, -5000, 5000); // Drehwinkel min, max servo_set_pulse_width(&servo, 0, 1000, 2000); // PWM servo_set_period(&servo, 0, 19500); servo_set_acceleration(&servo, 0, 30000); // Max Beschleunigung(65535) servo_set_velocity(&servo, 0, 65535); // Max Geschwindigkei(65535) // Grundlegende Einstellungen Servo-1 servo_set_degree(&servo, 1, -2000, 2000); servo_set_pulse_width(&servo, 1, 1000, 2000); servo_set_period(&servo, 1, 20000); servo_set_acceleration(&servo, 1, 65535); servo_set_velocity(&servo, 1, 65535); servo_set_position(&servo, 0, 0); // Servo-Motor in die Mitte servo_set_position(&servo, 1, 0); servo_enable(&servo, 0); servo_enable(&servo, 1); // Kalibrierung //calibrate_motor(3, 500); // dreht den unteren Servo-Motor(servo_num: 1) 5 sekunden lang mit was auch immer 2000 für eine Geschwindigkeit ist //calibrate_motor(3, -500); joystick_set_debounce_period(&jstick, 100); joystick_register_callback(&jstick, JOYSTICK_CALLBACK_PRESSED, (void *)cb_pressed, NULL); joystick_register_callback(&jstick, JOYSTICK_CALLBACK_POSITION, (void *)cb_position, NULL); joystick_register_callback(&jstick, JOYSTICK_CALLBACK_POSITION_REACHED, (void *)cb_change_position, NULL); joystick_set_position_callback_threshold(&jstick, 'o', -99, 99, -99, 99); // TEST joystick_set_position_callback_period(&jstick, 100); printf("Press key to exit\n"); getchar(); servo_disable(&servo, 0); servo_disable(&servo, 1); servo_destroy(&servo); joystick_destroy(&jstick); ipcon_destroy(&ipcon); return 0; } void calibrate_motor(double seconds, double speed) { std::clock_t start; double duration = 0; start = std::clock(); /* ### Funktion für die Servo-Motoren hier: ### */ //servo_set_position(&servo, num, speed); // num mit der Nummer des Motors ersetzen //servo_set_position(&servo, num, speed); // num mit der Nummer des Motors ersetzen servo_set_position(&servo, 1, speed); while (duration <= seconds) { duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; } servo_set_position(&servo, 1, 0); //servo_set_position(&servo, num, 0); // hier auch, und dann die kommentar "//" entfernen //servo_set_position(&servo, num, 0); } void rotate_servo(int16_t servo_num, double speed) { s_timer_1 = std::clock(); std::cout << servo_num << std::endl; /* ### Funktion für die Servo-Motoren hier: ### */ servo_set_position(&servo, servo_num, speed); //servo_set_position(&servo, num, speed); // num mit der Nummer des Motors ersetzen //servo_set_position(&servo, num, speed); // num mit der Nummer des Motors ersetzen //servo_set_position(&servo, num, 0); // hier auch, und dann die kommentar "//" entfernen //servo_set_position(&servo, num, 0); } void wait(double time) { while (dur_1 <= time) { dur_1 = (std::clock() - s_timer_1) / (double)CLOCKS_PER_SEC; std::cout << dur_1 << std::endl; }; dur_1 = 0; } void cb_pressed(void *user_data) { //std::clock_t start_count; if(presses == 0) start_count = std::clock(); double dur; dur = (std::clock() - start_count) / (double)CLOCKS_PER_SEC; (void)user_data; int a = joystick_is_pressed(&jstick, &start); std::cout << a << std::endl; presses++; if (presses >= 2 && dur <= 1) { // dur <= 1, die "eins" entspricht der zeit in sekunden std::cout << "Doppel-Klick!"; //calibrate_motor(3, 500); // dreht den unteren Servo-Motor(servo_num: 1) 5 sekunden lang mit was auch immer 2000 für eine Geschwindigkeit ist //calibrate_motor(3, -500); start = true; while (start) { // ABLAUF #1 rotate_servo(1, 300); // Busy-Wait: kann nichts anderes in der zeit ausgeführt werden wait(2); // ABLAUF #2 rotate_servo(1, -300); wait(3); rotate_servo(1, 200); servo_set_position(&servo, 0, 4000); wait(2); rotate_servo(1, -200); wait(3); } presses = 0; } servo_set_position(&servo, 0, 0); servo_set_position(&servo, 1, 0); servo_oben_pos = 0; std::cout << "Pressed!" << std::endl; if (presses > 1 || dur > 1) presses = 0; } void cb_position(int16_t x, int16_t y, void *user_data) { (void)user_data; std::cout << "X: " << x << std::endl; if (x == 0) { servo_set_position(&servo, 1, 0); } } void cb_change_position(int16_t x, int16_t y, void *user_data) { (void)user_data; int16_t pos; servo_get_position(&servo, 0, &pos); if (y == 100) { std::cout << "UP!" << std::endl; servo_set_position(&servo, 0, pos += (y * 5)); } else if (y == -100) { std::cout << "DOWN!" << std::endl; servo_set_position(&servo, 0, pos += (y * 5)); } if (x == 100) { std::cout << "RIGHT!" << std::endl; servo_set_position(&servo, 1, servo_unten_pos); } else if (x == -100) { std::cout << "LEFT!" << std::endl; servo_set_position(&servo, 1, servo_unten_neg); } }
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <algorithm> #include <cmath> #include <cstring> #include <stdexcept> #include <GL/glut.h> #include "wavefront_obj.h" namespace { using double2 = wavefront_obj_t::double2; using double3 = wavefront_obj_t::double3; double3 normalize(double3 u) { double l = 0; for (int i = 0; i < 3; i++) { l += u[i] * u[i]; } if (l == 0) { return u; } l = sqrt(l); for (int i = 0; i < 3; i++) { u[i] /= l; } return u; } //Given three vertices forming a triangle, compute the normal direction of its face double3 compute_face_normal(double3 &v0, double3 &v1, double3 &v2) { double3 a, b, n; for (int i = 0; i < 3; ++i) { a[i] = v1[i] - v0[i]; b[i] = v2[i] - v0[i]; } n[0] = a[1] * b[2] - a[2] * b[1]; n[1] = a[2] * b[0] - a[0] * b[2]; n[2] = a[0] * b[1] - a[1] * b[0]; return normalize(n); } //Given a list (represented by a pair of iterators) of vertices, compute axis-aligned bounding box (AABB). template<class IterT> std::pair<double3, double3> compute_aabb(IterT vert_begin, IterT vert_end) { std::pair<double3, double3> aabb{ double3{ 0, 0, 0 }, double3{ 0, 0, 0 } }; for (; vert_begin != vert_end; ++vert_begin) { auto &vert = *vert_begin; for (int i = 0; i < 3; ++i) { aabb.first[i] = std::min(aabb.first[i], vert[i]); aabb.second[i] = std::max(aabb.second[i], vert[i]); } } return aabb; } } wavefront_obj_t::wavefront_obj_t(char *path) { is_flat = true; std::string line; std::istringstream line_stream, item_stream; std::ifstream file(path); if (!file) throw std::runtime_error("Cannot open file."); while (std::getline(file, line)) { // strip off comments and blank lines if (line[0] == '#' || line.size() == 0) continue; // parse line line_stream.clear(); line_stream.str(line); std::string mode; line_stream >> mode; if (mode == "v") { double x, y, z; line_stream >> x >> y >> z; vertices.push_back(double3{ x, y, z }); } else if (mode == "vn") { double x, y, z; line_stream >> x >> y >> z; normals.push_back(normalize(double3{ x, y, z })); } else if (mode == "vt") { double u, v; line_stream >> u >> v; texcoords.push_back(double2{ u, v }); } else if (mode == "f") { face_t face; std::memset(&face, 0, sizeof(face_t)); face.idx_begin = vertex_indices.size(); std::string item; while (line_stream >> item) { item_stream.clear(); item_stream.str(item); int v = 0, t = 0, n = 0; do { item_stream >> v; char c; if (!(bool(item_stream >> c) && c == '/')) continue; if (!(item_stream >> t)) item_stream.clear(); if (!(bool(item_stream >> c) && c == '/')) continue; if (!(item_stream >> n)) item_stream.clear(); } while (false); vertex_indices.push_back(v - 1); texcoord_indices.push_back(t - 1); normal_indices.push_back(n - 1); ++face.count; if (n) is_flat = false; } if (face.count > 2) { face.normal = compute_face_normal( vertices[vertex_indices[face.idx_begin]], vertices[vertex_indices[face.idx_begin + 1]], vertices[vertex_indices[face.idx_begin + 2]] ); } faces.push_back(face); } // -------------------------------------------------- // [Proj 4] /* (Unneeded...) else if (mode == "g") { // group } else if (mode == "s") { // smoothing group } else if (mode == "u") { // material line } else { std::cerr << "Warning: unsupported Wavefront OBJ option: " << mode << "\n"; } */ // -------------------------------------------------- } aabb = compute_aabb(std::begin(vertices), std::end(vertices)); } //------------------------------------------------------------------------------ // OpenGL API ¸¦ »ç¿ëÇØ¼­ ÆÄÀÏ¿¡¼­ ÀоîµÐ object ¸¦ ±×¸°´Ù. // Draw object which is read from file void wavefront_obj_t::draw() { for (std::size_t f = 0; f < faces.size(); f++) { face_t &face = faces[f]; glBegin(gl_primitive_mode); for (std::size_t v = 0; v < face.count; v++) { int vi = face.idx_begin + v; int i; if (is_flat) { if (v == 0) { glNormal3dv(face.normal.data()); } } else if ((i = normal_indices[vi]) >= 0) { glNormal3dv(normals[i].data()); } if ((i = texcoord_indices[vi]) >= 0) { glTexCoord2dv(texcoords[i].data()); } if ((i = vertex_indices[vi]) >= 0) { glVertex3dv(vertices[i].data()); } } glEnd(); } }
int rtp_recv_init(); int main(int argc,char **argv) { rtp_recv_init(); }
#include <iostream> using namespace std; int main() { int years; int money; int moneyAnnually cout<<"Enter the years you are saving for"<<endl; cin<<years; cout<<"Enter the amount of money you are saving daily"<<endll; cin<<money; moneyAnnually = money * 365; int yearsRemaining int totalMoney = 0; for (yearsRemaining = years; yearsRemaining >= 0; yearsRemaining = yearsRemaining - 1) { totalMoney = totalMoney + ((moneyAnnually * 1.1) ^ yearsRemaining); } cout<<"The money you will save is: " <<cout totalMoney; }
#include "ActionManager.h" #include "Core.h" ActionManager::ActionManager(void) { } ActionManager::~ActionManager(void) { } void ActionManager::init(typeplayercontrol control[2]) { playertype[0]=control[0]; playertype[1]=control[1]; keylimit=2; setfirstkeys(); for (int i=0;i<keylimit;i++) { playeractions[i].up=false; playeractions[i].down=false; playeractions[i].left=false; playeractions[i].right=false; playeractions[i].punch=false; playeractions[i].kick=false; playeractions[i].defense=false; playeractions[i].megapunch=false; playeractions[i].deathray=false; } } void ActionManager::update(float timeElapsed) { for (int i=0;i<keylimit;i++) { if (playertype[i]==keyboardcontrol) { readkeyinput(timeElapsed,i); } else if (playertype[i]==networkcontrol) { readnetinput(timeElapsed,i); } } } void ActionManager::readkeyinput(float timeElapsed,int index) { OIS::Keyboard* keyboard = Core::singleton().inputManager().getKeyboard(); if (index==0) { setfirstkeys(); } else { setsecondkeys(); } playeractions[index].up=keyboard->isKeyDown(up_KC); playeractions[index].down=keyboard->isKeyDown(down_KC); playeractions[index].left=keyboard->isKeyDown(left_KC); playeractions[index].right=keyboard->isKeyDown(right_KC); playeractions[index].punch=keyboard->isKeyDown(punch_KC); playeractions[index].kick=keyboard->isKeyDown(kick_KC); playeractions[index].defense=keyboard->isKeyDown(defense_KC); playeractions[index].megapunch=keyboard->isKeyDown(megapunch_KC); playeractions[index].deathray=keyboard->isKeyDown(deathray_KC); } void ActionManager::readnetinput(float timeElapsed, int index) { //TODO } void ActionManager::setplayeractions(int index, actions inputplayeractions) { playeractions[index].up=inputplayeractions.up; playeractions[index].down=inputplayeractions.down; playeractions[index].left=inputplayeractions.left; playeractions[index].right=inputplayeractions.right; playeractions[index].punch=inputplayeractions.punch; playeractions[index].kick=inputplayeractions.kick; playeractions[index].defense=inputplayeractions.defense; playeractions[index].megapunch=inputplayeractions.megapunch; playeractions[index].deathray=inputplayeractions.deathray; } void ActionManager::setfirstkeys() { megapunch_KC=OIS::KC_LSHIFT; punch_KC=OIS::KC_LCONTROL; up_KC=OIS::KC_SPACE; kick_KC=OIS::KC_RSHIFT; left_KC=OIS::KC_LEFT; defense_KC=OIS::KC_UP; right_KC=OIS::KC_RIGHT; down_KC=OIS::KC_DOWN; //no defino deathray porque no tengo /* up_KC=OIS::KC_I; down_KC=OIS::KC_K; left_KC=OIS::KC_J; right_KC=OIS::KC_L; punch_KC=OIS::KC_D; kick_KC=OIS::KC_S; megapunch_KC=OIS::KC_E; deathray_KC=OIS::KC_W; defense_KC=OIS::KC_A; */ } void ActionManager::setsecondkeys() { megapunch_KC=OIS::KC_Z; punch_KC=OIS::KC_X; up_KC=OIS::KC_V; kick_KC=OIS::KC_M; left_KC=OIS::KC_G; defense_KC=OIS::KC_Y; right_KC=OIS::KC_J; down_KC=OIS::KC_H; /* up_KC=OIS::KC_UP; down_KC=OIS::KC_DOWN; left_KC=OIS::KC_LEFT; right_KC=OIS::KC_RIGHT; punch_KC=OIS::KC_NUMPAD1; kick_KC=OIS::KC_NUMPAD2; megapunch_KC=OIS::KC_NUMPAD4; deathray_KC=OIS::KC_NUMPAD5; defense_KC=OIS::KC_NUMPAD3; */ }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ group "posix.pi.networkinterface"; require POSIX_OK_NETWORK; import "pi.opnetworkinterface"; // group "posix.networkinterface"; // Any implementation-specific tests ?
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 1995-2003 Opera Software ASA. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // #include "core/pch.h" #include "LinksPanel.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "adjunct/quick/models/LinksModel.h" #include "adjunct/quick_toolkit/widgets/OpQuickFind.h" #include "adjunct/quick_toolkit/widgets/OpToolbar.h" #include "adjunct/quick/widgets/OpLinksView.h" #include "modules/widgets/WidgetContainer.h" #include "modules/dochand/win.h" #include "modules/dochand/winman.h" #include "modules/inputmanager/inputmanager.h" #include "modules/url/url_man.h" #include "modules/widgets/OpEdit.h" #include "modules/locale/oplanguagemanager.h" /*********************************************************************************** ** ** Init ** ***********************************************************************************/ OP_STATUS LinksPanel::Init() { RETURN_IF_ERROR(OpLinksView::Construct(&m_links_view)); AddChild(m_links_view, TRUE); m_links_view->GetTree()->SetSystemFont(OP_SYSTEM_FONT_UI_PANEL); SetToolbarName("Links Panel Toolbar", "Links Full Toolbar"); SetName("Links"); return OpStatus::OK; } /*********************************************************************************** ** ** GetPanelText ** ***********************************************************************************/ void LinksPanel::GetPanelText(OpString& text, Hotlist::PanelTextType text_type) { g_languageManager->GetString(Str::M_VIEW_HOTLIST_MENU_LINKS, text); } /*********************************************************************************** ** ** OnFullModeChanged ** ***********************************************************************************/ void LinksPanel::OnFullModeChanged(BOOL full_mode) { m_links_view->SetDetailed(full_mode); } /*********************************************************************************** ** ** OnLayout ** ***********************************************************************************/ void LinksPanel::OnLayoutPanel(OpRect& rect) { m_links_view->SetRect(rect); } /*********************************************************************************** ** ** OnFocus ** ***********************************************************************************/ void LinksPanel::OnFocus(BOOL focus,FOCUS_REASON reason) { if (focus) { m_links_view->SetFocus(reason); } } /*********************************************************************************** ** ** OnInputAction ** ***********************************************************************************/ BOOL LinksPanel::OnInputAction(OpInputAction* action) { return m_links_view->OnInputAction(action); }