text
stringlengths
8
6.88M
#define _USE_MATH_DEFINES #include <cmath> #include <string> #include "linalg.h" using std::string; /* * * Выражение для энергетического спектра (в декартовых координатах) * */ double energy(const Point & p); /* * * Выражение для энергетического спектра (в полярных координатах) * */ double energy_theta(double p, double theta); vec2 energy_gradient(const Point & p); /* * * Компоненты скорости * */ vec2 velocity(const Point & p); /* * * Правые части уравнений движения * */ vec2 forces(const Point & p, double t); /* * * Границы первой зоны Бриллюэна * */ double pmax(double theta); /* * * Функция, приводящая квазиимпульс к первой зоне Бриллюэна * */ Point to_first_bz(const Point & p);
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ int n; ll h, a, b, c, d, e; cin >> n >> h >> a >> b >> c >> d >> e; }
#ifndef CONTINUOUS_TIME_COLLISION_HANDLER_H #define CONTINUOUS_TIME_COLLISION_HANDLER_H #include "CollisionHandler.h" #include <vector> #include <iostream> class ContinuousTimeCollisionHandler : public CollisionHandler { public: ContinuousTimeCollisionHandler(double COR) : CollisionHandler(COR) {} virtual void handleCollisions(TwoDScene &scene, const VectorXs &oldpos, VectorXs &oldvel, scalar dt ); virtual std::string getName() const; public: bool detectParticleParticle (const TwoDScene &scene, const VectorXs &qs, const VectorXs &qe, int idx1, int idx2, Vector2s &n, double &time); bool detectParticleEdge (const TwoDScene &scene, const VectorXs &qs, const VectorXs &qe, int vidx, int eidx, Vector2s &n, double &time); bool detectParticleHalfplane (const TwoDScene &scene, const VectorXs &qs, const VectorXs &qe, int vidx, int pidx, Vector2s &n, double &time); void respondParticleParticle (const TwoDScene &scene, const VectorXs &qs, const VectorXs &qe, int idx1, int idx2, const Vector2s &n, double time, double dt, VectorXs &qm, VectorXs &qdotm); void respondParticleEdge (const TwoDScene &scene, const VectorXs &qs, const VectorXs &qe, int vidx, int eidx, const Vector2s &n, double time, double dt, VectorXs &qm, VectorXs &qdotm); void respondParticleHalfplane (const TwoDScene &scene, const VectorXs &qs, const VectorXs &qe, int vidx, int pidx, const Vector2s &n, double time, double dt, VectorXs &qm, VectorXs &qdotm); }; #endif
#ifndef NOTES_H_INCLUDED #define NOTES_H_INCLUDED #include<string> #include "timing.h" #include <ctime> using namespace TIME; using namespace std; /*********************************************************************/ /********************************************************************* *** Execption *** **********************************************************************/ class NotesException{ public: NotesException(const string& message):info(message) {} string getInfo() const { return info; } private: string info; }; /*********************************************************************/ /********************************************************************* *** Note Abstract Class *** **********************************************************************/ class Note { private: string id ; string title ; Date dateCreation; Date dateLastModif; bool archive; //attributs statiques réunissant l'ensemble des ids de toutes les notes static string* ids; static unsigned int nbId, nbMaxId; public: ///Constructor Note(const string i, const string t, Date d_c, Date d_lm): id(i), title(t), dateCreation(d_c), dateLastModif(d_lm), archive(false){addID(i);} ///Memento //Memento createMemento(); //setMemento(Memento m); ///Accessor in Reading (return by const ref) const string& getId() const {return id;} const string& getTitle() const {return title;} const Date& getDateCreation() const {return dateCreation ;} const Date& getLastModif() const {return dateLastModif ;} const bool GetArchive() const {return archive ;} ///Modify attribute void SetTitle(const string& newTitle) {title=newTitle ;} void SetDateCreation(Date& newDate) {dateCreation=newDate ;} void setDateLastCreation(Date& newDate) {dateLastModif=newDate;} void SetArchive() {archive=!archive ;} Note& setId(const string& i) {id = i; addID(i); return *this;} void addID(const string & id); //Get Ascendant/Descendant in all differents Relations void getRelAsc(const string& /*titre de la note à obtenir*/); void getRelDesc(const string&); virtual Note* clone()=0 ; virtual ~Note() {} // implement to delete in all relation /// Class Iterator class Iterator{ friend class Note; string* currentI; int nbRemain; Iterator(string*a, int nb): currentA(a), nbRemain(nb){} public: bool isDone()const {return nbRemain == 0;} Article& current() const{ return *currentI;} void next(){ if(isDone()) throw NotesException("ERROR : fin de la collection"); currentI++; nbRemain--; } }; //Méthode static car on itère sur l'attribut static ids (ensemble des IDs de toutes les notes) static Iterator getIterator() const; /*********************************************************************/ /********************************************************************* *** Article ** *********************************************************************/ class Article : public Note { private: string text; public : ///Constructor Article(const string i, const string t, Date d_c, Date d_lm, const string txt): Note(i,t,d_c,d_lm), text(txt) {} ///clone virtual Article* clone(); ///Accessor const string& getText() const {return text ;} ///Modify attribute void setText(string& newTxt) {text=newTxt ;} ~Article() {} }; /********************************************************************/ /******************************************************************** *** Task *** *********************************************************************/ enum state {Waiting,Ongoing,Done}; class Tache : public Note { private: string action; unsigned int priority; Date deadline; state status; public : ///Constructor (how to put deadline optional) Tache(const string i, const string t, Date d_c, Date d_lm, const string a, unsigned int p=0, Date dl=Date(1,1,1), state s=Waiting): Note(i,t,d_c,d_lm), action(a), priority(p), deadline(dl), status(s) {} ///clone virtual Tache* clone(); ///Accessor const string& getAction() const {return action ;} const unsigned int& getPriority() const {return priority ;} const Date& getDeadline() const {return deadline ;} const state& getStatus() const {return status ;} ///Modify attribute void setAction(string& newAction) {action=newAction;} void setPriority (unsigned int p) {priority = p ;} void setDeadline (Date newDl) {deadline=newDl ;} //void setSatus() ~Tache() {} }; /*********************************************************************/ /********************************************************************* *** Multimedia *** **********************************************************************/ class Multimedia : public Note { private: string description; string image; public: //Constructor Multimedia (const string i, const string t, Date d_c, Date d_lm, const string& d, const string& f) : Note(i,t,d_c,d_lm), description(d), image(f) {} //Accessor const string& getDescription() const {return description;} const string& getImage() {return image;} //clone virtual pure virtual Multimedia* clone()=0; ~Multimedia(){} }; /*********************************************************************/ /********************************************************************* *** Image *** **********************************************************************/ class Image : public Multimedia{ public: Image(const string i, const string t, Date d_c, Date d_lm, const string& d, const string& f): Multimedia(i,t,d_c,d_lm,d,f) {} virtual Image * clone (); ~Image() {} }; /*********************************************************************/ /********************************************************************* *** Enregistrement Audio *** **********************************************************************/ class Audio : public Multimedia{ public: Audio(const string i, const string t, Date d_c, Date d_lm, const string& d, const string& f): Multimedia(i,t,d_c,d_lm,d,f) {} virtual Audio* clone (); ~Audio() {} }; /*********************************************************************/ /********************************************************************* *** video *** **********************************************************************/ class Video : public Multimedia{ public: Video(const string i, const string t, Date d_c, Date d_lm, const string& d, const string& f): Multimedia(i,t,d_c,d_lm,d,f) {} virtual Video * clone (); ~Video() {} }; /*********************************************************************/ /******************************************************************** *** Couple *** ********************************************************************/ class Couple { private: string label; Note* note1; Note* note2; public: Couple(const string& l,Note* n1, Note* n2) :label(l), note1(n1), note2(n2) {} Note* getNote1() const {return note1;} Note* getNote2() const {return note2;} const string& getLabel() const {return label;} void setLabel(const string & l) {label =l;} }; /*********************************************************************/ /******************************************************************* *** Relation *** *******************************************************************/ class Relation{ private: string title, description; Couple** couples; unsigned int nbCouple, nbMaxCouple; bool oriented; public: Relation(const string & t, const string& d) : title(t), description(d), couples(nullptr), nbCouple(0), nbMaxCouple(0), oriented(false) {} const string& getTitle() const {return title;} const string& getDescription() const {return description;} void addCouple(Note* n1, Note* n2); //add a couple without label void removeCouple(const string&,Note* n1, Note* n2); //looks for a couple with this label & notes void setOriented(){oriented= !oriented;}; ~Relation() {for (unsigned int i=0; i<nbCouple;i++) delete couples[i]; delete [] couples;} }; #endif // NOTES_H_INCLUDED
/* -*-C++-*- */ /* * Copyright 2016 EU Project ASAP 619706. * * 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 <iterator> #include "asap/utils.h" #include "asap/arff.h" #include "asap/dense_vector.h" #include "asap/sparse_vector.h" template<typename VectorTy> typename std::enable_if<asap::is_dense_vector<VectorTy>::value, std::ostream &>::type & operator << ( std::ostream & os, const VectorTy & dv ) { os << '{'; for( int i=0, e=dv.length(); i != e; ++i ) { os << dv[i]; if( i+1 < e ) os << ", "; } os << '}'; return os; } template<typename VectorTy> typename std::enable_if<asap::is_sparse_vector<VectorTy>::value, std::ostream &>::type operator << ( std::ostream & os, const VectorTy & sv ) { os << '{'; for( int i=0, e=sv.nonzeros(); i != e; ++i ) { typename VectorTy::value_type v; typename VectorTy::index_type c; sv.get( i, v, c ); os << c << ": " << v; if( i+1 < e ) os << ", "; } os << '}'; return os; } template<typename vector_type> void test( const char * filename ) { typedef asap::data_set<vector_type> data_set_type; bool is_stored_sparse; data_set_type data = asap::arff_read<data_set_type>( std::string(filename), is_stored_sparse ); std::cout << "Relation: " << data.get_relation() << std::endl; std::cout << "Stored sparsely: " << is_stored_sparse << std::endl; std::cout << "Dimensions: " << data.get_dimensions() << std::endl; for( typename data_set_type::const_index_iterator I=data.index_cbegin(), E=data.index_cend(); I != E; ++I ) std::cout << " '" << *I << '\''; std::cout << std::endl; std::cout << "Points: " << data.get_num_points() << std::endl; for( typename data_set_type::const_vector_iterator I=data.vector_cbegin(), E=data.vector_cend(); I != E; ++I ) std::cout << '\t' << *I << '\n'; std::cout << std::endl; } int main( int argc, char *argv[] ) { if( argc < 2 ) fatal( "usage: t_arff_read input-filename" ); const char * filename = argv[1]; std::cout << "==== Reading ARFF file: dense vectors with ownership\n"; test<asap::dense_vector<size_t, float, false, asap::mm_ownership_type>>( filename ); std::cout << "==== Reading ARFF file: dense vectors without ownership\n"; test<asap::dense_vector<size_t, float, false, asap::mm_no_ownership_type>>( filename ); std::cout << "==== Reading ARFF file: sparse vectors with ownership\n"; test<asap::sparse_vector<size_t, float, false, asap::mm_ownership_type>>( filename ); std::cout << "==== Reading ARFF file: sparse vectors without ownership\n"; test<asap::sparse_vector<size_t, float, false, asap::mm_no_ownership_type>>( filename ); return 0; }
// Copyright (c) 2015 Alireza Kheirkhahan // Copyright (c) 2014 Shuangyang Yang // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(HPX_COMPONENTS_IO_LOCAL_FILE_HPP_AUG_26_2014_1102AM) #define HPX_COMPONENTS_IO_LOCAL_FILE_HPP_AUG_26_2014_1102AM #include <hpx/hpx_fwd.hpp> #include <hpx/include/client.hpp> #include <hpxio/server/local_file.hpp> /////////////////////////////////////////////////////////////////////////////// namespace hpx { namespace io { /////////////////////////////////////////////////////////////////////////// // The \a local_file class is the client side representation of a // concrete \a server#local_file component class local_file : public components::client_base<local_file, server::local_file> { private: typedef components::client_base<local_file, server::local_file> base_type; public: local_file(naming::id_type gid) : base_type(gid) {} local_file(hpx::future<naming::id_type> && gid) : base_type(std::move(gid)) {} lcos::future<void> open(std::string const& name, std::string const& mode) { typedef server::local_file::open_action action_type; return hpx::async<action_type>(this->base_type::get_gid(), name, mode); } void open_sync(std::string const& name, std::string const& mode) { return open(name, mode).get(); } lcos::future<bool> is_open() { typedef server::local_file::is_open_action action_type; return hpx::async<action_type>(this->base_type::get_gid()); } bool is_open_sync() { return is_open().get(); } lcos::future<void> close() { typedef server::local_file::close_action action_type; return hpx::async<action_type>(this->base_type::get_gid()); } void close_sync() { return close().get(); } lcos::future<int> remove_file(std::string const& file_name) { typedef server::local_file::remove_file_action action_type; return hpx::async<action_type>(this->base_type::get_gid(), file_name); } int remove_file_sync(std::string const& file_name) { return remove_file(file_name).get(); } lcos::future<std::vector<char> > read(size_t const& count) { typedef server::local_file::read_action action_type; return hpx::async<action_type>(this->base_type::get_gid(), count); } std::vector<char> read_sync(size_t const count) { return read(count).get(); } lcos::future<std::vector<char> > pread(ssize_t const count, off_t const offset) { typedef server::local_file::pread_action action_type; return hpx::async<action_type>(this->base_type::get_gid(), count, offset); } std::vector<char> pread_sync(size_t const count, off_t const offset) { return pread(count, offset).get(); } lcos::future<ssize_t> write(std::vector<char> const& buf) { typedef server::local_file::write_action action_type; return hpx::async<action_type>(this->base_type::get_gid(), buf); } ssize_t write_sync(std::vector<char> const& buf) { return write(buf).get(); } lcos::future<ssize_t> pwrite(std::vector<char> const& buf, off_t const offset) { typedef server::local_file::pwrite_action action_type; return hpx::async<action_type>(this->base_type::get_gid(), buf, offset); } ssize_t pwrite_sync(std::vector<char> const& buf, off_t const offset) { return pwrite(buf, offset).get(); } lcos::future<int> lseek(off_t const offset, int const whence) { typedef server::local_file::lseek_action action_type; return hpx::async<action_type>(this->base_type::get_gid(), offset, whence); } int lseek_sync(off_t const offset, int const whence) { return lseek(offset, whence).get(); } }; }} // hpx::io #endif
// // Car.cpp // w06_h02_pathfollow2 // // Created by Kris Li on 10/14/16. // // #include "Car.hpp" Car::Car(){ pos.x = ofRandom(0,100); pos.y = ofRandom(ofGetHeight()); maxspeed = 10; maxforce = 10; r = ofRandom(2,4); } void Car::init(ofPoint _start, ofPoint _end){ // ofPoint start = _start; // ofPoint end = _end; vel = ofPoint(ofRandom(-3,3), ofRandom(-3,3)); } void Car::adjust(){ ofPoint a = ofPoint(predictLoc - start); ofPoint b = ofPoint(end - start); b.normalize(); b*(a.dot(b)); ofPoint normalPoint = start + b; float distance = ofDist(predictLoc.x, predictLoc.y, normalPoint.x, normalPoint.y); if(distance > 20){ b.normalize(); b*25; ofPoint target = normalPoint + b; seek(target); } } void Car::seek(ofPoint _target){ ofPoint desired = _target - pos; desired.normalize(); desired*maxspeed; ofPoint steer = desired - vel; acc += steer; } void Car::update(){ pos += vel; vel += acc; vel.limit(maxspeed); } void Car::draw(){ // float theta = vel.angleRad(vel) + PI/2; ofSetColor(50); ofSetLineWidth(2); ofPushMatrix(); ofTranslate(pos.x,pos.y); // ofRotate(theta); ofBeginShape(); ofVertex(0, -r*2); ofVertex(-r, r*2); ofVertex(r, r*2); ofEndShape(); ofPopMatrix(); }
//=========================================================================== //! @file light_point.cpp //! @brife 点光源 //=========================================================================== //--------------------------------------------------------------------------- //! 初期化 //--------------------------------------------------------------------------- bool PointLight::initialize(s32 index) { lightType_ = LightType::PointLight; isActive_ = true; index_ = index; return true; } //--------------------------------------------------------------------------- //! 更新 //--------------------------------------------------------------------------- void PointLight::update() { if(!isActive_) { if(tmpIntensity_ == intensity_) { intensity_ = 0; return; } f = true; } else { if(f) { intensity_ = tmpIntensity_; f = false; } } matWorld_ = Matrix::translate(position_); } //--------------------------------------------------------------------------- //! 描画 //--------------------------------------------------------------------------- void PointLight::render() { if(!isActive_) return; // 行列更新(位置移動のみ) dxLoadMatrixf(matWorld_); // ライト自体の描画 drawSphere(0.2f, color_, 16 * 3); } //--------------------------------------------------------------------------- //! 解放 //--------------------------------------------------------------------------- void PointLight::cleanup() { } //--------------------------------------------------------------------------- //! 減衰パラメーター設定 //--------------------------------------------------------------------------- void PointLight::setAttenuation(const Vector3& attenuation) { attenuation_ = attenuation; } //--------------------------------------------------------------------------- //! 減衰パラメーター取得 //--------------------------------------------------------------------------- Vector3 PointLight::getAttenuation() const { return attenuation_; } //--------------------------------------------------------------------------- //! ImGui //--------------------------------------------------------------------------- void PointLight::showImGuiWindow() { std::string index = std::to_string(index_); std::string s = "PointLight [" + index + "]"; if(ImGui::TreeNode(s.c_str())) { ImGui::Checkbox("Active", &isActive_); auto p = this->ObjectBase::getPosition(); auto c = this->Light::getColor(); auto i = this->Light::getIntensity(); f32 fp[3] = { p.x_, p.y_, p.z_ }; f32 fc[3] = { c.r_, c.g_, c.b_ }; f32 fi = i; ImGui::DragFloat3("Position", fp, 0.05f, -100.0f, 100.0f); ImGui::SliderFloat3("Color", fc, 0.0f, 1.0f); ImGui::SliderFloat("Intensity", &fi, 0.0f, 100.0f); this->ObjectBase::setPosition({ fp[0], fp[1], fp[2] }); this->Light::setColor({ fc[0], fc[1], fc[2], 1.0f }); this->Light::setIntensity(fi); if (ImGui::Button("Remove")) { this->Light::isRemove(true); } ImGui::TreePop(); } }
#include "dbg.h" namespace dbg { int Dbg::loglevel = WARN; std::ostream *Dbg::out = &std::cout; } // namespace dbg
// // Created by Vasili Siachko on 14.12.2019. // #include <iostream> #include "Shape2d.h" Shape2d::~Shape2d() { } double Shape2d::GetPerimeter() { return perimeter; }
#include <windows.h> #include <thread> #include "SocketHelper.h" #include "TCPSocket.h" #include "UDPSocket.h" CTcpSocketHandler::CTcpSocketHandler() { this->SetAutoReConnect(false); this->SetRecvFlag(false); m_clientSocket = INVALID_SOCKET; } CTcpSocketHandler::~CTcpSocketHandler() { } int CTcpSocketHandler::Init(const char *cServerAddr, int nServerPort, bool bAutoReConnect/* = false*/) { this->SetAutoReConnect(bAutoReConnect); this->SetServerAddr(cServerAddr); this->SetServerPort(nServerPort); ClientInit(); SetRecvFlag(true); //启动接收线程 StartRecvDataThread(); return 0; } void CTcpSocketHandler::ClientInit() { ClientSockInitialize(); ClientSetSockOptions(); ClientSetSockAddrsIn(); ClientExecuteConnect(); } void CTcpSocketHandler::ClientSockInitialize() { m_clientReConnectSocket = Tcp_SockInitialize(); } void CTcpSocketHandler::ClientSetSockOptions() { //默认不设置超时 Tcp_SetSockOptions(m_clientSocket, 0, 0, TRUE); } void CTcpSocketHandler::ClientSetSockAddrsIn() { Tcp_SetSockAddrsIn(this->m_strServerAddr.c_str(), this->m_nServerPort, this->m_serverSockAddrIn); } void CTcpSocketHandler::ClientExecuteConnect() { m_clientSocket = Tcp_Connect(m_clientReConnectSocket, this->m_serverSockAddrIn); } int CTcpSocketHandler::Exit() { SetRecvFlag(false); SetAutoReConnect(false); while (this->GetReConnecting()) { Sleep(1); } Tcp_Exit(m_clientSocket); m_clientSocket = INVALID_SOCKET; return 0; } void CTcpSocketHandler::RecvDataFromApp(void * p) { SOCKET clientSocket = INVALID_SOCKET; char cResult[16384] = { 0 }; int nResult = 0; CTcpSocketHandler *pWSH = (CTcpSocketHandler *)p; if (pWSH) { //自动重连尚未开始 pWSH->SetReConnecting(false); while (pWSH->GetRecvFlag()) { clientSocket = pWSH->GetClientSocket(); if (clientSocket != INVALID_SOCKET) { memset(cResult, 0, sizeof(cResult)); nResult = Tcp_Recv(clientSocket, cResult, sizeof(cResult)); if (!pWSH->GetRecvFlag()) { break; } if (nResult > 0) { #ifdef DEBUG printf("Bytes received: %d-%ws\n", nResult, UTF8ToUnicode(cResult).c_str()); #endif // DEBUG printf("Bytes received: %d-%s\n", nResult, cResult); } else //如果nResult <= 0 { //设置当前Socket为无效值 pWSH->SetClientSocket(INVALID_SOCKET); //设置正在进行重连 pWSH->SetReConnecting(true); } } else { //设置正在进行重连 pWSH->SetReConnecting(true); } //判断是否设置了自动重连 if (pWSH->GetAutoReConnect()) { //初始化 pWSH->ClientSockInitialize(); //设置选项 pWSH->ClientSetSockOptions(); //完成自动重连事务 while (pWSH->GetReConnecting() && pWSH->GetAutoReConnect() && pWSH->GetRecvFlag() && pWSH->GetClientSocket() == INVALID_SOCKET) { pWSH->ClientExecuteConnect(); } std::string strCommand = ""; pWSH->RequestCommand(strCommand.c_str(), strCommand.length()); //自动重连已经结束 pWSH->SetReConnecting(false); } else { break; } } } } int CTcpSocketHandler::StartRecvDataThread() { std::thread(&CTcpSocketHandler::RecvDataFromApp, this).detach(); return 0; } int CTcpSocketHandler::RequestCommand(const char * pCommand, int nCommandLength) { return Tcp_Send(m_clientSocket, pCommand, nCommandLength); } ////////////////////////////////////////////////////////////////////////////////////////// SOCKET CUdpSocketHandler::udp_start(int nPort) { SOCKET s = INVALID_SOCKET; Udp_InitSocket(s); Udp_BindSocket(s, nPort); return s; } DWORD WINAPI CUdpSocketHandler::udp_recvdata_thread(void *p) { SOCKET s = (SOCKET)p; SOCKETPACKET sp = { 0 }; while (true) { //等待并接收数据 sp.ssize = sizeof(SOCKETPACKET); Udp_RecvData(s, &sp.si, (unsigned char *)&sp, sp.ssize); if (sp.size) { Udp_RecvData(s, &sp.si, (unsigned char *)&sp.data, sp.size); } } Udp_ExitSocket(s); return 0; } DWORD WINAPI CUdpSocketHandler::udp_senddata_thread(void *p) { SOCKETPACKET * psp = (SOCKETPACKET *)p; psp->ssize = sizeof(SOCKETPACKET); Udp_SendData(psp->s, &psp->si, (unsigned char *)psp, psp->ssize); if (psp->size) { Udp_RecvData(psp->s, &psp->si, (unsigned char *)psp->data, psp->size); } return 0; }
#pragma once /**************************************************************************** * Copyright (c) 2013 GeoMind Srl. www.geomind.it * All rights reserved. * *--------------------------------------------------------------------------- * This software is part of the GeoFlyerPro PROJECT by GeoMind Srl; * it is not allowed to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of software in parts or as a whole, * in source and binary forms, without a written permission of GeoMind Srl. * ****************************************************************************/ #ifndef _CFuffaDelegate_H #define _CFuffaDelegate_H #include "CGeoFlyerDelegate.h" // -------------------------------------------------------------------------- // CFuffaDelegate // -------------------------------------------------------------------------- /** * **/ class CFuffaDelegate : public CGeoFlyerDelegate { public: static void callback( CGeoFlyerDelegate* This, void* inData ) { int gg = 0; } }; #endif // _CFuffaDelegate_H
// Created on: 2018-12-12 // Created by: Olga SURYANINOVA // Copyright (c) 2018 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 _AIS_CameraFrustum_HeaderFile #define _AIS_CameraFrustum_HeaderFile #include <AIS_InteractiveObject.hxx> class Graphic3d_ArrayOfSegments; class Graphic3d_ArrayOfTriangles; //! Presentation for drawing camera frustum. //! Default configuration is built with filling and some transparency. class AIS_CameraFrustum : public AIS_InteractiveObject { DEFINE_STANDARD_RTTIEXT(AIS_CameraFrustum, AIS_InteractiveObject) public: //! Selection modes supported by this object enum SelectionMode { SelectionMode_Edges = 0, //!< detect by edges (default) SelectionMode_Volume = 1, //!< detect by volume }; public: //! Constructs camera frustum with default configuration. Standard_EXPORT AIS_CameraFrustum(); //! Sets camera frustum. Standard_EXPORT void SetCameraFrustum (const Handle(Graphic3d_Camera)& theCamera); //! Setup custom color. Standard_EXPORT virtual void SetColor (const Quantity_Color& theColor) Standard_OVERRIDE; //! Restore default color. Standard_EXPORT virtual void UnsetColor() Standard_OVERRIDE; //! Restore transparency setting. Standard_EXPORT virtual void UnsetTransparency() Standard_OVERRIDE; //! Return true if specified display mode is supported. Standard_EXPORT virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer theMode) const Standard_OVERRIDE; protected: //! Computes presentation of camera frustum. Standard_EXPORT virtual void Compute (const Handle(PrsMgr_PresentationManager)& thePrsMgr, const Handle(Prs3d_Presentation)& thePrs, const Standard_Integer theMode) Standard_OVERRIDE; //! Compute selection. Standard_EXPORT virtual void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection, const Standard_Integer theMode) Standard_OVERRIDE; private: //! Fills triangles primitive array for camera frustum filling. void fillTriangles(); //! Fills polylines primitive array for camera frustum borders. void fillBorders(); protected: NCollection_Array1<Graphic3d_Vec3d> myPoints; //!< Array of points Handle(Graphic3d_ArrayOfTriangles) myTriangles; //!< Triangles for camera frustum filling Handle(Graphic3d_ArrayOfSegments) myBorders; //!< Segments for camera frustum borders }; #endif // _AIS_CameraFrustum_HeaderFile
#include "stdafx.h" #include "PrimListAlgorithm.h" #include <iostream> PrimListAlgorithm::PrimListAlgorithm(Graph2 & graph):PrimMatrixAlgorithm(graph) { } PrimListAlgorithm::~PrimListAlgorithm() { } void PrimListAlgorithm::updatePriorityQueue(int u) { for (int i = 0; i < graph.neighborhoodListTable[u].size(); i++) { int edgeWeight = graph.neighborhoodListTable[u].getWeight(i);//.getVertrex(i); if (edgeWeight != INF )//-1) { if (edgeWeight < key[i])//priorityQueue.isInQueue(i) && {//dodajemy do zbioru potencjalnych sasiadow(if key= oo) lub poprawiamy dostepnosc key!=oo key[i] = edgeWeight; verticeConnected[i] = u; } } else if (edgeWeight < 0) { std::cout << "UJEMNA KAWEDZ ERROR\n"; error = true; return; } } }
1 //这是一个epoll的服务器程序 2 #include <iostream> 3 #include <sys/epoll.h> 4 #include <sys/socket.h> 5 #include <netinet/in.h> 6 #include <unistd.h> 7 #include <string.h> 8 #include <stdlib.h> 9 #include <arpa/inet.h> 10 using namespace std; 11 void ProcessConnect(int listen_fd, int epoll_fd)//连接到来 12 { 13 struct sockaddr_in client_addr; 14 socklen_t len = sizeof(client_addr); 15 int connect_fd = accept(listen_fd, (struct sockaddr*)&client_addr, &len); 16 if(connect_fd < 0) 17 { 18 cout<<"accept error..."; 19 return ; 20 } 21 cout<<"new client connect: "<<inet_ntoa(client_addr.sin_addr)<<" "\ 22 <<ntohs(client_addr.sin_port)<<endl; 23 24 struct epoll_event ev; 25 ev.data.fd = connect_fd; 26 ev.events = EPOLLIN; 27 28 int ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, connect_fd, &ev); 29 if(ret < 0) 30 { 31 cout<<"ctl error..."<<endl; 32 return ; 33 } 34 return ; 35 } 36 void ProcessRequest(int connect_fd, int epoll_fd) 37 { 38 char buf[1024]; 39 ssize_t read_size = read(connect_fd, buf, sizeof(buf)-1); 40 if(read_size < 0) 41 { 42 cout<<"read error...."<<endl; 43 return ; 44 } 45 if(read_size == 0) 46 { 47 close(connect_fd); 48 epoll_ctl(epoll_fd, EPOLL_CTL_DEL, connect_fd, NULL); 49 cout<<"client close..."<<endl; 50 return ; 51 } 52 cout<<"client say: "<<buf<<endl; 53 write(connect_fd, buf, strlen(buf)); 54 } 55 int main(int argc, char* argv[]) 56 { 57 if(argc!=3) 58 cout<<"Use: IP port..."<<endl; 59 60 struct sockaddr_in addr; 61 addr.sin_family = AF_INET; 62 addr.sin_addr.s_addr = inet_addr(argv[1]); 63 addr.sin_port = htons(atoi(argv[2])); 64 65 int listen_fd = socket(AF_INET, SOCK_STREAM, 0); 66 if(listen_fd < 0) 67 { 68 cout<<"socket error..."<<endl; 69 return 1; 70 } 71 if(bind(listen_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) 72 { 73 cout<<"bind error..."<<endl; 74 return 1; 75 } 76 if(listen(listen_fd, 5) < 0) 77 { 78 cout<<"listen error..."<<endl; 79 return 1; 80 } 81 82 //下面就需要用到多路转接之epoll了 83 int epoll_fd = epoll_create(10); 84 //这里是创建了epoll模型,就绪队列,红黑树,回调机制 85 if(epoll_fd < 0) 86 { 87 cout<<"epoll_create error..."<<endl; 88 return 1; 89 } 90 struct epoll_event event; 91 event.events = EPOLLIN;//关注读事件 92 event.data.fd = listen_fd; 93 int ret = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, listen_fd, &event); 94 if(ret < 0) 95 { 96 cout<<"epoll_ctl error...."<<endl; 97 return 1; 98 } 99 100 for(;;) 101 { 102 struct epoll_event events[10]; 103 int size = epoll_wait(epoll_fd, events, sizeof(events)/sizeof(events[0]), 5000); 104 if(size < 0) 105 { 106 cout<<"epoll_wait...."<<endl; 107 continue; 108 } 109 if(size == 0) 110 { 111 cout<<"epoll_wait timeout...."<<endl; 112 continue; 113 } 114 for(int i=0;i<size;i++) 115 { 116 if(!(events[i].events & EPOLLIN)) 117 continue; 118 if(events[i].data.fd == listen_fd) 119 ProcessConnect(listen_fd, epoll_fd);//连接到来 120 else 121 ProcessRequest(events[i].data.fd, epoll_fd); 122 } 123 } 124 return 0; 125 } 126
/* template number * * * */ #include<stdio.h> #include<cstring> #include<iostream> #include<algorithm> // std::sort #include<cstring> #include<vector> #include<set> #include<string> #include<map> #include<queue> #include<stack> #include<deque> #include<unordered_set> #include<unordered_map> using namespace std; class Solution { public: <T1> foo(<T2>& param) { <T1> ans; //process return ans; } }; /************************** run solution **************************/ <T1> _solution_run(<T2>>& param) { Solution template; <T1> ans = template.foo(param); return ans; } // in case of listnode, tree node, we need to use solution_custom #ifdef USE_SOLUTION_CUSTOM string _solution_custom(TestCases &tc) { string a = tc.get<string>(); // get 1 line from test.txt, if the type of a is string ,use tc.get<string>() int b = tc.get<int>(); // get 1 next line from test.txt, if the type of b is int ,use tc.get<int>() ListNode *head = StringIntToCycleListNode(a, b); Solution leetcode_141; return leetcode_141.hasCycle(head); } #endif /************************** get testcase **************************/ #ifdef USE_GET_TEST_CASES_IN_CPP vector<string> _get_test_cases_string() { return {}; } #endif
#include "StdAfx.h" #include "VoxelHash.h" VoxelHash::VoxelHash(void) { m_hashMat = nullptr; } VoxelHash::~VoxelHash(void) { if (m_hashMat) { for (size_t i = 0; i < m_dimSize[0]; i++) { for (size_t j = 0; j < m_dimSize[1]; j++) { delete []m_hashMat[i][j]; } delete []m_hashMat[i]; } } delete []m_hashMat; } void VoxelHash::init(std::vector<Cube> &cubes, Vec3i leftDown, Vec3i rightUp) { // Determine the bounding box of the voxels set m_leftDown = leftDown; m_rightUp = rightUp; m_dimSize = m_rightUp - m_leftDown + Vec3i(1,1,1); m_hashSize = m_dimSize[0]*m_dimSize[1]*m_dimSize[2]; // Use std vector m_hashArray.resize(m_hashSize, INVALID_IDX); for (int i = 0; i < cubes.size(); i++) { int idx = hash(cubes[i].m_pos); // ASSERT(m_hashArray[hash(cubes[i].m_pos)] == INVALID_IDX); m_hashArray[hash(cubes[i].m_pos)] = i; } // use pointer m_hashMat = new int **[m_dimSize[0]]; for (size_t i = 0; i < m_dimSize[0]; i++) { m_hashMat[i] = new int *[m_dimSize[1]]; for (size_t j = 0; j < m_dimSize[1]; j++) { m_hashMat[i][j] = new int[m_dimSize[2]]; std::fill(m_hashMat[i][j], m_hashMat[i][j]+m_dimSize[2], INVALID_IDX); } } for (int i = 0; i < cubes.size(); i++) { setHash(cubes[i].m_pos, i); } } long VoxelHash::hash(int ix, int jy, int kz) { Vec3i ofset = Vec3i(ix, jy, kz) - m_leftDown; ASSERT(ofset[0]>=0 && ofset[1]>=0 && ofset[2]>=0); return ofset[0]*m_dimSize[1]*m_dimSize[2] + ofset[1]*m_dimSize[2] + ofset[2]; } long VoxelHash::hash(Vec3i ptInt) { Vec3i ofset = ptInt - m_leftDown; ASSERT(ofset[0]>=0 && ofset[1]>=0 && ofset[2]>=0); return ofset[0]*m_dimSize[1]*m_dimSize[2] + ofset[1]*m_dimSize[2] + ofset[2]; } int VoxelHash::intersectWithCube(Vec3i ptInt) { if (!validateIntPoint(ptInt)) return INVALID_IDX; //return m_hashArray[hash(ptInt)]; return getHash(ptInt); } BOOL VoxelHash::validateIntPoint(Vec3i pt) { for (int i = 0; i < 3; i++) { if (pt[i] < m_leftDown[i] || pt[i] > m_rightUp[i]) { return FALSE; } } return TRUE; } void VoxelHash::setHash(Vec3i pti, int _value) { Vec3i pt = pti - m_leftDown; m_hashMat[pt[0]][pt[1]][pt[2]] = _value; } int VoxelHash::getHash(Vec3i pti) { Vec3i pt = pti - m_leftDown; return m_hashMat[pt[0]][pt[1]][pt[2]]; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 2003-2007 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // shuais // #include "core/pch.h" #include "adjunct/quick/managers/RedirectionManager.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "adjunct/quick/managers/SpeedDialManager.h" #include "adjunct/quick/Application.h" #include "adjunct/desktop_util/resources/ResourceDefines.h" #include "modules/url/url_man.h" ////////////////////////////////////////////////////////////////////////////////////////////////////////////// RedirectUrl::RedirectUrl(OpStringC unique_id) { OpStatus::Ignore(id.Set(unique_id)); g_main_message_handler->SetCallBack(this, MSG_URL_LOADING_FAILED, 0); g_main_message_handler->SetCallBack(this, MSG_HEADER_LOADED, 0); } RedirectUrl::~RedirectUrl() { g_main_message_handler->RemoveCallBack(this, MSG_URL_LOADING_FAILED); g_main_message_handler->RemoveCallBack(this, MSG_HEADER_LOADED); } void RedirectUrl::ResolveUrl(OpStringC url_str) { if (!url.IsEmpty()) url.Unload(); url = urlManager->GetURL(url_str, NULL, TRUE); if (url.IsEmpty()) return; URL ref_url; URL_LoadPolicy policy; url.SetHTTP_Method(HTTP_METHOD_HEAD); url.Load(g_main_message_handler, ref_url); } void RedirectUrl::OnResolved() { moved_to_url.Set(url.GetAttribute(URL::KHTTP_Location, TRUE)); // Resolve recursively if (moved_to_url.HasContent() && RedirectionManager::GetInstance()->IsRedirectUrl(moved_to_url)) ResolveUrl(moved_to_url); else OnComplete(); } void RedirectUrl::OnComplete() { if (moved_to_url.HasContent()) { if (g_hotlist_manager) { BookmarkModel* model = g_hotlist_manager->GetBookmarksModel(); if (model) { HotlistModelItem* item = model->GetByUniqueGUID(id); if (item && item->GetPartnerID().HasContent()) { OP_ASSERT(!item->GetHasDisplayUrl()); item->SetDisplayUrl(moved_to_url); } } } if (g_speeddial_manager) { DesktopSpeedDial* sd = g_speeddial_manager->GetSpeedDialByID(id); if (sd && sd->GetPartnerID().HasContent()) { OP_ASSERT(!sd->HasDisplayURL()); sd->SetDisplayURL(moved_to_url); } } } if (RedirectionManager::GetInstance()) RedirectionManager::GetInstance()->OnResolved(this); } void RedirectUrl::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { if ((URL_ID)par1 == url.Id()) { switch(msg) { case MSG_HEADER_LOADED: OnResolved(); break; case MSG_URL_LOADING_FAILED: OnComplete(); break; default: OP_ASSERT(false); } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// RedirectionManager::RedirectionManager() { } RedirectionManager::~RedirectionManager() { g_speeddial_manager->RemoveListener(*this); g_desktop_bookmark_manager->RemoveBookmarkListener(this); g_desktop_bookmark_manager->GetBookmarkModel()->RemoveModelListener(this); } OP_STATUS RedirectionManager::Init() { g_speeddial_manager->AddListener(*this); g_desktop_bookmark_manager->AddBookmarkListener(this); return OpStatus::OK; } void RedirectionManager::ResolveRedirectUrl(OpStringC unique_id, OpStringC url) { if (!IsRedirectUrl(url)) return; for (UINT i=0; i<m_urls.GetCount(); i++) { if (m_urls.Get(i)->id.Compare(unique_id) == 0) { m_urls.Get(i)->ResolveUrl(url); return; } } RedirectUrl* new_url = OP_NEW(RedirectUrl, (unique_id)); if (new_url) { OpStatus::Ignore(m_urls.Add(new_url)); new_url->ResolveUrl(url); } } void RedirectionManager::OnResolved(RedirectUrl* url) { m_urls.RemoveByItem(url); OP_DELETE(url); } BOOL RedirectionManager::IsRedirectUrl(OpStringC url) { return url.Find("://redir.opera.com") != KNotFound || url.Find("://redir.operachina.com") != KNotFound; } void RedirectionManager::OnBookmarkModelLoaded() { if (g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRST_NEW_BUILD_NUMBER || g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRST || g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRSTCLEAN || g_run_type->m_added_custom_folder || g_region_info->m_changed) { OpINT32Vector& default_bookmarks = g_desktop_bookmark_manager->GetDefaultBookmarks(); for (UINT32 i=0; i<default_bookmarks.GetCount(); i++) { HotlistModelItem* item = g_hotlist_manager->GetItemByID(default_bookmarks.Get(i)); if (item && item->GetPartnerID().HasContent()) { // On upgrade display url is reset to what is in the new file, // so this is TRUE if there was no display url set there if (!item->GetHasDisplayUrl()) { // What the redirect url points to may have changed after an upgrade ResolveRedirectUrl(item->GetUniqueGUID(), item->GetUrl()); } } } } g_desktop_bookmark_manager->GetBookmarkModel()->AddModelListener(this); } void RedirectionManager::OnHotlistItemAdded(HotlistModelItem* item) { if (item->GetPartnerID().HasContent() && !item->GetHasDisplayUrl()) ResolveRedirectUrl(item->GetUniqueGUID(), item->GetUrl()); } void RedirectionManager::OnSpeedDialAdded(const DesktopSpeedDial& entry) { if (entry.GetPartnerID().HasContent() && !entry.HasDisplayURL()) ResolveRedirectUrl(entry.GetUniqueID(), entry.GetURL()); } void RedirectionManager::OnSpeedDialsLoaded() { if (g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRST_NEW_BUILD_NUMBER || g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRST || g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRSTCLEAN || g_run_type->m_added_custom_folder || g_region_info->m_changed) { UINT count = g_speeddial_manager->GetTotalCount(); for (UINT i=0; i<count; i++) { DesktopSpeedDial* sd = g_speeddial_manager->GetSpeedDial(i); if (sd->GetPartnerID().HasContent()) { // What the redirect url points to may have changed after an upgrade sd->SetDisplayURL(NULL); ResolveRedirectUrl(sd->GetUniqueID(), sd->GetURL()); } } } }
/* Copyright (c) 2015, Vlad Mesco 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "common.h" #include "document_display.h" #include "document.h" #include <algorithm> #include <numeric> #include <assert.h> extern bool TryParseNote(const char*, Note*); cell_t TitleCell::GetRenderThing() { cell_t ret; ret.x = Location().x; ret.y = Location().y; ret.type = cell_t::BLOCK; ret.color = color_t::CRIMSON; ret.text = (char*)malloc(sizeof(char) * COLUMNS); ret.ntext = COLUMNS; for(size_t i = 0; i < COLUMNS; ++i) { if(i < Text().size()) ret.text[i] = Text()[i]; else ret.text[i] = ' '; } return ret; } cell_t StaffName::GetRenderThing() { cell_t ret; ret.x = Location().x; ret.y = Location().y; ret.type = cell_t::BLOCK; ret.color = color_t::WHITE; ret.text = (char*)malloc(sizeof(char) * 8); ret.ntext = 8; for(size_t i = 0; i < 8; ++i) { if(i < Text().size()) ret.text[i] = Text()[i]; else ret.text[i] = ' '; } return ret; } void StaffName::UserInput(std::string s) { doc_.staves_[staffIdx_].name_ = s; } cell_t StaffType::GetRenderThing() { cell_t ret; ret.x = Location().x; ret.y = Location().y; ret.type = cell_t::BLOCK; ret.color = color_t::CRIMSON; ret.text = (char*)malloc(sizeof(char) * 1); ret.ntext = 1; ret.text[0] = Text()[0]; return ret; } void StaffType::UserInput(std::string s) { if(s.empty()) return; switch(s[0]) { case 'N': case 'P': doc_.staves_[staffIdx_].type_ = s[0]; break; } } cell_t StaffScale::GetRenderThing() { cell_t ret; ret.x = Location().x; ret.y = Location().y; ret.type = cell_t::BLOCK; ret.color = color_t::WHITE; ret.text = (char*)malloc(sizeof(char) * 3); ret.ntext = 3; size_t scale = doc_.staves_[staffIdx_].scale_; if(scale < 1000) { ret.text[0] = ((scale / 100) % 10) + '0'; ret.text[1] = ((scale / 10) % 10) + '0'; ret.text[2] = ((scale / 1) % 10) + '0'; } else { ret.text[0] = 'B'; ret.text[1] = 'I'; ret.text[2] = 'G'; } return ret; } void StaffScale::UserInput(std::string s) { if(s.empty()) return; int i = atoi(s.c_str()); if(i < 0) return; doc_.staves_[staffIdx_].scale_ = i; } cell_t StaffInterpolation::GetRenderThing() { cell_t ret; ret.x = Location().x; ret.y = Location().y; ret.type = cell_t::BLOCK; ret.color = color_t::CRIMSON; ret.text = (char*)malloc(sizeof(char) * 1); ret.ntext = 1; ret.text[0] = Text()[0]; return ret; } void StaffInterpolation::UserInput(std::string s) { if(s.empty()) return; switch(s[0]) { case 'C': case 'T': case 'L': doc_.staves_[staffIdx_].interpolation_ = s[0]; break; } } void NoteCell::UserInput(std::string text) { if(noteIdx_ < 0) return; Note& c = doc_.staves_[staffIdx_].notes_[noteIdx_]; if(doc_.staves_[staffIdx_].type_ == 'N') { (void) TryParseNote(text.c_str(), &c); } else { std::stringstream s; s << text; std::string s1, s2; s >> s1 >> s2; if(s1.empty() || s2.empty()) return; int scale = atoi(s1.c_str()); if(scale <= 0) return; int goodNum = atoi(s2.c_str()); if(abs(goodNum) > 999) return; char snum[4]; sprintf(snum, "%03u", abs(goodNum)); snum[3] = '\0'; if(goodNum >= 0) c.name_ = snum[0]; else c.name_ = snum[0] - '0' + 'A'; c.height_ = snum[1]; c.sharp_ = snum[2]; c.scale_ = scale; } doc_.UpdateCache(); } cell_t NoteCell::GetRenderThing() { cell_t ret; ret.x = Location().x; ret.y = Location().y; ret.text = (char*)malloc(sizeof(char) * 5); ret.ntext = 5; if(doc_.staves_[staffIdx_].type_ == 'N') { ret.type = cell_t::NOTE; if(noteIdx_ >= 0) { ret.text[3] = (noteIdx_ % 2) ? '\0' : 'T'; Note& n = doc_.staves_[staffIdx_].notes_[noteIdx_]; if(doc_.staves_[staffIdx_].notes_[noteIdx_].name_ == '-') { ret.color = color_t::GRAY; ret.text[4] = (first_) ? 'T' : '\0'; ret.text[0] = n.name_; ret.text[1] = '0'; ret.text[2] = ' '; } else { ret.color = (noteIdx_ % 2) ? color_t::YELLOW : color_t::WHITE; if(first_) { ret.text[4] = 'T'; } else { ret.text[4] = '\0'; } ret.text[0] = n.name_; ret.text[1] = n.height_; ret.text[2] = n.sharp_; } if(doc_.IsNoteSelected(this)) { ret.color = color_t::BLUE; } } else { ret.color = color_t::BLACK; ret.text[0] = ret.text[1] = ret.text[2] = ' '; ret.text[4] = '\0'; } } else if(doc_.staves_[staffIdx_].type_ == 'P') { ret.type = cell_t::SAMPLE; if(noteIdx_ >= 0) { ret.color = (noteIdx_ % 2) ? color_t::SEA : color_t::SKY; ret.text[3] = '\0'; if(doc_.IsNoteSelected(this)) { ret.color = color_t::BLUE; } if(first_) { Note& n = doc_.staves_[staffIdx_].notes_[noteIdx_]; ret.text[0] = n.name_; ret.text[1] = n.height_; ret.text[2] = n.sharp_; } else { ret.text[0] = ' '; ret.text[1] = ' '; ret.text[2] = ' '; } } else { ret.color = color_t::BLACK; ret.text[0] = ret.text[1] = ret.text[2] = ' '; ret.text[4] = '\0'; } } return ret; }
// PIN SETUP CODE // pwm pins: 4, 14, 15 #define motorPin1 4 #define motorPin2 14 #define motorPin3 15 #define directionPin1 1 #define directionPin2 2 #define directionPin3 3 // encoder pins: 5, 6, 7, 8 #define encoderPin1A 5 #define encoderPin1B 6 #define encoderPin2A 7 #define encoderPin2B 8 // analog pins: 11 to 21 #define analogPin1 19 #define analogPin2 20 #define analogPin3 21 #define ledPin 11 //####################################################################################################################// //###################################################### SERVOS ######################################################// //####################################################################################################################// #include <PWMServo.h> // docs: https://www.pjrc.com/teensy/td_libs_Servo.html PWMServo servo1; PWMServo servo2; PWMServo servo3; void servo_setup() { servo1.attach(motorPin1); servo2.attach(motorPin2); servo3.attach(motorPin3); digitalWrite(3, HIGH); } /** converts a duty cycle into an "angle" that servo library wants scales the value from [-100, 100] to [0, 180] */ uint16_t servo_convertForLibrary(const int16_t dc) { return (dc + 100) * 9 / 10; } void servo_write(const int8_t duty1, const int8_t duty2, const int8_t duty3) { servo1.write(servo_convertForLibrary(duty1)); servo2.write(servo_convertForLibrary(duty2)); servo3.write(servo_convertForLibrary(duty3)); } //####################################################################################################################// //############################################## DIRECTION + DUTY CYCLE ##############################################// //####################################################################################################################// #include <TimerOne.h> void ddc_setup() { Timer1.initialize(20); // 50kHz Timer1.pwm(motorPin1, 0); Timer1.pwm(motorPin2, 0); Timer1.pwm(motorPin3, 0); pinMode(directionPin1, OUTPUT); pinMode(directionPin2, OUTPUT); pinMode(directionPin3, OUTPUT); } /** converts a duty cycle into an "angle" that servo library wants scales the value from [-100, 100] to [0, 1023] */ uint16_t ddc_convertForLibrary(const int16_t dc) { return abs(dc) * 93 / 100 * 11; // avoid overflow, 93 * 11 = 1023 } void ddc_write(const int8_t duty1, const int8_t duty2, const int8_t duty3) { digitalWrite(directionPin1, duty1 < 0 ? LOW : HIGH); digitalWrite(directionPin2, duty2 < 0 ? LOW : HIGH); digitalWrite(directionPin3, duty3 < 0 ? LOW : HIGH); Timer1.setPwmDuty(motorPin1, ddc_convertForLibrary(duty1)); Timer1.setPwmDuty(motorPin2, ddc_convertForLibrary(duty2)); Timer1.setPwmDuty(motorPin3, ddc_convertForLibrary(duty3)); } //####################################################################################################################// //##################################################### ENCODERS #####################################################// //####################################################################################################################// //#define ENCODER_OPTIMIZE_INTERRUPTS // may conflict with other libraries using `attachInterrupt()` //#include <Encoder.h> // docs: https://www.pjrc.com/teensy/td_libs_Encoder.html#optimize //Encoder encoder1(encoderPin1A, encoderPin1B); //Encoder encoder2(encoderPin2A, encoderPin2B); //####################################################################################################################// //######################################################## USB #######################################################// //####################################################################################################################// #define TX_SIZE 34 #define RX_SIZE 8 #define IO_TIMEOUT 100 uint8_t sendBuffer[TX_SIZE] = {0}; uint8_t recieveBuffer[RX_SIZE] = {0}; // every integer primitive in Java is signed // so we must use signed numbers here void usb_write( const int32_t encoder1_ticks = 0, const int32_t encoder1_period = 0, const int32_t encoder2_ticks = 0, const int32_t encoder2_period = 0, const int16_t analog1 = 0, const int16_t analog2 = 0, const int16_t analog3 = 0, const int8_t servo1 = 0, const int8_t servo2 = 0, const int8_t servo3 = 0, const int8_t mode = 0, const int64_t timeStamp = 0 ) { memcpy(sendBuffer + 0, &encoder1_ticks, 4); memcpy(sendBuffer + 4, &encoder1_period, 4); memcpy(sendBuffer + 8, &encoder2_ticks, 4); memcpy(sendBuffer + 12, &encoder2_period, 4); memcpy(sendBuffer + 16, &analog1, 2); memcpy(sendBuffer + 18, &analog2, 2); memcpy(sendBuffer + 20, &analog3, 2); memcpy(sendBuffer + 22, &servo1, 1); memcpy(sendBuffer + 23, &servo2, 1); memcpy(sendBuffer + 24, &servo3, 1); memcpy(sendBuffer + 25, &mode, 1); memcpy(sendBuffer + 26, &timeStamp, 8); Serial.write(sendBuffer, TX_SIZE); Serial.send_now(); } void usb_read() { const uint64_t loopStart = millis(); while (Serial.available() < RX_SIZE) { if (millis() - loopStart > IO_TIMEOUT) { digitalWrite(ledPin, HIGH); memset(recieveBuffer, 0, RX_SIZE); return; } } digitalWrite(ledPin, LOW); for (int i = 0; i < RX_SIZE; i++) { recieveBuffer[i] = Serial.read(); } while (Serial.read() != -1); } int8_t usb_getOutput(const uint8_t motorNumber) { return recieveBuffer[motorNumber]; } int8_t usb_getMode() { return recieveBuffer[0]; } //####################################################################################################################// //####################################################### MAIN #######################################################// //####################################################################################################################// #define SERVO_MODE 1 #define DDC_MODE 2 uint8_t mode = 0; #define ledPin 11 void setup() { // called by arduino main pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); Serial.begin(115200); while (!Serial.dtr()); do { usb_read(); mode = usb_getMode(); } while(mode == 0); if (mode == DDC_MODE) ddc_setup(); else servo_setup(); encoder_setup(); digitalWrite(ledPin, LOW); } void loop() { // called by arduino main const uint64_t loopStart = micros(); usb_read(); const int8_t m1 = usb_getOutput(1); const int8_t m2 = usb_getOutput(2); const int8_t m3 = usb_getOutput(3); if (mode == DDC_MODE) ddc_write(m1, m2, m3); else servo_write(m1, m2, m3); const uint64_t timeStamp = micros(); usb_write( encoder1_getTicks(),//encoder1.read(), encoder1_getPeriod(), encoder2_getTicks(),//encoder2.read(), encoder2_getPeriod(), analogRead(analogPin1), // uint10_t casted to int16_t analogRead(analogPin2), analogRead(analogPin3), m1, m2, m3, mode, timeStamp // uint64_t casted to int64_t ); while(micros() - loopStart < 5000); }
/*You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.Return the sum of all the unique elements of nums.*/ class Solution { public: int sumOfUnique(vector<int>& nums) { int f[100]={0}; for(int i=0;i<nums.size();i++) { f[nums[i]-1]++; } int s=0; for(int i=0;i<100;i++) { if(f[i]==1) s+=i+1; } return s; } };
#pragma once #include "Cell.h" class map { public: map(); };
#include <iostream> #include <cryptopp/hmac.h> #include <cryptopp/sha.h> #include "bip32.h" unsigned char * hd_master( unsigned char * y, const unsigned char * x ) { try { CryptoPP::HMAC< CryptoPP::SHA512 > hmc( reinterpret_cast<const byte*>( "Bitcoin seed" ), 12); hmc . Update( x, 512 ); hmc . Final( y ); } catch ( const CryptoPP::Exception & e ) { std::cerr << e.what() << std::endl; } return y; } unsigned char * hd_level( unsigned char * y, const unsigned char * x, const unsigned int i ) { try { //CryptoPP::ECDSA< CryptoPP::ECP, CryptoPP::SHA256 >::PrivateKey d; CryptoPP::HMAC< CryptoPP::SHA512 > hmc( reinterpret_cast<const byte*>( "Bitcoin seed" ), 12); //d . Initialize( CryptoPP::ASN1::secp256k1() hmc . Update( x, 512 ); hmc . Final( y ); } catch ( const CryptoPP::Exception & e ) { std::cerr << e.what() << std::endl; } return y; }
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include "cmCursesLabelWidget.h" #include "cmCursesWidget.h" cmCursesLabelWidget::cmCursesLabelWidget(int width, int height, int left, int top, const std::string& name) : cmCursesWidget(width, height, left, top) { field_opts_off(this->Field, O_EDIT); field_opts_off(this->Field, O_ACTIVE); field_opts_off(this->Field, O_STATIC); this->SetValue(name); } cmCursesLabelWidget::~cmCursesLabelWidget() = default; bool cmCursesLabelWidget::HandleInput(int& /*key*/, cmCursesMainForm* /*fm*/, WINDOW* /*w*/) { // Static text. No input is handled here. return false; }
#ifndef NMOS_CLOCK_NAME_H #define NMOS_CLOCK_NAME_H #include "cpprest/basic_utils.h" #include "nmos/string_enum.h" namespace nmos { // Clock name // See https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/APIs/schemas/clock_internal.json // and https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/APIs/schemas/clock_ptp.json // and https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/APIs/schemas/source_core.json DEFINE_STRING_ENUM(clock_name) namespace clock_names { const clock_name clk0{ U("clk0") }; inline const clock_name clk(unsigned int n) { return clock_name{ U("clk") + utility::ostringstreamed(n) }; } } } #endif
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <quic/api/QuicTransportBase.h> #include <quic/api/QuicTransportFunctions.h> #include <quic/codec/ConnectionIdAlgo.h> #include <quic/common/TransportKnobs.h> #include <quic/congestion_control/CongestionControllerFactory.h> #include <quic/server/handshake/ServerTransportParametersExtension.h> #include <quic/server/state/ServerConnectionIdRejector.h> #include <quic/server/state/ServerStateMachine.h> #include <quic/state/QuicTransportStatsCallback.h> #include <folly/io/async/AsyncTransportCertificate.h> #include <fizz/record/Types.h> namespace quic { struct CipherInfo { TrafficKey trafficKey; fizz::CipherSuite cipherSuite; Buf packetProtectionKey; }; class QuicServerTransport : public QuicTransportBase, public ServerHandshake::HandshakeCallback, public std::enable_shared_from_this<QuicServerTransport> { public: using Ptr = std::shared_ptr<QuicServerTransport>; using Ref = const QuicServerTransport&; using SourceIdentity = std::pair<folly::SocketAddress, ConnectionId>; class RoutingCallback { public: virtual ~RoutingCallback() = default; // Called when a connection id is available virtual void onConnectionIdAvailable( Ptr transport, ConnectionId id) noexcept = 0; virtual void onConnectionIdRetired( Ref transport, ConnectionId id) noexcept = 0; // Called when a connection id is bound and ip address should not // be used any more for routing. virtual void onConnectionIdBound(Ptr transport) noexcept = 0; // Called when the connection is finished and needs to be Unbound. virtual void onConnectionUnbound( QuicServerTransport* transport, const SourceIdentity& address, const std::vector<ConnectionIdData>& connectionIdData) noexcept = 0; }; class HandshakeFinishedCallback { public: virtual ~HandshakeFinishedCallback() = default; virtual void onHandshakeFinished() noexcept = 0; virtual void onHandshakeUnfinished() noexcept = 0; }; static QuicServerTransport::Ptr make( folly::EventBase* evb, std::unique_ptr<QuicAsyncUDPSocketType> sock, ConnectionSetupCallback* connSetupCb, ConnectionCallback* connStreamsCb, std::shared_ptr<const fizz::server::FizzServerContext> ctx, bool useConnectionEndWithErrorCallback = false); QuicServerTransport( folly::EventBase* evb, std::unique_ptr<QuicAsyncUDPSocketType> sock, ConnectionSetupCallback* connSetupCb, ConnectionCallback* connStreamsCb, std::shared_ptr<const fizz::server::FizzServerContext> ctx, std::unique_ptr<CryptoFactory> cryptoFactory = nullptr, bool useConnectionEndWithErrorCallback = false); // Testing only API: QuicServerTransport( folly::EventBase* evb, std::unique_ptr<QuicAsyncUDPSocketType> sock, ConnectionSetupCallback* connSetupCb, ConnectionCallback* connStreamsCb, std::shared_ptr<const fizz::server::FizzServerContext> ctx, std::unique_ptr<CryptoFactory> cryptoFactory, PacketNum startingPacketNum); ~QuicServerTransport() override; virtual void setRoutingCallback(RoutingCallback* callback) noexcept; virtual void setHandshakeFinishedCallback( HandshakeFinishedCallback* callback) noexcept; virtual void setOriginalPeerAddress(const folly::SocketAddress& addr); virtual void setServerConnectionIdParams( ServerConnectionIdParams params) noexcept; /** * Set callback for various transport stats (such as packet received, dropped * etc). */ virtual void setTransportStatsCallback( QuicTransportStatsCallback* statsCallback) noexcept; /** * Set ConnectionIdAlgo implementation to encode and decode ConnectionId with * various info, such as routing related info. */ virtual void setConnectionIdAlgo(ConnectionIdAlgo* connIdAlgo) noexcept; void setServerConnectionIdRejector( ServerConnectionIdRejector* connIdRejector) noexcept; virtual void setClientConnectionId(const ConnectionId& clientConnectionId); void setClientChosenDestConnectionId(const ConnectionId& serverCid); void verifiedClientAddress(); // From QuicTransportBase void onReadData( const folly::SocketAddress& peer, NetworkDataSingle&& networkData) override; void writeData() override; void closeTransport() override; void unbindConnection() override; bool hasWriteCipher() const override; std::shared_ptr<QuicTransportBase> sharedGuard() override; QuicConnectionStats getConnectionsStats() const override; const fizz::server::FizzServerContext& getCtx() { return *ctx_; } virtual void accept(); virtual void setBufAccessor(BufAccessor* bufAccessor); const std::shared_ptr<const folly::AsyncTransportCertificate> getPeerCertificate() const override; virtual CipherInfo getOneRttCipherInfo() const; /* Log a collection of statistics that are meant to be sampled consistently * over time, rather than driven by transport events. */ void logTimeBasedStats() const; protected: // From QuicSocket SocketObserverContainer* getSocketObserverContainer() const override { return wrappedObserverContainer_.getPtr(); } // From ServerHandshake::HandshakeCallback virtual void onCryptoEventAvailable() noexcept override; void onTransportKnobs(Buf knobBlob) override; void handleTransportKnobParams(const TransportKnobParams& params); // Made it protected for testing purpose void registerTransportKnobParamHandler( uint64_t paramId, std::function<void(QuicServerTransport*, TransportKnobParam::Val)>&& handler); private: void processPendingData(bool async); void maybeNotifyTransportReady(); void maybeNotifyConnectionIdRetired(); void maybeNotifyConnectionIdBound(); void maybeWriteNewSessionTicket(); void maybeIssueConnectionIds(); void maybeNotifyHandshakeFinished(); bool hasReadCipher() const; void registerAllTransportKnobParamHandlers(); private: RoutingCallback* routingCb_{nullptr}; HandshakeFinishedCallback* handshakeFinishedCb_{nullptr}; std::shared_ptr<const fizz::server::FizzServerContext> ctx_; bool notifiedRouting_{false}; bool notifiedConnIdBound_{false}; bool newSessionTicketWritten_{false}; QuicServerConnectionState* serverConn_; std::unordered_map< uint64_t, std::function<void(QuicServerTransport*, TransportKnobParam::Val)>> transportKnobParamHandlers_; // Container of observers for the socket / transport. // // This member MUST be last in the list of members to ensure it is destroyed // first, before any other members are destroyed. This ensures that observers // can inspect any socket / transport state available through public methods // when destruction of the transport begins. const WrappedSocketObserverContainer wrappedObserverContainer_; }; } // namespace quic
// Project #include "Example.h" #include "Settings.h" Example::Example() { Q_UNUSED(APP_NAME); } Example::~Example() { }
#include "activity_mgr_merge.hpp" #include "prepare.hpp" #include "utils/log.hpp" #include "utils/proto_utils.hpp" #include "utils/assert.hpp" namespace nora { void activity_mgr_merger::start() { ASSERT(st_); st_->async_call( [this] { ILOG << "merge activity begin"; load_mgr(); }); } void activity_mgr_merger::load_mgr() { ASSERT(st_->check_in_thread()); auto from_db_msg = make_shared<db::message>("get_activity_mgr", db::message::req_type::rt_select, [this] (const auto& msg) { ASSERT(msg->results().size() == 1); from_activity_mgr_ = make_unique<pd::activity_mgr>(); from_activity_mgr_->ParseFromString(boost::any_cast<string>(msg->results()[0][0])); if (to_activity_mgr_) { this->merge_mgr(); } }); from_db_->push_message(from_db_msg, st_); auto to_db_msg = make_shared<db::message>("get_activity_mgr", db::message::req_type::rt_select, [this] (const auto& msg) { ASSERT(msg->results().size() == 1); to_activity_mgr_ = make_unique<pd::activity_mgr>(); to_activity_mgr_->ParseFromString(boost::any_cast<string>(msg->results()[0][0])); if (from_activity_mgr_) { this->merge_mgr(); } }); to_db_->push_message(to_db_msg, st_); } void activity_mgr_merger::merge_mgr() { ASSERT(st_->check_in_thread()); if (to_activity_mgr_->prize_wheel() != from_activity_mgr_->prize_wheel()) { ELOG << "activity mgr prize wheel mismatch:\n" << "from:\n" << from_activity_mgr_->prize_wheel().DebugString() << "\nto:\n" << to_activity_mgr_->prize_wheel().DebugString(); exit(1); } to_activity_mgr_->mutable_fund()->set_value(to_activity_mgr_->fund().value() + from_activity_mgr_->fund().value()); auto db_msg = make_shared<db::message>("save_activity_mgr", db::message::req_type::rt_update, [this] (const auto& msg) { this->on_db_save_activity_mgr_done(msg); }); string str; to_activity_mgr_->SerializeToString(&str); db_msg->push_param(str); to_db_->push_message(db_msg, st_); } void activity_mgr_merger::on_db_save_activity_mgr_done(const shared_ptr<db::message>& msg) { ASSERT(st_->check_in_thread()); if (msg->results().empty()) { ILOG << "merge activity_fund done"; if (done_cb_) { done_cb_(); } return; } } }
// Copyright (c) 2013 Nick Porcino, All rights reserved. // License is MIT: http://opensource.org/licenses/MIT #include "LandruVM/MachineCache.h" #include "LandruVM/Exemplar.h" #include "LandruVM/Fiber.h" #include "LandruVM/VarObj.h" #include <string.h> #define MAX_STACK_DEPTH 32 #define MAX_VARS 32 namespace Landru { MachineCacheEntry::MachineCacheEntry(std::unique_ptr<Exemplar> e) : exemplar(std::move(e)) { } MachineCacheEntry::MachineCacheEntry(const MachineCacheEntry& mc) : exemplar(mc.exemplar) {} MachineCache::MachineCache() {} MachineCache::~MachineCache() {} std::shared_ptr<MachineCacheEntry> MachineCache::findExemplar(const char* name) { for (auto i = cache.begin(); i != cache.end(); ++i) { if (!strcmp((*i).get()->exemplar->nameStr, name)) return *i; } return 0; } void MachineCache::add(VarObjFactory* factory, std::shared_ptr<Exemplar> e1) { // Supplied exemplar might be used in many different machine contexts, // but MachineCache refers to a single context; it's fine to JIT a copy // of the exemplar per context, but not across machine contexts - // different engines might instantiate different libraries causing // different resolutions of function pointers. // std::unique_ptr<Exemplar> e(new Exemplar()); e->copy(e1.get()); std::shared_ptr<MachineCacheEntry> mce = std::make_shared<MachineCacheEntry>(std::move(e)); if (mce->exemplar->sharedVarCount > 0) { for (int i = 0; i < e->sharedVarCount; ++i) { const char* varType = &mce->exemplar->stringData[e->stringArray[mce->exemplar->sharedVarTypeIndex[i]]]; const char* varName = &mce->exemplar->stringData[e->stringArray[mce->exemplar->sharedVarNameIndex[i]]]; std::unique_ptr<VarObj> v = factory->make(varType, varName); if (!v) RaiseError(0, "Unknown variable type", varType); mce->sharedVars->add(std::shared_ptr<VarObj>(std::move(v))); } } cache.push_back(std::move(mce)); } std::shared_ptr<Fiber> MachineCache::createFiber(VarObjFactory* factory, char const* name) { std::shared_ptr<MachineCacheEntry> mce = findExemplar(name); if (mce) { std::shared_ptr<Fiber> f = std::make_shared<Fiber>("fiber"); f->Create(factory, MAX_STACK_DEPTH, MAX_VARS, mce); return f; } return 0; } } // Landru
#include "Game.h" #include "MenuState.h" #include "PlayState.h" #include "HexaState.h" #include "GameObject.h" #include "LoaderParams.h" #include "SDLGameObject.h" #include "TextureManager.h" #include "MenuButton.h" #include "Block.h" const std::string MenuState::s_menuID = "MENU"; void MenuState::update() { for (int i = 0; i < objectMaxCount; i++) { m_gameObjects[i]->update(); } } void MenuState::render() { for (int i = 0; i < objectMaxCount; i++) { m_gameObjects[i]->draw(); } } bool MenuState::onEnter() { if (!TheTextureManager::Instance()->load("assets/button.png", "playbutton", TheGame::Instance()->get_Renderer())) { return false; } if (!TheTextureManager::Instance()->load("assets/exit.png", "exitbutton", TheGame::Instance()->get_Renderer())) { return false; } GameObject* button1 = new MenuButton(s_menuToPlay); button1->load( new LoaderParams( 312, 180, 400, 100, "playbutton" ) ); GameObject* button2 = new MenuButton(s_exitFromMenu); button2->load( new LoaderParams( 312, 480, 400, 100, "exitbutton" ) ); m_gameObjects.push_back(button1); m_gameObjects.push_back(button2); objectMaxCount = m_gameObjects.size(); return true; } bool MenuState::onExit() { TheTextureManager::Instance()->clearFromTextureMap( "playbutton" ); TheTextureManager::Instance()->clearFromTextureMap( "exitbutton" ); for (int i = m_gameObjects.size()-1 ; i >= 0; i--) { m_gameObjects[i]->clean(); m_gameObjects.pop_back(); } m_gameObjects.clear(); return true; } void MenuState::s_menuToPlay() { TheGame::Instance()->getStateMachine()->changeState(new HexaState()); } void MenuState::s_exitFromMenu() { TheGame::Instance()->setRunning(false); } void MenuState::reset() { m_gameObjects.resize(0); }
#include<bits/stdc++.h> using namespace std; typedef long long ll; //AC in one go. Good dp. Box stacking problem. vector<vector<ll>> cubes(30, vector<ll>(3,-1)); vector<vector<ll>> dp(2501,vector<ll>(2501,-1)); ll n,min_area; ll dp_rec(ll i, ll j){ if(dp[i][j]!=-1) return dp[i][j]; if(i*j < min_area){ return 0; } dp[i][j] = 0; for(ll k=0;k<n;k++){ if((cubes[k][0] < i && cubes[k][1]< j) || (cubes[k][0] < j && cubes[k][1]< i)){ dp[i][j] = max(dp[i][j], cubes[k][2] + dp_rec(cubes[k][0], cubes[k][1])); } if((cubes[k][0] < i && cubes[k][2]< j) || (cubes[k][0] < j && cubes[k][2]< i)){ dp[i][j] = max(dp[i][j] , cubes[k][1] + dp_rec(cubes[k][0], cubes[k][2])); } if((cubes[k][1] < i && cubes[k][2]< j) || (cubes[k][1] < j && cubes[k][2]< i)){ dp[i][j] = max(dp[i][j], cubes[k][0] + dp_rec(cubes[k][1], cubes[k][2])); } } dp[j][i] = dp[i][j]; return dp[i][j]; } int main(){ while(true){ cin>>n; if(n==0) break; min_area = INT_MAX; for(ll i=0;i<n;i++){ for(ll j=0;j<3;j++){ cin>>cubes[i][j]; } if(cubes[i][0]*cubes[i][1] < min_area) min_area = cubes[i][0]*cubes[i][1]; if(cubes[i][0]*cubes[i][2] < min_area) min_area = cubes[i][0]*cubes[i][2]; if(cubes[i][2]*cubes[i][1] < min_area) min_area = cubes[i][2]*cubes[i][1]; } for(ll i=0;i<2501;i++){ for(ll j=0;j<2501;j++){ dp[i][j] = -1; } } dp[0][0] = 0; ll m=0,ans=0; for(ll k=0;k<n;k++){ m = cubes[k][2] + dp_rec(cubes[k][0],cubes[k][1]); m = max(m, cubes[k][1] + dp_rec(cubes[k][0],cubes[k][2])); m = max(m, cubes[k][0] + dp_rec(cubes[k][1],cubes[k][2])); ans = (ans<m)? m:ans; } cout<<ans<<"\n"; } return 0; }
#include "pch.h" #include "phrasetable.h" #include<string.h> #include<stdio.h> using namespace std; phrasetable::phrasetable() { head = NULL; } void phrasetable::AddNode(char *str,int count) { if (str == NULL)return; if (head == NULL) { head = new phrase; strcpy_s(head->content, str); head->count = count; head->next = NULL; //printf("创建:%s 次数:%d\n", head->content, head->count); return; } phrase *p = search(str); if (p == NULL) { p = new phrase; phrase *r = head; strcpy_s(p->content, str); p->count = count; p->next = NULL; while (r->next != NULL)r = r->next; r->next = p; //printf("创建:%s 次数:%d\n", p->content, p->count); } else { p->count += count; //printf("累加:%s 次数:%d\n", p->content, p->count); } } phrase *phrasetable::search(char *str) { if (str == NULL)return NULL; phrase *p = head; while (p!= NULL) { if (strcmp(p->content, str) == 0) return p; p = p->next; } return NULL; } phrasetable::~phrasetable() { } bool phrasetable::empty() { if (head !=NULL)return false; return true; } phrase*phrasetable::front() { return head; } void phrasetable::pop() { if (head = NULL)return; phrase *r = head; head = head->next; delete r; r = NULL; } phrase *phrasetable::max_count() { if (head == NULL)return NULL; phrase *x,*r; x = r = head; while (x ->next!= NULL) { x = x->next; if (r->count < x->count)r = x; else if (r->count == x->count) { if (strcmp(r->content, x->content) > 0) r = x; } } return r; } void phrasetable::del(phrase * p) { if (head == NULL)return; phrase *x=head; if (head == p) { head = head->next; delete x; x = NULL; return; } while (x!= NULL) { if (x->next == p) { x->next = p->next; delete p; p = NULL; return; } x = x->next; } }
// // Created by roy on 12/18/18. // #include "LineParser.h" /** * Constructor of LineParser, used for parsing single line. * @param symbolTable symbol table for variables access. * @param dataReaderServer data reader server for the check if in bind table. * @param dataSender data sender for the execution of sending commands to the client. */ LineParser::LineParser(SymbolTable *symbolTable, DataReaderServer *dataReaderServer, DataSender * newDataSender) { this->symbolTable = symbolTable; this->dataReaderServer = dataReaderServer; this->util.set(this->symbolTable, this->dataReaderServer); this->dataSender = newDataSender; } /** * This method parses the given strings vector and executes the matching commands * by their order. The block will be of two types: If block or While block. * @param stringVector vector of strings representing the commands and parameters. * @param startIndex starting index for the iteration on the vector. * @return int value of the jump needed in while/if commands. */ int LineParser::parse(vector<string> stringVector, int startIndex) { string commandString = stringVector.at(startIndex); // first string will represent the first command in line. Commands command = commandMap.getCommand(commandString); if (stringVector.at(startIndex + 1) == "=") { command = Equal; } int indexJumpValue = 0; // for each command option - execute the fitting operation: switch (command) { case OpenDataServer : { string port = util.shuntingYard(smallLexer.lexer(stringVector.at(startIndex + 1))); string herz = util.shuntingYard(smallLexer.lexer(stringVector.at(startIndex + 2))); OpenServerCommand openServer(port, herz, this->dataReaderServer, this->symbolTable); indexJumpValue = openServer.execute(); break; } case Connect : { ConnectCommand connect(stringVector.at(startIndex + 1), util.shuntingYard(smallLexer.lexer(stringVector.at(startIndex + 2))), this->dataSender); indexJumpValue = connect.execute(); break; } case Var : { if (stringVector.size() == 5) { VarCommand varCommand(this->dataReaderServer, this->symbolTable, stringVector.at(startIndex + 1), stringVector.at(startIndex + 2), stringVector.at(startIndex + 3), stringVector.at(startIndex + 4)); indexJumpValue = varCommand.execute(); } else { VarCommand varCommand(this->dataReaderServer, this->symbolTable, stringVector.at(startIndex + 1), stringVector.at(startIndex + 2), stringVector.at(startIndex + 3)); indexJumpValue = varCommand.execute(); } break; } case Equal : { EqualCommand equalCommand(this->dataReaderServer, this->dataSender, stringVector.at(startIndex), stringVector.at(startIndex + 2), this->symbolTable); indexJumpValue = equalCommand.execute(); break; } case Print : { string printString; // if the next string starts with quotes - string will be the string inside quotes. if (stringVector.at(startIndex + 1).at(0) == '"') { printString = stringVector.at(startIndex + 1).substr(1, stringVector.at(startIndex + 1).length() - 2); } // else, get the string value from symbol map. //if the next string starts as a number consider it a mathematical expression else if (stringVector.at(startIndex + 1).at(0) == '-' || stringVector.at(startIndex + 1).at(0) == '(' || isdigit(stringVector.at(startIndex + 1).at(0))) { printString = util.shuntingYard(smallLexer.lexer(stringVector.at(startIndex + 1))); } else { //check if its a local variable if (this->symbolTable->isInMap(stringVector.at(startIndex + 1))) { printString = to_string(this->symbolTable->get(stringVector.at(startIndex + 1))); //check if its a global variable } else if (this->symbolTable->isInMap(this->dataReaderServer->getBindAddress(stringVector.at(startIndex + 1)))) { printString = to_string( this->symbolTable->get(this->dataReaderServer->getBindAddress(stringVector.at(startIndex + 1)))); } } PrintCommand printCommand(printString); indexJumpValue = printCommand.execute(); break; } case Sleep : { // sleeps for the given amount of time. vector<string> stringExp = this->smallLexer.lexer(stringVector.at(startIndex + 1)); SleepCommand sleepCommand(stod(this->util.shuntingYard(stringExp))); indexJumpValue = sleepCommand.execute(); break; } // if the command is invalid command, throw. default: throw "No such Command"; } return indexJumpValue; }
// LeastSquares.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <vector> #include <iostream> using namespace std; vector<float> get_jth_col(vector<vector<float>>&B, int J) { vector<float>col; for (int i = 0; i < (int)B.size(); i++) { for (int j = 0; j <(int) B[0].size(); j++) { if (j == J) col.push_back(B[i][j]); } } return col; } vector<vector<float>> init_mxn(int m, int n) { vector<vector<float>> A; for (int i = 0; i < m; i++) { vector<float>row; for (int j = 0; j < n; j++) { row.push_back(0); } A.push_back(row); } return A; } vector<vector<float>> mxn_transpose(vector<vector<float>>&T) { int m = T.size(); int n = T[0].size(); vector<vector<float>>_A = init_mxn(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { _A[i][j] = T[j][i]; } } return _A; } float vector_dot(vector<float>&U, vector<float>&V) { if (U.size() != V.size()) { printf("error vmul: vectors must be same size: exiting with code 1\n"); exit(1); } float ss = 0; for (int i = 0; i < (int)U.size(); i++) { ss += U[i] * V[i]; } return ss; } vector<vector<float>> matrix_mul_AB(vector<vector<float>>&A, vector<vector<float>>&B, int an, int am, int bn, int bm) { if (an != bm) { printf("error mmul: matrices inner dimensions must agree: exiting with code 2\n"); exit(2); } float ij_dot_prod; vector<vector<float>>C = init_mxn(am, bn); for (int i = 0; i < am; i++) { vector<float>a_row_i = A[i]; //get ith row of A for (int j = 0; j < bn; j++) { vector<float>b_col_j = get_jth_col(B, j); float vmul = vector_dot(a_row_i, b_col_j); C[i][j] = vmul; } } return C; } vector<float> vector_sub(vector<float>&A, vector<float>&B) { vector<float>C; for (int i = 0; i < (int)A.size(); i++) { C.push_back(A[i] - B[i]); } return C; } vector<float> get_proj_A_onto_B(vector<float>&A, vector<float>&B) { vector<float>proj; vector<float>Bh; float s1 = vector_dot(A, B); float s2 = vector_dot(B, B); float op = s1 / s2; for (int i = 0; i < (int)B.size(); i++) { Bh.push_back(B[i] * op); } return Bh; } vector<vector<float>> get_Q(vector<vector<float>>&A) { int num_cols = A[0].size(); vector<float>v1 = get_jth_col(A, 0); vector<vector<float>>orthogonal_vecs; orthogonal_vecs.push_back(v1); for (int i = 1; i < num_cols; i++) { vector<float>xn = get_jth_col(A, i); vector<float>vn; vector<float>proj; for (int k = 0; k < (int)xn.size(); k++) { vn.push_back(xn[k]); } for (int j = 0; j < i; j++) { proj = get_proj_A_onto_B(xn, orthogonal_vecs[j]); vn = vector_sub(vn, proj); } orthogonal_vecs.push_back(vn); } return orthogonal_vecs; } void print_matrix(vector<vector<float>>&A, int m, int n) { for (int i = 0; i<m; i++) { printf("["); for (int j = 0; j<n; j++) { printf("%f,", A[i][j]); } printf("]\n"); } } int main() { vector<vector<float>>A = { {1.0,2.0,4.0}, {3.0,4.0,6.0}, {12.0,2.0,66.0}}; vector<vector<float>>_Q = get_Q(A); printf("%f", vector_dot(_Q[1], _Q[2])); int usr_in; cin >> usr_in; return usr_in; }
#pragma once #include <Dot++/parser/ParserStateInterface.hpp> #include <Dot++/Exceptions.hpp> #include <Dot++/lexer/Token.hpp> #include <Dot++/lexer/TokenType.hpp> #include <vector> namespace dot_pp { namespace parser { namespace states { template<class ConstructionPolicy> class ReadAttributeEqualState : public ParserStateInterface<ConstructionPolicy> { public: ParserState consume(const TokenInfoHandle& handle, TokenStack& stack, TokenStack& attributes, ConstructionPolicy& constructor) override { const auto& token = handle->token(); if((token.type() == lexer::TokenType::string) || (token.type() == lexer::TokenType::string_literal)) { const auto attribute = attributes.top(); const auto attributeToken = attribute->token(); attributes.pop(); std::vector<TokenInfoHandle> tokens; while(!stack.empty()) { tokens.push_back(stack.top()); stack.pop(); } for(std::size_t v2 = 0, v1 = 1, end = tokens.size(); v1 < end; ++v2, ++v1) { const auto v1Token = tokens[v1]->token(); const auto v2Token = tokens[v2]->token(); constructor.applyEdgeAttribute(v1Token.to_string(), v2Token.to_string(), attributeToken.to_string(), token.to_string()); } for(auto iter = tokens.crbegin(), end = tokens.crend(); iter != end; ++iter) { stack.push(*iter); } return ParserState::ReadLeftBracket; } throw dot_pp::SyntaxError("Unexpected token encountered, expected <string> or <string_literal>, found '" + token.to_string() + "'", *handle); } }; }}}
int t[1001][1001]; int recur(string a, string b, int m, int n){ if(m < 0) return n + 1; if(n < 0) return m + 1; if(t[n][m] != -1) return t[n][m]; if(a[m] == b[n]) return t[n][m] = recur(a, b, m-1, n-1); else{ //m,n-1 is basically inserting a char in A that is not matching //m-1,n-1 is replacing the char in a with that of b; //m-1,n is removing char from a return t[n][m] = 1 + min(recur(a, b, m, n-1), min(recur(a, b, m-1, n), recur(a, b, m-1, n-1))); } } int Solution::minDistance(string a, string b) { memset(t, -1, sizeof(t)); return recur(a, b, a.length()-1, b.length()-1); }
#ifndef MYXML_H #define MYXML_H #include<QPoint> #include <QtXml> #include<QFile> #include<QDebug> #include<QPaintDevice> #include<QPainter> #include<QPaintEngine> //#include "myxml_global.h" struct MyRect { QString name; QPoint start; QPoint end; int width; int height; }; class INFO { public: QString m_author; QString m_date; public: INFO() { m_author.clear(); m_date.clear(); } }; class OBJECT { public: QString m_name; QPoint m_start; QPoint m_end; public: OBJECT() { m_name.clear(); m_start.setX(0); m_start.setY(0); m_end.setX(0); m_end.setY(0); } }; class MyXML { public: int m_count=0;//object total number INFO m_info; OBJECT m_object[100]; public: MyXML(); MyXML(const char *filename); int readxml(const char *filename);//return the Object number int writexml(const char * filename); void MydrawRect(QPixmap& image, QString name,QPoint start,QPoint end); }; #endif // MYXML_H
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/resource.h> #include <sys/time.h> #include <vector> #include <fstream> #include <sstream> #include <chrono> #include "creads.h" //#include "config.h" #include "cseq.h" #include "mst.h" #include "trail.h" using namespace std; void RunMST(float **dist_matrix); float **process(char *dir, int k, char *matrix_fp); float **ReadMatrix(char *file_name); char *file_list_path; int n_threads=12; double threshold=1.2; int selected_number=100; char *output_fp; vector<string> file_list; int main (int argc, char **argv) { int _k = 7; int c; int if_read = 0; char *matrix_fp=NULL; while ((c = getopt(argc, argv, "r:o:t:k:e:s:m:z:")) != -1) switch (c) { case 'r': file_list_path = optarg; break; case 't': n_threads = atoi(optarg); break; case 'o': output_fp = optarg; break; case 'k': _k = atoi(optarg); break; case 's': selected_number = atoi(optarg); break; case 'e': threshold = atof(optarg); break; case 'm': file_list_path = optarg; if_read = 1; case 'z': matrix_fp = optarg; break; } char output_name[1024]; sprintf(output_name,"%s/cluster",output_fp); if( if_read ) { float **dist_matrix = ReadMatrix(file_list_path); printf("file number:%d\n",file_list.size()); Trail *trail = new Trail(file_list.size(),dist_matrix); trail->Run(); trail->WriteResult(output_fp); //RunMST(dist_matrix); return 0; } else { float **dist_matrix = process(output_fp,_k,matrix_fp); Trail *trail = new Trail(file_list.size(),dist_matrix); trail->Run(); trail->WriteResult(output_name); } return 0; } float **process(char *dir,int k, char *matrix_fp) { printf("input file list path: %s\n",file_list_path); fstream file; file.open(file_list_path,ios::in); int n = 0; if (file.is_open()) { //checking whether the file is open string line; while(getline(file, line)) { file_list.push_back(line); n++; } file.close(); //close the file object. } else { printf("failed to open %s\n",file_list_path); exit(1); } float **vectors = pre_process(file_list,output_fp,k,selected_number,matrix_fp); return vectors; } void RunMST(float **dist_matrix) { printf("bgein minimum tree\n"); // Edge e; // Graph* graph = new Graph(file_list.size(),threshold); // for(int i = 0; i < file_list.size()-1; i++) // { // for(int j = i+1; j < file_list.size(); j++) // { // e.vertices[0] = i; // e.vertices[1] = j; // e.weight = dist_matrix[i][j]; // graph->AddEdge(e); // } // } PrimMST *pMST = new PrimMST(dist_matrix,file_list.size()); printf("begin MST\n"); pMST->RunMST(); //graph->Split(output_fp); } float **ReadMatrix( char *file_name) { ifstream f(file_name); string line,value; int n = count(istreambuf_iterator<char>(f), istreambuf_iterator<char>(),'\n')-1; f.close(); printf("read file %s, line number:%d\n",file_name,n); // int n = 16, m = 4096; float **vectors = (float **)malloc(sizeof(float *)*n); for(int i = 0; i < n; i++) { file_list.push_back("a"); vectors[i] = (float *)malloc(sizeof(float)*selected_number); } ifstream myfile; myfile.open(file_name); getline(myfile,line); for(int i = 0; i < n; i++) { getline(myfile,line); stringstream linestream(line); getline(linestream,value,','); for(int j = 0; j < selected_number; j++) { getline(linestream,value,','); vectors[i][j] = stof(value); } } // for(int i = 0; i < n; i++) // { // float sum = 0.0; // for(int j = 0; j < selected_number; j++) // sum += vectors[i][j]; // for(int j = 0; j < selected_number; j++) // vectors[i][j] = 100*vectors[i][j]/sum; // } myfile.close(); return vectors; } // void RunMST() // { // //test case // Graph* graph = new Graph(4,1.2); // // add edge 0-1 // Edge e; // e.vertices[0] = 0; // e.vertices[1] = 1; // e.weight = 10.0; // graph->AddEdge(e); // e.vertices[0] = 0; // e.vertices[1] = 2; // e.weight = 6.0; // graph->AddEdge(e); // e.vertices[0] = 0; // e.vertices[1] = 3; // e.weight = 5.0; // graph->AddEdge(e); // e.vertices[0] = 1; // e.vertices[1] = 3; // e.weight = 15.0; // graph->AddEdge(e); // e.vertices[0] = 2; // e.vertices[1] = 3; // e.weight = 4.0; // graph->AddEdge(e); // graph->MST(); // graph->Split(output_fp); // delete graph; // return; // }
#include "Particle.h" #include <stdlib.h> #include <math.h> namespace pawstef { Particle::Particle(): m_x(0), m_y(0) { init(); } void Particle::init() { m_x=0; m_y=0; direction = (2* M_PI*rand())/RAND_MAX; speed = (0.04* rand())/RAND_MAX; speed *= speed; } Particle::~Particle() { } void Particle::update(int interval) { direction+= interval*0.0004; double xspeed = speed * cos(direction); double yspeed = speed * sin(direction); m_x += xspeed*interval; m_y += yspeed*interval; if(m_x<-1 || m_x>1 || m_y<-1 || m_y>1) { init(); } } }
// // meshingalgs.h // Total Control // // Created by Parker Lawrence on 8/23/15. // Copyright (c) 2015 Parker Lawrence. All rights reserved. // #ifndef __Total_Control__meshingalgs__ #define __Total_Control__meshingalgs__ #include <stdio.h> #include <vector> #include "glm/glm.hpp" // // //class Voxel8x8x8 { // public: // void recalculate(); // private: // float data[8][8][8]; // std::vector<unsigned int> vertexIndices; // std::vector<unsigned int> normalIndices; // std::vector<glm::vec3> vertices; // std::vector<glm::vec2> uvs; // std::vector<glm::vec3> normals; // // //}; #endif /* defined(__Total_Control__meshingalgs__) */
( English:'English'; Native:'American English'; LangFile:'english.lang'; DicFile:'english.dic'; FlagID:'us'; Letters:'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z'; LetterCount:'9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1'; LetterValue:'1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10'; NumberOfJokers:2; ReadingDirection:rdLeftToRight; ExcludedCat:'1'; //page 29, VI.A. RulesValid:true; NumberOfLetters:7; NumberOfRandoms:0; TimeControl:2; TimeControlEnd:false; TimeControlBuy:true; //page 26, V.F.3. TimePerGame:'0:50:00'; //page 26, V.F.2. PenaltyValue:10; //page 26, V.F.2. PenaltyCount:10; //page 26, V.F.3. GameLostByTime:true; //page 26, V.F.3. WordCheckMode:2; ChallengePenalty:0; //doubtful, but in fact in the rules nothing is written about that issue ChallengeTime:20; //page 20, IV.I.1. JokerExchange:false; ChangeIsPass:true; //page 25, V.C.2 CambioSecco:false; SubstractLetters:true; //page 25, V.F.1. (adapted to the current features of Scrabble3D) AddLetters:true; //page 25, V.F.1. (adapted to the current features of Scrabble3D) JokerPenalty:0; NumberOfPasses:3; //page 25, V.C.2 LimitExchange:7; //page 16, IV.E.2.a. EndBonus:0; ScrabbleBonus:50) {References: http://www.scrabbleplayers.org/wiki/images/9/95/Rules-20120616.pdf (NASPA, June 27, 2012) http://www.scrabbleplayers.org/w/Welcome_to_NASPAWiki http://www.scrabbleplayers.org/w/Rules - Current state of implementation in this *.inc file: 2012-08-10 }
#pragma once #ifndef VIEW3D_WINDOW_H #define VIEW3D_WINDOW_H #include <stddef.h> #define IMGUI_DEFINE_MATH_OPERATORS #include "imgui/imgui.h" #include "imgui/imgui_internal.h" #include "wimgui/window.h" #include "painter3d.h" namespace wimgui { class painter3d; class view3d : public window { private: std::vector<painter3d*> painters; protected: ImColor cross_line_color = ImColor(0.5f, 0.5f, 0.5f); ImColor x_axis_color = ImColor(1.0f, 0.0f, 0.0f); ImColor y_axis_color = ImColor(0.0f, 1.0f, 0.0f); ImColor z_axis_color = ImColor(0.0f, 0.0f, 1.0f); glm::mat4 projection_matrix, camera_matrix, view_matrix; glm::mat4 temp_camera_matrix; void stop_rotating(); void stop_moving(); public: view3d(const char* _title); glm::mat4 get_view_matrix() { view_matrix = projection_matrix * camera_matrix; return view_matrix; } void gl_paint(); void draw(); void center(); void view_top(); void view_bottom(); void view_left(); void view_right(); void view_front(); void view_back(); void init_scene(); void set_rotation(float x, float y, float z); void set_translation(float x, float y, float z); void move(float x, float y); void move(float x, float y, float z); void scale(float wheel); void rotate(float x, float y); void rotate(float x, float y, float z); void draw_zero_cross(); void add_painter(painter3d *painter); void remove_painter(painter3d *painter); }; } #endif
// // Created by 송지원 on 2020/06/29. // //바킹독 9강 BFS boj1926 #include <iostream> #include <queue> #include <utility> using namespace std; #define X first #define Y second int N, M; int dat[502][502]; bool vis[502][502]; int CNT = 0; int MAX = -1; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> N >> M; for(int i=0; i<N; i++) { for (int j=0; j<M; j++) { cin >> dat[i][j]; } } for(int i=0; i<N; i++) { for (int j=0; j<M; j++) { int temp_cnt; if (dat[i][j] && vis[i][j]==0) { queue<pair<int, int>> Q; // pair<int, int> cur; vis[i][j] = 1; Q.push({i, j}); temp_cnt = 1; while (!Q.empty()) { pair<int, int> cur = Q.front(); Q.pop(); for (int dir=0; dir<4; dir++) { int nx = cur.X + dx[dir]; int ny = cur.Y + dy[dir]; if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue; if (vis[nx][ny] || dat[nx][ny] != 1) continue; temp_cnt++; vis[nx][ny] = 1; Q.push({nx, ny}); } } if (temp_cnt > MAX) MAX = temp_cnt; CNT ++; } } } if (CNT == 0) MAX = 0; cout << CNT << "\n" << MAX; }
// TerrainLightDialog.cpp : 实现文件 // #include "stdafx.h" #include "Editor.h" #include "OgreEditor.h" #include "TerrainLightDialog.h" // CTerrainLightDialog 对话框 IMPLEMENT_DYNCREATE(CTerrainLightDialog, CDialog) CTerrainLightDialog::CTerrainLightDialog(CWnd* pParent /*=NULL*/) : CDialog(CTerrainLightDialog::IDD, pParent), mTerrainLight(NULL) { } CTerrainLightDialog::~CTerrainLightDialog() { } void CTerrainLightDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_X_EDIT, mXEdit); DDX_Control(pDX, IDC_Y_EDIT, mYEdit); DDX_Control(pDX, IDC_Z_EDIT, mZEdit); DDX_Text(pDX, IDC_X_EDIT, mDir.x); DDX_Text(pDX, IDC_Y_EDIT, mDir.y); DDX_Text(pDX, IDC_Z_EDIT, mDir.z); } BOOL CTerrainLightDialog::OnInitDialog() { CDialog::OnInitDialog(); mTerrainLight = GetEditor()->GetSceneManager()->getLight( "terrainLight" ); mDir = mTerrainLight->getDerivedDirection(); UpdateData(FALSE); return TRUE; } BEGIN_MESSAGE_MAP(CTerrainLightDialog, CDialog) ON_BN_CLICKED(IDC_APPLY_BTN, &CTerrainLightDialog::OnBnClickedApplyBtn) END_MESSAGE_MAP() // CTerrainLightDialog 消息处理程序 void CTerrainLightDialog::OnBnClickedApplyBtn() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); mTerrainLight->setDirection( mDir ); GetEditor()->GetTerrainGlobalOptions()->setLightMapDirection(mDir); //GetEditor()->GetTerrainGroup()->update(); //GetEditor()->GetTerrainGroup()->getTerrain(0,0)->dirtyLightmap(); //GetEditor()->GetTerrainGroup()->updateDerivedData(true); }
// // GameBegin.cpp // GetFish // // Created by zhusu on 15/5/12. // // #include "GameBegin.h" #include "Common.h" #include "Tools.h" #include "GameScene.h" GameBegin* GameBegin::create(int score,int type,int fishID,int num,int tishi1,int tishi2) { GameBegin* map = new GameBegin(); if(map && map->init( score, type,fishID, num,tishi1,tishi2)) { map->autorelease(); return map; } CC_SAFE_DELETE(map); return NULL; } GameBegin::GameBegin():_dead(false) { } GameBegin::~GameBegin() { } bool GameBegin::init(int score,int type,int fishID,int num,int tishi1,int tishi2) { if(!CCLayer::init()) { return false; } CCSprite* back = CCSprite::createWithSpriteFrameName("ui_tishi_back.png"); addChild(back); if(tishi1!=0){ CCSprite* back1 = CCSprite::createWithSpriteFrameName("ui_c_tishi.png"); back1->setPosition(ccp(back->boundingBox().size.width*0.5+back1->boundingBox().size.width*0.5-5, -2)); addChild(back1); int tinum = 1; if (tishi2!=0) { tinum=2; } CCSprite* t1 = CCSprite::create(("ui/ui_ctishi_"+Tools::intToString(tishi1)+".png").c_str()); t1->setPosition(ccp(back1->getPositionX(), back1->getPositionY()+40*(tinum-1))); addChild(t1); if (tinum>1) { CCSprite* t2 = CCSprite::create(("ui/ui_ctishi_"+Tools::intToString(tishi2)+".png").c_str()); t2->setPosition(ccp(back1->getPositionX(), back1->getPositionY()-90)); addChild(t2); } } CCSprite* zi0 = CCSprite::createWithSpriteFrameName("ui_tishi_guanka.png"); zi0->setAnchorPoint(ccp(0, 0)); zi0->setPosition(ccp(-back->boundingBox().size.width*0.5+15, 122)); addChild(zi0); int lev = GameScene::instance()->getNowLevel(); CCLabelAtlas *_levLabel = CCLabelAtlas::create( (Tools::intToString((lev/12)+1)+ "-"+Tools::intToString(lev-(lev/12)*12+1)).c_str(), "ui/shuzi4.png", 21, 28, 43); _levLabel->setAnchorPoint(ccp(0, 0)); _levLabel->setPosition(ccp(zi0->boundingBox().getMaxX()+10, zi0->getPositionY()+4)); addChild(_levLabel); CCSprite* zi1 = CCSprite::createWithSpriteFrameName("ui_tishi_zi.png"); zi1->setAnchorPoint(ccp(0, 0)); zi1->setPosition(ccp(-back->boundingBox().size.width*0.5+20, 60)); addChild(zi1); CCSprite* zi2; if (GameScene::instance()->getShip()->getActor()->count()>1){ zi2 = CCSprite::createWithSpriteFrameName("ui_tishi_zi4_4.png"); }else{ zi2 = CCSprite::createWithSpriteFrameName("ui_tishi_zi2.png"); } zi2->setAnchorPoint(ccp(0, 0)); zi2->setPosition(ccp(-back->boundingBox().size.width*0.5+25, 25)); addChild(zi2); for (int i = 0; i<2; ++i) { CCSprite* star10 = CCSprite::createWithSpriteFrameName("ui_sr.png"); star10->setPosition(ccp(80+i*60, 75)); addChild(star10); } CCSprite* zi20; if (GameScene::instance()->getShip()->getActor()->count()>1){ zi20 = CCSprite::createWithSpriteFrameName("ui_tishi_zi4_4.png"); }else{ zi20 = CCSprite::createWithSpriteFrameName("ui_tishi_zi2.png"); } zi20->setAnchorPoint(ccp(0, 0)); zi20->setPosition(ccp(25, 25)); addChild(zi20); CCLabelAtlas* _score20 = CCLabelAtlas::create( (","+Tools::intToString(GameScene::instance()->getMuBiao(1))).c_str(), "ui/shuzi5.png", 12, 15, 43); _score20->setAnchorPoint(ccp(0, 0)); _score20->setPosition(ccp(zi20->boundingBox().getMaxX()+5, zi20->getPositionY()+2)); addChild(_score20); for (int i = 0; i<3; ++i) { CCSprite* star1 = CCSprite::createWithSpriteFrameName("ui_sr.png"); star1->setPosition(ccp(50+i*60, -15)); addChild(star1); } CCSprite* zi21; if (GameScene::instance()->getShip()->getActor()->count()>1){ zi21 = CCSprite::createWithSpriteFrameName("ui_tishi_zi4_4.png"); }else{ zi21 = CCSprite::createWithSpriteFrameName("ui_tishi_zi2.png"); } zi21->setAnchorPoint(ccp(0, 0)); zi21->setPosition(ccp(25, -80)); addChild(zi21); CCLabelAtlas* _score21 = CCLabelAtlas::create( (","+Tools::intToString(GameScene::instance()->getMuBiao(2))).c_str(), "ui/shuzi5.png", 12, 15, 43); _score21->setAnchorPoint(ccp(0, 0)); _score21->setPosition(ccp(zi21->boundingBox().getMaxX()+5, zi21->getPositionY()+2)); addChild(_score21); CCSprite* zi3 = CCSprite::createWithSpriteFrameName("ui_tishi_zi3.png"); zi3->setAnchorPoint(ccp(0, 0)); zi3->setPosition(ccp(-back->boundingBox().size.width*0.5+20, -30)); addChild(zi3); CCSprite* zi4 = CCSprite::createWithSpriteFrameName(("ui_tishi_zi4_"+Tools::intToString(type+1)+".png").c_str()); zi4->setAnchorPoint(ccp(0, 0)); zi4->setPosition(ccp(-back->boundingBox().size.width*0.5+25, -80)); addChild(zi4); if(type == 0){ zi4->setPosition(ccp(-back->boundingBox().size.width*0.5+25, -80)); fish = CCArmature::create(("fish_"+Tools::intToString(fishID)).c_str()); fish->setPosition(ccp(-back->boundingBox().size.width*0.5+100, -70)); fish->setScale(0.5); addChild(fish); _num = CCLabelAtlas::create((","+Tools::intToString(num)).c_str(), "ui/shuzi5.png", 12, 15, 43); _num->setAnchorPoint(ccp(0, 0)); _num->setPosition(ccp(-back->boundingBox().size.width*0.5+130, -78)); addChild(_num); }else if(type == 1){ fish = CCArmature::create("item_2"); fish->setPosition(ccp(-back->boundingBox().size.width*0.5+100, -70)); addChild(fish); _num = CCLabelAtlas::create((","+Tools::intToString(num)).c_str(), "ui/shuzi5.png", 12, 15, 43); _num->setAnchorPoint(ccp(0, 0)); _num->setPosition(ccp(-back->boundingBox().size.width*0.5+130, -78)); addChild(_num); }else if(type == 3){ _num = CCLabelAtlas::create((","+Tools::intToString(num)).c_str(), "ui/shuzi5.png", 12, 15, 43); _num->setAnchorPoint(ccp(0, 0)); _num->setPosition(ccp(-back->boundingBox().size.width*0.5+zi2->boundingBox().size.width+30, -78)); addChild(_num); } _buttons = ButtonWithSpriteManage::create("ui/button.png"); addChild(_buttons); ButtonWithSprite* button_begin = ButtonWithSprite::create(BUTTON_GAME_BEGIN, "button_kaishi.png",0.8,0.8); button_begin->setPosition(ccp(120, -132)); _buttons->addButton(button_begin); ButtonWithSprite* button_back = ButtonWithSprite::create(BUTTON_GAME_BACK, "button_fanhui2.png",0.8,0.8); button_back->setPosition(ccp(-120, -132)); _buttons->addButton(button_back); _score = CCLabelAtlas::create( (","+Tools::intToString(score)).c_str(), "ui/shuzi5.png", 12, 15, 43); _score->setAnchorPoint(ccp(0, 0)); _score->setPosition(ccp(-back->boundingBox().size.width*0.5+zi2->boundingBox().size.width+30, 28)); addChild(_score,100); CCSprite* xian = CCSprite::createWithSpriteFrameName("ui_set_xian.png"); addChild(xian); return true; } void GameBegin::touchesBegan(CCSet * touchs,CCEvent * event) { _buttons->touchesBegan(touchs, event); } void GameBegin::touchesCancelled(CCSet * touchs,CCEvent * event) { _buttons->touchesCancelled(touchs, event); } void GameBegin::touchesMoved(CCSet * touchs,CCEvent * event) { _buttons->touchesMoved(touchs, event); } void GameBegin::touchesEnded(CCSet * touchs,CCEvent * event) { _buttons->touchesEnded(touchs, event); if(_buttons->getNowID() == BUTTON_GAME_BEGIN){ setDead(DEAD_TYPE_TOGAME); }else if(_buttons->getNowID() == BUTTON_GAME_BACK){ setDead(DEAD_TYPE_BACK); } }
# include <iostream> using namespace std; int main1() { // 变量创建 数据类型 变量名 = 初始值 int a = 10; cout << "a=" << a << endl; cout << "hello world" << endl; system("pause"); return 0; }
// Strongly-connected components const int maxn = 222; vector<int> g[maxn]; // <-- input data int comp[maxn]; // <-- result here ;) bool visit[maxn]; vector<int> revg[maxn]; vector<int> que, component; int last_comp_id; void dfs_fwd(int v) { visit[v] = true; for (int u : g[v]) if (!visit[u]) dfs_fwd(u); que.push_back(v); } void dfs_rev(int v) { visit[v] = true; for (int u : revg[v]) if (!visit[u]) dfs_rev(u); component.push_back(v); } void tarjan() { // add reverse edges for (int v = 0; v < maxn; ++v) revg[v].clear(); for (int v = 0; v < maxn; ++v) for (int u : g[v]) revg[u].push_back(v); // dfs forward memset(visit, 0, sizeof(visit)); que.clear(); for (int v = 0; v < maxn; ++v) if (!visit[v]) dfs_fwd(v); reverse(que.begin(), que.end()); // dfs backward memset(visit, 0, sizeof(visit)); for (int v : que) if (!visit[v]) { component.clear(); dfs_rev(v); for (int u : component) comp[u] = last_comp_id; ++last_comp_id; } }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <unordered_map> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 11111 struct Tp { int score, mask; } a[N]; int n, k, m; unordered_map<int, vector<int> > v[1111]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf("%d%d", &n, &k); for (int i = 1; i <= n; ++i) { int t; scanf("%d%d", &a[i].score, &t); for (int j = 0; j < t; ++j) { int x; scanf("%d", &x); a[i].mask |= (1 << (x - 1)); } for (int j = 0; j < (1 << k); ++j) v[j][j & a[i].mask].push_back(a[i].score); } for (int i = 0; i < (1 << k); ++i) for (unordered_map<int, vector<int> >::iterator j = v[i].begin(); j != v[i].end(); ++j) sort(j->second.begin(), j->second.end(), greater<int>()); scanf("%d", &m); for (int i = 0; i < m; ++i) { int x, t, msk1 = 0, msk2 = 0; scanf("%d%d", &x, &t); for (int j = 0; j < t; ++j) { int y; scanf("%d", &y); msk1 |= (1 << (y - 1)); msk2 |= a[x].mask & (1 << (y - 1)); } vector<int>& vv = v[msk1][msk2]; printf("%d\n", (int)(lower_bound(vv.begin(), vv.end(), a[x].score, greater<int>()) - vv.begin()) + 1); } return 0; }
// Copyright (c) 2017 Mozart Alexander Louis. All rights reserved. // Includes #include "base_entity.hxx" #include "engines/tmx/tmx_engine.hxx" BaseEntity::BaseEntity(BaseGameScene* scene, ValueMap params, const string& tmx_layer) : direction_(NONE), game_scene_(*scene), stats_(std::move(params)), current_point_(Point(-1, -1)), movement_(decimal<3>(0)), speed_changer_(decimal<3>(0)), can_move_(true), tiles_(*TmxEngine::getInstance()->getTmxObject(game_scene_.map_->getName())) { // Initialize the entity and set parameters auto data = ArchiveUtils::loadValueMap(stats_.at(__ENTITY_FILE__).asString()); initWithDictionary(data); setPositionType(PositionType::RELATIVE); ParticleSystemQuad::setName(stats_.at(__ENTITY_ID__).asString()); ParticleSystemQuad::setCascadeOpacityEnabled(true); ParticleSystemQuad::setOpacityModifyRGB(true); // Set entities speed entitiy_speed_ = stats_.at(__ENTITY_SPEED__).asDouble(); // Initialize the PathUtils pointer path_utils_.setWorldSize(game_scene_.map_->getMapSize()); // Set the current layer that enitiy should be observing setCurrentTmxLayer(tmx_layer); } BaseEntity::~BaseEntity() = default; void BaseEntity::setCurrentPoint(const Point& point) { current_point_ = point; } Point BaseEntity::getCurrentPoint() const { return current_point_; } void BaseEntity::setCanMove(const bool move) { can_move_.store(move); } bool BaseEntity::getCanMove() const { return can_move_.load(memory_order_acquire); } void BaseEntity::setCurrentTmxLayer(const string& layer) { current_tmx_layer_ = layer; path_utils_.addCollisionList(tiles_, current_tmx_layer_); } string BaseEntity::getCurrentTmxLayer() const { return current_tmx_layer_; }
/** ****************************************************************************** * Copyright (c) 2019 - ~, SCUT-RobotLab Development Team * @file : referee.h * @author : Lingzi_Xie 1357657340@qq.com * @brief : Code for communicating with Referee system of Robomaster 2021. ****************************************************************************** * @attention * * if you had modified this file, please make sure your code does not have many * bugs, update the version NO., write dowm your name and the date, the most * important is make sure the users will have clear and definite understanding * through your new brief. ****************************************************************************** */ #ifndef __REFEREE_H__ #define __REFEREE_H__ /* Includes ------------------------------------------------------------------*/ #include <stdint.h> #include <string.h> #include "../Components/drv_uart.h" #ifdef __cplusplus /* Private define ------------------------------------------------------------*/ #define DRAWING_PACK 15 #define ROBOT_COM_PACK 8 /* Private variables ---------------------------------------------------------*/ /* Exported macros -----------------------------------------------------------*/ /* Private type --------------------------------------------------------------*/ /* 裁判系统状态;0:掉线,1:在线 */ enum RF_status_e { RF_OFFLINE = 0U, RF_ONLINE }; /* 枚举变量,用于车间通信数组访问 */ enum{ HERO = 0U, ENGINEER, INFANTRY_3, INFANTRY_4, INFANTRY_5, AERIAL, SENTRY, RADAR = 8U }; enum{ Robot_Red = 0U, Robot_Blue }; /* 己方机器人ID及当前机器人客户端ID */ typedef struct { uint8_t hero; uint8_t engineer; uint8_t infantry_3; uint8_t infantry_4; uint8_t infantry_5; uint8_t aerial; uint8_t sentry; uint8_t drat; //飞镖发射架 uint8_t radar; //雷达站 uint8_t local; //本机器人ID uint8_t robot_where; //蓝方 or 红方机器人 uint16_t client; //对应的客户端ID } __attribute__((packed))RC_ID; /* 数据帧帧头结构体 */ typedef struct { uint8_t SOF; uint16_t DataLength; uint8_t Seq; uint8_t CRC8; uint16_t CmdID; } __attribute__((packed))FrameHeader; /* 交互数据帧的统一数据段段头 */ typedef __packed struct { uint16_t data_cmd_id; uint16_t send_ID; uint16_t receiver_ID; } DataHeader; /* ----------------------------------各种数据类型对应的ID号--------------------------------------- */ typedef enum { /* 裁判系统发过来数据帧ID类型,注意这里是CMD_ID */ GameState_ID = 0x0001, //比赛状态数据 1Hz GameResult_ID = 0x0002, //比赛结果数据 结束后发送 GameRobotHP_ID = 0x0003, //机器人血量数据 1Hz DartStatus_ID = 0x0004, //【05.06的协议中移除了?!】飞镖发射状态数据 ICRA_DebuffStatus_ID = 0x0005, //人工智能挑战赛加成与惩罚状态 1Hz EventData_ID = 0x0101, //场地事件数据 1Hz SupplyProjectileAction_ID = 0x0102, //补给站动作标识 动作后发送 RefereeWarning_ID = 0x0104, //裁判警告数据 警告后发送 DartRemainingTime_ID = 0x0105, //飞镖发射口倒计时 1Hz GameRobotState_ID = 0x0201, //机器人状态 10Hz PowerHeatData_ID = 0x0202, //功率热量数据 50Hz GameRobotPos_ID = 0x0203, //机器人位置数据 10Hz BuffMusk_ID = 0x0204, //机器人增益 状态改变后发送 AerialRobotEnergy_ID = 0x0205, //空中机器人能量 10Hz RobotHurt_ID = 0x0206, //伤害数据 伤害发生后发送 ShootData_ID = 0x0207, //实时射击数据 发射后发送 BulletRemaining_ID = 0x0208, //子弹剩余发送数 哨兵及空中 1Hz RFID_Status_ID = 0x0209, //RFID状态 1Hz ExtDartClientCmd_ID = 0x020A, //飞镖机器人客户端发送指令 10Hz StudentInteractiveHeaderData_ID = 0x0301, //机器人交互数据 30Hz上限 CustomControllerData_ID = 0x0302, //自定义控制器交互数据接口 30Hz MiniMapInteractiveData_ID = 0x0303, //小地图交互数据 交互发送 VT_Data_ID = 0x0304, //键盘、鼠标数据,通过图传发送 ClientMapCommand_ID = 0x0305, //小地图接收信息 /* 机器人交互数据段的ID类型,注意这里是数据段内容ID! */ RobotComData_ID = 0x0233, //车间交互,该ID由各个队伍自定义 CustomData_ID = 0xD180, //自定义数据ID Drawing_Clean_ID = 0x0100, Drawing_1_ID = 0x0101, Drawing_2_ID = 0x0102, Drawing_5_ID = 0x0103, Drawing_7_ID = 0x0104, Drawing_Char_ID = 0x0110, } RefereeSystemID_t; /* ----------------------------------比赛数据帧的数据段框架--------------------------------------- */ /** @brief 比赛状态数据:0x0001,1Hz */ typedef struct { uint8_t game_type : 4; uint8_t game_progress : 4; uint16_t stage_remain_time; uint64_t SyncTimeStamp; } __attribute__((packed))ext_game_status_t; /** @brief 比赛结果数据:0x0002,在比赛结束后发送 */ typedef struct { uint8_t winner; } ext_game_result_t; /** @brief 机器人血量数据:0x0003,1Hz */ typedef struct { uint16_t red_1_robot_HP; uint16_t red_2_robot_HP; uint16_t red_3_robot_HP; uint16_t red_4_robot_HP; uint16_t red_5_robot_HP; uint16_t red_7_robot_HP; uint16_t red_outpost_HP; uint16_t red_base_HP; uint16_t blue_1_robot_HP; uint16_t blue_2_robot_HP; uint16_t blue_3_robot_HP; uint16_t blue_4_robot_HP; uint16_t blue_5_robot_HP; uint16_t blue_7_robot_HP; uint16_t blue_outpost_HP; uint16_t blue_base_HP; } ext_game_robot_HP_t; /** @brief 飞镖发射状态:0x0004,飞镖发射后发送(05.06删去) */ typedef struct { uint8_t dart_belong; //发射方 uint16_t stage_remaining_time; //发射时比赛剩余时间 } __attribute__((packed))ext_dart_status_t; /** @brief 人工智能挑战赛加成与惩罚区状态:0x0005,1Hz */ typedef struct { uint8_t F1_zone_status:1; uint8_t F1_zone_buff_debuff_status:3; uint8_t F2_zone_status:1; uint8_t F2_zone_buff_debuff_status:3; uint8_t F3_zone_status:1; uint8_t F3_zone_buff_debuff_status:3; uint8_t F4_zone_status:1; uint8_t F4_zone_buff_debuff_status:3; uint8_t F5_zone_status:1; uint8_t F5_zone_buff_debuff_status:3; uint8_t F6_zone_status:1; uint8_t F6_zone_buff_debuff_status:3; uint16_t red1_bullet_felt; uint16_t red2_bullet_felt; uint16_t blue1_bullet_felt; uint16_t blue2_bullet_felt; } __attribute__((packed))ext_ICRA_buff_debuff_zone_status_t; /** @brief 场地事件数据:0x0101,事件改变发送 */ typedef struct { uint32_t event_type; } ext_event_data_t; /** @brief 补给站动作标识:0x0102 动作改变后发送 */ typedef struct { uint8_t supply_projectile_id; uint8_t supply_robot_id; uint8_t supply_projectile_step; uint8_t supply_projectile_num; } ext_supply_projectile_action_t; /** @brief 裁判警告信息:0x0104 警告发生后发送 */ typedef struct { uint8_t level; uint8_t foul_robot_id; } ext_referee_warning_t; /** @brief 飞镖发射口倒计时:0x0105,1Hz */ typedef struct { uint8_t dart_remaining_time; } ext_dart_remaining_time_t; /** @brief 当前比赛机器人状态:0x0201,10Hz */ typedef struct { uint8_t robot_id; uint8_t robot_level; uint16_t remain_HP; uint16_t max_HP; uint16_t shooter_id1_17mm_cooling_rate;/* 17mm */ uint16_t shooter_id1_17mm_cooling_limit; uint16_t shooter_id1_17mm_speed_limit; uint16_t shooter_id2_17mm_cooling_rate; uint16_t shooter_id2_17mm_cooling_limit; uint16_t shooter_id2_17mm_speed_limit; uint16_t shooter_id1_42mm_cooling_rate; uint16_t shooter_id1_42mm_cooling_limit; uint16_t shooter_id1_42mm_speed_limit; uint16_t classis_power_limit; uint8_t mains_power_gimbal_output : 1; uint8_t mains_power_chassis_output : 1; uint8_t mains_power_shooter_output : 1; } __attribute__((packed))ext_game_robot_status_t; /** @brief 实时功率热量数据:0x0202,50Hz */ typedef struct { uint16_t chassis_volt; uint16_t chassis_current; float chassis_power; uint16_t chassis_power_buffer; uint16_t shooter_id1_17mm_cooling_heat; uint16_t shooter_id2_17mm_cooling_heat; uint16_t shooter_id1_42mm_cooling_heat; } __attribute__((packed))ext_power_heat_data_t; /** @brief 机器人位置:0x0203,10Hz */ typedef __packed struct { float x; float y; float z; float yaw; } ext_game_robot_pos_t; /** @brief 机器人增益:0x0204,状态改变后发送 */ typedef struct { uint8_t power_rune_buff; } ext_buff_t; /** @brief 空中机器人能量状态:0x0205,10Hz */ typedef struct { uint8_t attack_time; } aerial_robot_energy_t; /** @brief 伤害状态:0x0206,受到伤害后发送 */ typedef struct { uint8_t armor_id : 4; uint8_t hurt_type : 4; } ext_robot_hurt_t; /** @brief 实时射击信息:0x0207,射击后发送 */ typedef struct { uint8_t bullet_type; uint8_t shooter_id; uint8_t bullet_freq; float bullet_speed; } __attribute__((packed))ext_shoot_data_t; /** @brief 子弹剩余发射数:0x0208,10Hz */ typedef struct { uint16_t bullet_remaining_num_17mm; uint16_t bullet_remaining_num_42mm; uint16_t coin_remaining_num; } ext_bullet_remaining_t; /** @brief 机器人RFID状态:0x0209,1Hz */ typedef struct { uint32_t rfid_status; /* 每个位代表不同地点的RFID状态 */ } ext_rfid_status_t; /*RFID状态不完全代表对应的增益或处罚状态,例如敌方已占领的高低增益点,不能获取对应的增益效果*/ /** @brief 飞镖机器人客户端指令数据:0x020A,10Hz 只对飞镖发送 */ typedef struct { uint8_t dart_launch_opening_status; uint8_t dart_attack_target; uint16_t target_change_time; uint16_t operate_launch_cmd_time; } __attribute__((packed))ext_dart_client_cmd_t; /* ----------------------------------裁判系统客户端交互部分--------------------------------------- */ /** @brief 交互数据段通用段头结构体定义:自定义数据的命令ID为:0x0301,10Hz */ typedef struct { uint16_t data_cmd_id; uint16_t sender_ID; uint16_t receiver_ID; } ext_student_interactive_header_data_t; /** @brief 学生机器人间通信:命令ID为0x0301,内容ID:在0x0200~0x02FF内自由选择,10Hz @brief 这里定义了完整的数据段格式,虽然看起来有些冗余,但方便处理其他机器人的发过来的数据报 */ typedef struct { uint16_t data_cmd_id; //数据段段首 uint16_t sender_ID; uint16_t receiver_ID; uint8_t data[112]; //!<长度需要小于113个字节(官方手册约定) } __attribute__((packed))robot_interactive_data_t; typedef struct { uint8_t data[ROBOT_COM_PACK]; //接收到的数据 } my_interactive_data_t; /** @brief 自定义控制器交互数据:0x0302,30Hz; @brief 注意!该交互数据包数据段没有段首,直接就是数据部分 */ typedef struct { uint8_t data[30]; //!<长度需要小于30个字节(官方手册约定) } custom_controller_interactive_data_t; /** @brief 小地图下发数据:0x0303 触发时发送; */ typedef struct { float target_position_x; float target_position_y; float target_position_z; uint8_t commd_keyboard; uint16_t target_robot_ID; } __attribute__((packed))ext_mini_map_command_t; /** @brief 键鼠信息,通过图传发送到机器人(图传发送端的3pin接口):0x0304; */ typedef struct { int16_t mouse_x; int16_t mouse_y; int16_t mouse_z; int8_t left_button_down; int8_t right_button_down; uint16_t keyboard_value; uint16_t reserved; } __attribute__((packed))ext_VT_command_t; /** @brief 雷达站下发数据帧内容定义,将被己方操作手以第一人称看到,0x305 */ typedef struct { uint16_t target_robot_ID; //敌方机器人的坐标 float target_position_x; float target_position_y; float toward_angle; } __attribute__((packed))ext_client_map_command_t; /* ----------------------------------解包用到的宏定义、枚举量--------------------------------------- */ #define START_ID 0XA5 //数据帧的起始ID,官方约定 #define PROTOCAL_FRAME_MAX_SIZE 60 //这个参数在解包时只作为大致的数据包长度判断,可以设置为 >= 最大长度 #define HEADER_LEN 4 //数据帧帧头长度(为5),4是为了方便直接用数组访问 #define CRC_ALL_LEN 3 //CRC校验码长度 #define CRC_8_LEN 1 #define CMD_LEN 2 //数据帧指令ID /* 数据帧解包状态 */ typedef enum { STEP_HEADER_SOF=0, //帧头SOF,应为0xA5 STEP_LENGTH_LOW, //数据段长度低8位 STEP_LENGTH_HIGH, //数据段长度高8位 STEP_FRAME_SEQ, //包序号 STEP_HEADER_CRC8, //帧头CRC8校验码 STEP_DATA_CRC16 //帧末CRC16校验码 } unPackStep_e; /* Exported ------------------------------------------------------------------*/ /* ----------------------------------客户端绘图相关--------------------------------------- */ /* 绘制图形操作,数据段 */ typedef struct { uint8_t graphic_name[3]; //图形名称,作为客户端中的索引 uint32_t operate_tpye:3; //图形操作(空、增加、修改、删除) uint32_t graphic_tpye:3; //图形类型(何种图案或数字) uint32_t layer:4; //图层数 uint32_t color:4; //颜色 uint32_t start_angle:9; //起始角度 uint32_t end_angle:9; //终止角度 uint32_t width:10; //线宽 uint32_t start_x:11; //起点坐标 uint32_t start_y:11; uint32_t radius:10; //字体大小或半径 uint32_t end_x:11; //终点坐标 uint32_t end_y:11; } __attribute__((packed))graphic_data_struct_t; /* 删除指定图层操作,数据段 */ typedef __packed struct { uint8_t operate_tpye; uint8_t layer; } ext_client_custom_graphic_delete_t; /* 图形配置操作指令,参照官方手册P23 */ typedef enum { NULL_OPERATION = 0U, ADD_PICTURE = 1U, MODIFY_PICTURE = 2U, CLEAR_ONE_PICTURE = 3U, } drawOperate_e; /* 图形清除操作指令 */ typedef enum { CLEAR_ONE_LAYER = 1U, CLEAR_ALL = 2U, } clearOperate_e; /* 图形绘制类型 */ typedef enum { LINE = 0U, RECTANGLE = 1U, CIRCLE = 2U, OVAL = 3U, ARC = 4U, _FLOAT = 5U, _INT = 6U, _CHAR = 7U, } graphic_tpye_e; /* 图形色彩配置 */ typedef enum { RED = 0U, BLUE = 0U, YELLOW, GREEN, ORANGE, PURPLE, PINK, DARKGREEN, BLACK, WHITE }colorType_e; /* 交互数据帧的通信类型,机器人间通信 or 自定义UI or 小地图通信 */ typedef enum { CV_OtherRobot = 0U, UI_Client, MiniMap_Client }receive_Type_e; typedef uint32_t (*SystemTick_Fun)(void); /* ----------------------------------裁判系统串口通信类--------------------------------------- */ class referee_Classdef { public: /* 机器人ID */ RC_ID robot_client_ID; /* 裁判系统连接状态,Todo */ RF_status_e status; /* 比赛接收数据 */ ext_game_status_t GameState; //比赛状态数据 ext_game_result_t GameResult; //比赛结果数据 ext_game_robot_HP_t GameRobotHP; //机器人血量数据 ext_dart_status_t DartStatus; //飞镖状态数据 ext_event_data_t EventData; //场地事件数据 ext_supply_projectile_action_t SupplyAction; //补给站动作数据 ext_referee_warning_t RefereeWarning; //裁判警告信息数据 ext_dart_remaining_time_t DartRemainTime; //飞镖发射倒计时数据 ext_game_robot_status_t GameRobotState; //机器人状态:当前血量、射速、底盘功率等 ext_power_heat_data_t PowerHeatData; //机器人功率、热量数据 ext_game_robot_pos_t RobotPos; //机器人位置数据 ext_buff_t RobotBuff; //机器人增益数据 aerial_robot_energy_t AerialEnergy; //空中机器人能量状态数据 ext_robot_hurt_t RobotHurt; //机器人伤害状态数据 ext_shoot_data_t ShootData; //实时射击信息数据 ext_bullet_remaining_t BulletRemaining; //剩余弹丸量数据 ext_rfid_status_t RFID_Status; //RFID状态数据 ext_dart_client_cmd_t DartClientCmd; //飞镖机器人客户端指令数据 /* 交互数据 */ my_interactive_data_t robot_rec_data[9]; //存储本方其他机器人发送的信息,添加了雷达站 custom_controller_interactive_data_t custom_control_data; //自定义控制器数据段部分 ext_mini_map_command_t mini_map_data; //小地图下发信息 ext_VT_command_t VT_command_data; //键鼠信息,通过图传发送端接收 ext_client_map_command_t radar_map_data; //雷达站信息 referee_Classdef(){} //构造函数定义 void Init(UART_HandleTypeDef *_huart, uint32_t (*getTick_fun)(void)); //初始化学生串口 void unPackDataFromRF(uint8_t *data_buf, uint32_t length); //数据帧整帧解包 void CV_ToOtherRobot(uint8_t target_id, uint8_t* data1, uint8_t length); //机器人之间车间通信 void Radar_dataTransmit(uint8_t target_id, float position_x, float position_y, float toward_angle); //雷达站信息发送 /* 用于清除图像 */ void clean_one_picture(uint8_t vlayer,uint8_t name[]); //清除单个图形 void clean_two_picture(uint8_t vlayer,uint8_t name1[], uint8_t name2[]); //清除两张图形 void clean_layer(uint8_t _layer); //清除单个图层 void clean_all(); //清除所有 /* 组合图形用户接口实现【已测试】 */ /* 字符串绘制 */ void Draw_Char(uint8_t _layer, uint16_t start_x, uint16_t start_y, uint8_t* char_name, uint8_t* data, uint16_t str_len, uint16_t str_size, colorType_e _color, drawOperate_e _operate_type); /* 通用UI标尺 */ uint8_t UI_ruler(uint8_t _layer, uint16_t start_x, uint16_t start_y, uint16_t scale_step, uint16_t scale_long, uint16_t scale_short, colorType_e _color, drawOperate_e _operate_type); /* 通用UI准星 */ void UI_Collimator(uint8_t _layer, uint16_t start_x, uint16_t start_y, uint16_t line_length, colorType_e _color, drawOperate_e _operate_type); /* 【图层0】视觉自瞄开启标志 */ void Draw_Auto_Lock(uint8_t auto_flag, uint16_t center_x, uint16_t center_y, uint16_t line_width, colorType_e _color); /* 【图层0】车界线绘制 */ void Draw_Robot_Limit(uint16_t height, uint16_t distance, uint16_t center_x, uint16_t line_width, colorType_e _color, drawOperate_e _operate_type); /* 【图层3】静态弹仓标志,不允许添加其他图形在该图层 */ void Draw_Bullet(uint8_t bullet_flag, uint16_t center_x, uint16_t center_y, uint16_t line_width, colorType_e _color); /* 【图层2】静态小陀螺标志 */ void Draw_Spin(uint8_t spin_flag, uint16_t center_x, uint16_t center_y, uint16_t line_width, colorType_e _color); /* 【图层1】超级电容开启绘制 */ void Draw_Boost(uint8_t boost_flag, uint16_t center_x, uint16_t center_y, uint16_t line_width, colorType_e _color); /* 【图层1】电容电压百分比绘制,并配合超级电容开启打印提示字符串 */ void Draw_Cap_Energy(float current_volt, float max_volt, float min_volt, uint8_t enable_cnt, uint16_t center_x, uint16_t center_y); /* 【图层4】无弹丸时提示补弹 */ void Draw_No_Bullet(uint8_t no_bullet_flag, uint16_t center_x, uint16_t center_y, colorType_e _color); /* ---------------------英雄机器人榴弹准星,自定义图层----------------------- */ void Hero_UI_ruler(uint8_t _layer, uint16_t start_x, uint16_t start_y, uint16_t* line_distance, uint16_t* line_length, colorType_e* _color, drawOperate_e _operate_type); /* ---------------------空中机器人UI绘制,自定义图层----------------------- */ //空中机器人pitch轴标尺 void Aerial_PitchRuler_Frame(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t total_length, uint16_t long_scale_length, uint16_t short_scale_length, colorType_e ruler_color, colorType_e current_color, colorType_e target_color); void Aerial_Pitch_Update(float pitch_angle, uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t total_length, colorType_e tag_color); //空中机器人pitch轴浮标 void Aerial_Pitch_Target(float pitch_target, uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t total_length, colorType_e target_color); //空中机器人pitch轴目标浮标 //云台手剩余全局剩余弹量显示 void Aerial_BulletRemain_Frame(uint8_t layer, uint16_t start_x, uint16_t start_y, uint16_t size); void Aerial_BulletRemain_Update(uint16_t _17mm, uint16_t _42mm, uint8_t layer, uint16_t start_x, uint16_t start_y, uint16_t size); /* ---------------------工程机器人UI绘制,自定义图层----------------------- */ //工程机器人抬升高度标尺 void Engineer_HighthRuler_Frame(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t total_length, uint16_t long_scale_length, uint16_t short_scale_length, uint8_t ruler_tag, colorType_e ruler_color, colorType_e current_color); //工程机器人当前抬升高度浮标 void Engineer_Height_Update(float height, uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t total_length, uint8_t ruler_tag, colorType_e tag_color); //工程机器人当前抬升高度浮标(两个标尺的浮标合并为一个数据包发送,减少数据包传输延迟带来的动态效果不同步) void Engineer_HeightMul_Update(float *height, uint8_t _layer, uint16_t *center_x, uint16_t *center_y, uint16_t *total_length, colorType_e tag_color); //工程机器人目标抬升高度浮标 void Engineer_Target_Height(float target_height, uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t total_length, uint8_t ruler_tag, colorType_e tag_color); void Mine_Icon(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t mine_tag, colorType_e _color, drawOperate_e _operate_type); //矿石图标 void Engineer_MineRe_Frame(uint8_t _layer, uint16_t start_x, uint16_t start_y, uint8_t size); //工程机器人当前存储矿石数UI框架 void Engineer_MineRe_Update(uint8_t mine_num, uint8_t _layer, uint16_t start_x, uint16_t start_y, uint8_t size); //更新工程机器人存储矿石数 void Engineer_MineMode_Update(uint8_t mode, uint8_t _layer, uint16_t start_x, uint16_t start_y, uint8_t size, colorType_e _color); //工程机器人自动/手动组状态 void Engineer_RescueMode_Update(uint8_t mode, uint8_t _layer, uint16_t start_x, uint16_t start_y, uint8_t size, colorType_e _color); //工程机器人救援/刷卡状态 void Engineer_AutoMode_Update(uint8_t status, uint8_t _layer, uint16_t start_x, uint16_t start_y, uint8_t size); //工程机器人自动组状态 /* ----------------------哨兵机器人UI绘制,自定义图层----------------------- */ void Sentry_PosRuler_Frame(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t total_length, colorType_e ruler_color, colorType_e current_color);//哨兵机器人移动轨道绘制 void Sentry_Pos_Update(float pos_percent, uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t total_length, colorType_e tag_color); //哨兵机器人当前位置浮标 void Sentry_Patrol_Frame(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t size, uint8_t *keys, colorType_e patrol_color); //哨兵机器人巡逻区域绘制 void Sentry_Patrol_Update(uint8_t tag, uint8_t _layer, uint16_t center_x, uint16_t center_y, uint16_t size, colorType_e _color); //哨兵机器人索敌状态指示 void Sentry_Bullet_Frame(uint8_t _layer, uint16_t start_x, uint16_t start_y, uint16_t size, colorType_e _color); //哨兵机器人发弹状态框架 void Sentry_Bullet_Update(uint8_t tag, uint8_t _layer, uint16_t start_x, uint16_t start_y, uint16_t size, colorType_e _color); //哨兵机器人发弹状态 /* ----------------------雷达站策略集显示,占用图层9------------------------ 策略集发生变化时,会占用带宽以绘制对应UI*/ void Armor(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t armor_tag, colorType_e _color, drawOperate_e _operate_type); //盾牌图标 void Sword(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t sword_tag, colorType_e _color, drawOperate_e _operate_type); //剑图标 void Outpost_Icon(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t tag, colorType_e _color, drawOperate_e _operate_type); //前哨站图标 void Sentry_Icon(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t tag, colorType_e _color, drawOperate_e _operate_type); //哨兵图标 void Missle_Icon(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t tag, colorType_e _color, drawOperate_e _operate_type); //飞镖图标 void High_Land(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t tag, colorType_e _color, drawOperate_e _operate_type); //高地图标 void Windmill_Icon(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t tag, colorType_e _color, drawOperate_e _operate_type); //神符图标 void FlyingSlope_Icon(uint8_t _layer, uint16_t center_x, uint16_t center_y, uint8_t size, uint8_t tag, colorType_e _color, drawOperate_e _operate_type); //飞坡图标 void Radar_Strategy_Frame(uint16_t *frame_pos_x, uint16_t *frame_pos_y); //雷达站策略UI框架 void Radar_CStrategy_Update(uint8_t protect, uint8_t attack, uint8_t comment_startegy, uint16_t *pos_x, uint16_t *pos_y); //雷达站全局策略UI绘制 void Radar_SStrategy_Update(uint16_t special_startegy, uint16_t *pos_x, uint16_t *pos_y); //雷达站专用策略UI绘制 private: /* 外部句柄 */ UART_HandleTypeDef *refereeUart; SystemTick_Fun Get_SystemTick; /*<! Pointer of function to get system tick */ uint8_t repeat_cnt = 0; //UI绘制重复发包 /* 发送数据包缓存区,最大128字节 */ uint8_t transmit_pack[128]; /* UI绘制数据包 */ uint8_t data_pack[DRAWING_PACK*7] = {0}; /* 客户端删除图形数据包 */ ext_client_custom_graphic_delete_t cleaning; /* 计算我方机器人ID */ void Calc_Robot_ID(uint8_t local_id); /* 解包过程用到的变量及函数 */ uint8_t DataCheck(uint8_t **p); //绘画时用于拼接的空间 unsigned char Get_CRC8_Check_Sum(unsigned char *pchMessage,unsigned int dwLength,unsigned char ucCRC8); //获取数据包包头的CRC8校验和 uint16_t Get_CRC16_Check_Sum(uint8_t *pchMessage,uint32_t dwLength,uint16_t wCRC); //获取数据包整包的CRC16校验和 void RefereeHandle(uint8_t *data_buf); //更新对应ID的数据 void RobotInteractiveHandle(robot_interactive_data_t* RobotInteractiveData_t); //机器人间通信 /* 发送时用到的 */ void pack_send_robotData(uint16_t _data_cmd_id, uint16_t _receiver_ID, uint8_t* _data, uint16_t _data_len); //0x301交互数据,包括UI绘制和车间通信 void send_toReferee(uint16_t _com_id, uint16_t length, receive_Type_e _receive_type); /** 具体图形的绘制:空操作、线、矩形、圆、椭圆、圆弧、浮点数、整数、字符;并指定绘制的图层 */ graphic_data_struct_t* null_drawing(uint8_t _layer,uint8_t name[]); graphic_data_struct_t* line_drawing(uint8_t _layer,drawOperate_e _operate_type,uint16_t startx,uint16_t starty,uint16_t endx,uint16_t endy, uint16_t line_width, colorType_e vcolor,uint8_t name[]); graphic_data_struct_t* rectangle_drawing(uint8_t _layer,drawOperate_e _operate_type, uint16_t startx,uint16_t starty,uint16_t length,uint16_t width, uint16_t line_width, colorType_e vcolor, uint8_t name[]); graphic_data_struct_t* circle_drawing(uint8_t _layer,drawOperate_e _operate_type, uint16_t centrex,uint16_t centrey,uint16_t r, uint16_t line_width, colorType_e vcolor, uint8_t name[]); graphic_data_struct_t* oval_drawing(uint8_t _layer,drawOperate_e _operate_type, uint16_t centrex,uint16_t centrey,uint16_t minor_semi_axis,uint16_t major_semi_axis, uint16_t line_width, colorType_e vcolor, uint8_t name[]); graphic_data_struct_t* arc_drawing(uint8_t _layer,drawOperate_e _operate_type, uint16_t centrex,uint16_t centrey,uint16_t minor_semi_axis,uint16_t major_semi_axis,int16_t start_angle,int16_t end_angle,uint16_t line_width,colorType_e vcolor, uint8_t name[]); graphic_data_struct_t* float_drawing(uint8_t _layer,drawOperate_e _operate_type, uint16_t startx,uint16_t starty,uint16_t size, uint16_t width,colorType_e vcolor, float data, uint8_t name[]); graphic_data_struct_t* int_drawing(uint8_t _layer, drawOperate_e _operate_type, uint16_t startx,uint16_t starty,uint16_t size, uint16_t width, colorType_e vcolor, int32_t data,uint8_t name[]); graphic_data_struct_t* character_drawing(uint8_t _layer,drawOperate_e _operate_type,uint16_t startx,uint16_t starty,uint16_t size, uint8_t width,uint8_t* data, uint16_t str_len, colorType_e vcolor, uint8_t name[]); }; #endif #endif /************************ COPYRIGHT(C) SCUT-ROBOTLAB **************************/
#pragma once #ifndef WIMGUI_WINDOW_H #define WIMGUI_WINDOW_H #include <stddef.h> #define IMGUI_DEFINE_MATH_OPERATORS #include "../imgui/imgui.h" #include "../imgui/imgui_internal.h" namespace wimgui { class docker; class window { bool visible = true; const char *title = nullptr; docker *dock = nullptr; ImGuiWindowFlags flags = 0; bool dockable = true; protected: ImVec2 size = ImVec2(0.0f, 0.0f); ImVec2 position = ImVec2(0.0f, 0.0f); public: window(const char* name); window(); ~window(); void show_title(bool show); void show_border(bool show); void allow_resize(bool allow); void allow_move(bool allow); void show_scrollbar(bool show); void allow_collapse(bool allow); void show_menu(bool show); void allow_mouse_scroll(bool allow); void auto_resize(bool allow); void save_settings(bool save); void allow_inputs(bool allow); void horizontal_scrollbar(bool allow); void always_horizontal_scrollbar(bool always); void always_vertical_scrollbar(bool always); void focus_on_appearing(bool allow); void to_front_on_focus(bool allow); void use_window_padding(bool allow); void set_flags(ImGuiWindowFlags _flags); virtual void show(bool _visible); virtual void draw(); virtual void init_draw() {} virtual void finish_draw() {} virtual void draw_imgui(); inline const char* get_title() { return title; }; float get_width(); void set_width(float width); float get_height(); void set_height(float height); ImVec2 get_size(); void set_size(float x, float y); ImVec2 get_position(); void set_position(float x, float y); float get_current_width(); float get_current_height(); ImRect get_content_rectangle(); bool is_collapsed(); bool mouse_double_clicked(int button_index=0); void set_collapsed(bool collapsed); inline bool is_moving() { ImGuiWindow* imgui_window = get_imgui_window(); return (GImGui->MovingWindow == imgui_window); } bool is_resizing(); void draw_vertical_text(const char* text, ImVec2 _position); //inline docker *docked_to() { return dock; } //inline void dock_to(docker *new_dock = nullptr) // { if (dockable) dock = new_dock; } //inline bool is_docked() { return dock != nullptr; } inline bool is_dockable() { return dockable; } inline void set_dockable(bool _dockable) { dockable = _dockable; } void set_cursor_position(ImVec2 _position); ImVec2 get_cursor_position(); ImGuiWindow *get_imgui_window(); }; class background_window : public window { ImVec4 normal_window_background; ImVec2 normal_window_padding; public: background_window(const char* title); ~background_window(); virtual void init_draw(); virtual void finish_draw(); private: void save_style(ImGuiStyle& style); void restore_style(ImGuiStyle& style); }; } #endif
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define S 20 #define T 20 int dp_1[S][T] = {0}; int dp_2[S][T][2] = {0}; int dp_3[S][T] = {0}; int dp_sumCommonPartString(string s , string t){ for (int i = 0; i < s.size(); i++) { for (int j = 0; j < t.size(); j++) { if(s[i] == t[j]){ dp_3[i + 1][j + 1] = dp_3[i][j + 1] + dp_3[i + 1][j] + 1; } else { dp_3[i + 1][j + 1] = dp_3[i][j + 1] + dp_3[i + 1][j] - dp_3[i][j]; } printf("[%d][%d]:%d ", i, j, dp_3[i + 1][j + 1]); } printf("\n"); } return dp_3[s.size()][t.size()]; } //input 二つの文字列, output 一致部分列の長さ(飛び飛びの部分列を許容する。) int dp_commonPartString(string s, string t){ //dp[0][*], dp[*][0]は値0の空間として使用 for (int i = 0; i < s.size(); i++) { for (int j = 0; j < t.size(); j++) { if(s[i] == t[j]){ dp_1[i + 1][j + 1] = dp_1[i][j] + 1; } else { dp_1[i + 1][j + 1] = max(dp_1[i][j + 1], dp_1[i + 1][j]); } printf("[%d][%d]:%d ", i, j, dp_1[i + 1][j + 1]); } printf("\n"); } return dp_1[s.size()][t.size()]; } //input 二つの文字列, output 一致部分列の長さ(飛び飛びの部分列を許容しない。) int dp_commonAreaString(string s, string t){ //dp[0][*], dp[*][0]は値0の空間として使用 int ans = 0; for (int i = 0; i < s.size(); i++) { for (int j = 0; j < t.size(); j++) { if(s[i] == t[j]){ if (dp_2[i][j][1] == 0){ dp_2[i + 1][j + 1][0] = dp_2[i][j][0] + 1; } else { dp_2[i + 1][j + 1][0] = 1; } } else { dp_2[i + 1][j + 1][1] = 1; dp_2[i + 1][j + 1][0] = max(dp_2[i][j + 1][0], dp_2[i + 1][j][0]); } ans = max(ans, dp_2[i + 1][j + 1][0]); printf("[%d][%d]:%d ", i, j, dp_2[i + 1][j + 1][0]); } printf("\n"); } return ans; } int main(){ //s:125643 //t:24638 string s = "23456"; string t = "24546"; // cin >> t; cout << "s: "<< s << ",t: "<< t << endl; cout << dp_commonPartString(s, t) << endl; cout << dp_commonAreaString(s, t) << endl; cout << dp_sumCommonPartString(s, t) + 1 << endl; }
#include <iostream> #include <string> #include "src/data.h" #include "src/decision_tree.h" #include "src/random_forest.h" #include "src/metrics.h" #include "src/time_measurement.h" int main() { std::string train_dataset_filename = "../data/train.csv"; std::string val_dataset_filename = "../data/val.csv"; dataset train_dataset; dataset val_dataset; read_dataset(train_dataset_filename, train_dataset); read_dataset(val_dataset_filename, val_dataset); auto start_time = get_current_time_fenced(); // Tree model(0.1, 10, true, 17); RandomForest model(20, 0.1, 20, 42, 4); model.fit(train_dataset); auto train_preds = model.predict(train_dataset.X); auto train_score = accuracy_score(train_dataset.y, train_preds); auto val_preds = model.predict(val_dataset.X); auto val_score = accuracy_score(val_dataset.y, val_preds); auto finish_time = get_current_time_fenced(); auto total_time = finish_time - start_time; std::cout << "total time, s: " << to_sec(total_time) << std::endl; std::cout << "train score: " << train_score << \ ", validation score: " << val_score << std::endl; return 0; }
#include "dbcontroler.h" QSqlDatabase DBControler::mydb; bool DBControler::OpenDB(){ if(mydb.isOpen()) return true; mydb=QSqlDatabase::addDatabase("QSQLITE"); mydb.setDatabaseName("dic.db"); if( !mydb.open() ){ qDebug() << "Open DB Error\n"; } /* QSqlQuery query(mydb); query.exec("create table person (id int primary key, " "firstname varchar(20), lastname varchar(20))"); query.exec("insert into person values(101, 'Danny', 'Young')"); query.exec("insert into person values(102, 'Christine', 'Holand')"); query.exec("insert into person values(103, 'Lars', 'Gordon')"); query.exec("insert into person values(104, 'Roberto', 'Robitaille')"); query.exec("insert into person values(105, 'Maria', 'Papadopoulos')"); query.exec("insert into person values(106, 'Danny', 'Young')"); query.exec("insert into person values(107, 'Christine', 'Holand')"); query.exec("insert into person values(108, 'Lars', 'Gordon')"); query.exec("insert into person values(109, 'Roberto', 'Robitaille')"); query.exec("insert into person values(110, 'Maria', 'Papadopoulos')"); query.exec("insert into person values(111, 'Danny', 'Young')"); query.exec("insert into person values(112, 'Christine', 'Holand')"); query.exec("insert into person values(113, 'Lars', 'Gordon')"); query.exec("insert into person values(114, 'Roberto', 'Robitaille')"); query.exec("insert into person values(115, 'Maria', 'Papadopoulos')"); query.exec("insert into person values(116, 'Danny', 'Young')"); query.exec("insert into person values(117, 'Christine', 'Holand')"); query.exec("insert into person values(118, 'Lars', 'Gordon')"); query.exec("insert into person values(119, 'Roberto', 'Robitaille')"); query.exec("insert into person values(120, 'Maria', 'Papadopoulos')"); */ return true; } bool DBControler::ExecuteSQL(QString sql){ qDebug() << sql; QSqlQuery query(mydb); return query.exec(sql); } bool DBControler::CreateZITable(){ ExecuteSQL("drop table zi"); return ExecuteSQL("create table zi (id integer primary key autoincrement, zi varchar(8), pinyin varchar(64), bihua int, bushou varchar(8))"); } bool DBControler::AddZItoTable(int id,QString zi,QString pinyin,QString bihua,QString bushou){ return ExecuteSQL("insert into zi values("+ QString::number(id,10) +", '" + zi +"', '"+ pinyin +"',"+bihua+",'"+ bushou +"')"); } bool DBControler::CloseDB(){ mydb.close(); return true; } bool DBControler::ShowTable(QString sql , QSqlTableModel *model){ model->setTable("zi"); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->select(); return true; } DBControler::DBControler() { }
#include "VariableEntryWidgetGTK.h" void VariableEntryWidgetGTK::onInternalDataChange() { onChangeSignal.emit(); } /************************************************************** * * StringVariableEntryWidgetGTK * * ************************************************************/ StringVariableEntryWidgetGTK::StringVariableEntryWidgetGTK(std::string initialValue) { widget.set_text(initialValue); widget.signal_changed().connect( sigc::mem_fun(*this, &VariableEntryWidgetGTK::onInternalDataChange) ); } std::string StringVariableEntryWidgetGTK::getStringValue() { return widget.get_text(); } Gtk::Widget *StringVariableEntryWidgetGTK::getWidget() { return &widget; } /************************************************************** * * BooleanVariableEntryWidgetGTK * * ************************************************************/ BooleanVariableEntryWidgetGTK::BooleanVariableEntryWidgetGTK(bool initialValue) { if (initialValue) { checkbox.set_active(true); } else { checkbox.set_active(false); } checkbox.signal_toggled().connect( sigc::mem_fun(*this, &VariableEntryWidgetGTK::onInternalDataChange) ); } std::string BooleanVariableEntryWidgetGTK::getStringValue() { if (checkbox.get_active()) { return "true"; } else { return "false"; } } Gtk::Widget *BooleanVariableEntryWidgetGTK::getWidget() { return &checkbox; } /************************************************************** * * FolderVariableEntryWidgetGTK * * ************************************************************/ FolderVariableEntryWidgetGTK::FolderVariableEntryWidgetGTK(std::string initialValue) { button.set_current_folder(initialValue); button.set_action(Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER); button.signal_file_set().connect( sigc::mem_fun(*this, &VariableEntryWidgetGTK::onInternalDataChange) ); } std::string FolderVariableEntryWidgetGTK::getStringValue() { return button.get_filename(); } Gtk::Widget *FolderVariableEntryWidgetGTK::getWidget() { return &button; } /************************************************************** * * FileVariableEntryWidgetGTK * * ************************************************************/ FileVariableEntryWidgetGTK::FileVariableEntryWidgetGTK(std::string initialValue) { button.set_filename(initialValue); button.set_action(Gtk::FILE_CHOOSER_ACTION_SAVE); button.signal_file_set().connect( sigc::mem_fun(*this, &VariableEntryWidgetGTK::onInternalDataChange) ); } std::string FileVariableEntryWidgetGTK::getStringValue() { return button.get_filename(); } Gtk::Widget *FileVariableEntryWidgetGTK::getWidget() { return &button; } /************************************************************** * * MultipleChoiceVariableEntryWidgetGTK * * ************************************************************/ MultipleChoiceVariableEntryWidgetGTK::MultipleChoiceVariableEntryWidgetGTK(std::vector<MultipleChoiceItem> *options, std::string initialValue) { comboBox.append("", "--"); int index = 1; int initialIndex = 0; for (MultipleChoiceItem option : *options) { if (option.value == initialValue) { initialIndex = index; } comboBox.append(option.value, option.label); index++; } comboBox.set_active(initialIndex); comboBox.signal_changed().connect( sigc::mem_fun(*this, &VariableEntryWidgetGTK::onInternalDataChange) ); } std::string MultipleChoiceVariableEntryWidgetGTK::getStringValue() { return comboBox.get_active_id(); } Gtk::Widget *MultipleChoiceVariableEntryWidgetGTK::getWidget() { return &comboBox; }
#include <iostream> #include <string> int main() { std::string firststr; getline(std::cin, firststr); std::string comarSeparator = ","; std::string witeSpace = " "; for (int i = 0; i < firststr.size(); ++i) { if (firststr[i]==comarSeparator[0]) { firststr[i]=witeSpace[0]; } } std::cout << firststr; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** This is the abstract interface class that's used for drawing the ** vector graphics. */ #ifndef SVGCANVAS_H #define SVGCANVAS_H #ifdef SVG_SUPPORT #include "modules/svg/src/SVGCanvasState.h" #include "modules/svg/src/SVGCache.h" #include "modules/libvega/vegatransform.h" #include "modules/libvega/vegapath.h" #include "modules/util/simset.h" class OpFont; class OpPainter; class OpBitmap; class OpBpath; class SVGRect; class SVGSurface; class SVGVector; /** * This is an abstract interface class to be implemented on your * platform. When rendering SVG content a SVGCanvas object is created * for doing the actual painting. SVGCanvasState keeps track of * current canvas properties. * * The class hierarchy looks like: * SVGCanvasState (in SVGCanvasState.{cpp,h}) * +-SVGCanvas * | +-SVGGeometryCanvas * | +-SVGCanvasVega * | +-SVGCanvasFakePainter * | +-SVGInvalidationCanvas * | +-SVGIntersectionCanvas * +-SVGNullCanvas * * Note that stroking should be centered around the contour given, * half on the inside, half on the outside. */ class SVGCanvas : public SVGCanvasState { public: enum RenderMode { RENDERMODE_DRAW = 0x00, ///< Draw to canvas RENDERMODE_INTERSECT_POINT = 0x01, ///< Intersect element with coordinate RENDERMODE_INTERSECT_RECT = 0x02, ///< Intersect element with rectangle RENDERMODE_ENCLOSURE = 0x03, ///< Elements enclosed by rectangle RENDERMODE_INVALID_CALC = 0x04 ///< Don't draw anything. Just calculate dirty rect. }; enum StencilMode { STENCIL_USE = 0x00, ///< Draw using current stencil STENCIL_CONSTRUCT = 0x01 ///< Construct a stencil }; enum ImageRenderQuality { IMAGE_QUALITY_LOW, IMAGE_QUALITY_NORMAL, IMAGE_QUALITY_HIGH }; virtual ~SVGCanvas(){} /** * Set the base scale factor for the canvas. This roughly * translates to the scale factor of the target visual device. */ void SetBaseScale(SVGNumber base_scale) { m_base_scale = base_scale; } /** * Get the base scale factor for the canvas. */ SVGNumber GetBaseScale() const { return m_base_scale; } /** * Resets the transform to the base transform (used for * ref-transform) */ void ResetTransform() { GetTransform().LoadScale(m_base_scale, m_base_scale); } /** * Sets the anti-aliasing quality. A value of 0 disables anti-aliasing. * * @return OpStatus::OK if successful */ virtual OP_STATUS SetAntialiasingQuality(unsigned int quality) { return OpStatus::OK; } /** * Get the estimated amount of memory used by the canvas. * (Currently only the buffer from the root-surface). * @return Size (in bytes) used. */ virtual unsigned int GetMemUsed() { return 0; } /** * Destroy resources associated with the canvas, such as * clips/masks/transparency layers. To be used if a canvas from * an aborted rendering needs to reused. */ virtual void Clean() {} #ifdef SVG_SUPPORT_STENCIL /** * Create a rectangular clipping region. * Is equivalent to a sequence BeginClip() / DrawRect(cliprect) / EndClip(). * * @return OpStatus::OK if successful */ virtual OP_STATUS AddClipRect(const SVGRect& cliprect) = 0; /** * Begin defining a clipping region. All subsequent drawing * operations until EndClip() will be used to define the * region. The clipping will be intersected with the previous * clipping region if any. The old clipregion is saved on a * stack, for restoring when RemoveClip is called. * * @return OpStatus::OK if successful */ virtual OP_STATUS BeginClip() = 0; /** * All drawing commands between a BeginClip and an EndClip will be * used for clipping. EndClip sets the clipping, so after this * call the clipping is active. Needs to be balaced with * BeginClip. */ virtual void EndClip() = 0; /** * Remove the current clippath from the stack and set the previous one. * * @return OpStatus::OK if successful */ virtual void RemoveClip() = 0; #endif // SVG_SUPPORT_STENCIL #ifdef SVG_SUPPORT_STENCIL /** * Begin a defining mask. Create a new off-screen buffer where all * the drawing operations until EndMask() will be rendered. The * previous mask is saved on a stack, and is restored when * RemoveMask() is called. * * @return OpStatus::OK if successful */ virtual OP_STATUS BeginMask() { return OpStatus::OK; } /** * End the definition of a mask. EndMask() sets the mask, so after * this call, the mask will be set. Needs to be balanced with * BeginMask(). */ virtual void EndMask() {} /** * Removes the current mask from the stack and sets the previous one. * * @return OpStatus::OK if successful */ virtual void RemoveMask() {} #endif // SVG_SUPPORT_STENCIL /** * Return the current render mode */ RenderMode GetRenderMode() const { return m_render_mode; } #ifdef SVG_SUPPORT_STENCIL /** * Return the current clipping mode */ StencilMode GetClipMode() const { return m_clip_mode; } /** * Sets the clipping mode, only for the brave. */ void SetClipMode(StencilMode mode) { m_clip_mode = mode; } /** * Return the current mask mode */ StencilMode GetMaskMode() const { return m_mask_mode; } /** * Sets the mask mode, only for the brave. */ void SetMaskMode(StencilMode mode) { m_mask_mode = mode; } #endif // SVG_SUPPORT_STENCIL /** * Tests the current render mode is one of the intersection modes * * @return Returns TRUE if the current render mode is an intersection mode */ BOOL IsIntersectionMode() { return m_render_mode == RENDERMODE_INTERSECT_POINT || m_render_mode == RENDERMODE_INTERSECT_RECT || m_render_mode == RENDERMODE_ENCLOSURE; } /** * Get the current intersectionpoint. * * @return Return the intersectionpoint passed in through SetIntersectionMode. */ virtual const SVGNumberPair& GetIntersectionPoint() = 0; /** * Get the current intersectionpoint in (truncated) integer form. * * @return Return the intersectionpoint passed in through SetIntersectionMode. */ virtual const OpPoint& GetIntersectionPointInt() = 0; /** * Clears the canvas with the color specified. * * For this to have an effect, you'd need a canvas that actually * paints. * * @param r The value for red (0 - 255) * @param g The value for green (0 - 255) * @param b The value for blue (0 - 255) * @param a The value for alpha (0 - 255). 255 means opaque, 0 means transparent */ virtual void Clear(UINT8 r, UINT8 g, UINT8 b, UINT8 a, const OpRect* clear_rect = NULL) {} /** * Draws a line between the points (x1,y1), (x2,y2). * * Coordinate values are in userspace units, which means they are * affected by the current transformation matrix. * * NOTE: DrawLine should only stroke the line, not fill it. This * is what the SVG spec says: "Because 'line' elements are single * lines and thus are geometrically one-dimensional, they have no * interior; thus, 'line' elements are never filled (see the * 'fill' property)" * * @param x1 Start x * @param y1 Start y * @param x2 End x * @param y2 End y */ virtual OP_STATUS DrawLine(SVGNumber x1, SVGNumber y1, SVGNumber x2, SVGNumber y2) = 0; /** * Draws a rectangle with it's left upper corner in (x,y) with * width and height (w,h) and optional rounded corners. * * Coordinate values are in userspace units, which means they are * affected by the current transformation matrix. * * @param x Left upper corner x * @param y Left upper corner y * @param w Width of rectangle * @param h Height of rectangle * @param rx If 0 then the corners will be straight, if > 0 then that specifies the x radius * @param ry If 0 then the corners will be straight, if > 0 then that specifies the y radius */ virtual OP_STATUS DrawRect(SVGNumber x, SVGNumber y, SVGNumber w, SVGNumber h, SVGNumber rx, SVGNumber ry) = 0; /** * Draws an ellipse centered in the point (x,y) with radius (rx,ry). * * Coordinate values are in userspace units, which means they are * affected by the current transformation matrix. * * @param x Center x * @param y Center y * @param rx The x radius * @param ry The y radius */ virtual OP_STATUS DrawEllipse(SVGNumber x, SVGNumber y, SVGNumber rx, SVGNumber ry) = 0; /** * Draws a polygon shape, which means move to the first * coordinate, then connect the dots with straight lines. * * Coordinate values are in userspace units, which means they are * affected by the current transformation matrix. * * @param points An array of points, the first coordinate is (x,y) = (points[0],points[1]), the second is (points[2],points[3]) and so on. * @param closed Flag indicating whether the polygon should be explicitly closed. */ virtual OP_STATUS DrawPolygon(const SVGVector& list, BOOL closed) = 0; /** * Draws a path, that may consist of straight lines, 2nd or 3rd * degree Bezier curves, and arcs. If that sounds complicated, * relax, OpBpath is your friend and can convert those curves to * straight lines. * * Coordinate values are in userspace units, which means they are * affected by the current transformation matrix. * * @param path The path * @param path_length A user-specified value for how long the path is, -1 means not specified */ virtual OP_STATUS DrawPath(const OpBpath *path, SVGNumber path_length = -1) = 0; /** * Draws a bitmap. * * Coordinate values are in userspace units, which means they are * affected by the current transformation matrix. * * @param bitmap/surface The bitmap/surface * @param source The source rectangle * @param dest The destination rectangle * @param quality The interpolation quality to use */ virtual OP_STATUS DrawImage(OpBitmap* bitmap, const OpRect& source, const SVGRect& dest, ImageRenderQuality quality) = 0; virtual OP_STATUS DrawImage(SVGSurface* surface, const OpRect& source, const SVGRect& dest, ImageRenderQuality quality) = 0; /** * Set the rect which we expect to be painting on. This generally * equals the 'screen box' of a text-root. * * This rect will be used by GetPainter(unsigned int). */ virtual void SetPainterRect(const OpRect& rect) = 0; /** * Get an OpPainter for the canvas. This is used to draw systemfonts. * Only one active painter is allowed at any one time for a canvas. * The painter must be released with ReleasePainter(). * * @param font_overhang Overhang compensation * @return ERR if not supported, OK if success. */ virtual OP_STATUS GetPainter(unsigned int font_overhang) = 0; /** * Get an OpPainter for the canvas. * Only one active painter is allowed at any one time for a canvas. * The painter must be released with ReleasePainter(). * * This will do an implicit SetPainterRect with rect. * * @param rect The smallest interesting region. * @param painter The painter will be returned here. * @return ERR if not supported, OK if success. */ virtual OP_STATUS GetPainter(const OpRect& rect, OpPainter*& painter) = 0; /** * Releases the painter that was returned from GetPainter(). * * @param resultbitmap If NULL then data should be copied back, if non-NULL then the resulting * bitmap is desired instead. */ virtual void ReleasePainter() = 0; virtual BOOL IsPainterActive() = 0; virtual void DrawStringPainter(OpFont* font, const OpPoint& pos, uni_char* text, UINT32 len, INT32 extra_char_spacing, int* caret_x = NULL) = 0; virtual void DrawSelectedStringPainter(const OpRect& selected, COLORREF sel_bg_color, COLORREF sel_fg_color, OpFont* font, const OpPoint& pos, uni_char* text, UINT32 len, INT32 extra_char_spacing) = 0; /** * Returns the parts of the canvas (in fixed canvas/pixel * coordinates) that has been rendered to since the last call to * ResetDirtyRect. This may return a too big area (which will * reduce the usefulness of other optimizations) but never a too * small one. * * Should only be used during invalidation/layout-passes, and as * such belongs in the SVGInvalidationCanvas. */ virtual OpRect GetDirtyRect() { return OpRect(); } /** * This is to tell the canvas about things that will make an area * dirty without passing through the Canvas. For example system * fonts which copy a bitmap on top on the canvas. * * Should only be used during invalidation/layout-passes, and as * such belongs in the SVGInvalidationCanvas. * * @param new_dirty_area The rect that should be marked dirty. */ virtual void AddToDirtyRect(const OpRect& new_dirty_area) {} /** * Clears the "dirty rect". See the documentation of GetDirtyRect. * * Should only be used during invalidation/layout-passes, and as * such belongs in the SVGInvalidationCanvas. */ virtual void ResetDirtyRect() {} /** * Check if the given rect intersects the hard clip area. * If no hard clip area has been set TRUE should be returned. */ virtual BOOL IsVisible(const OpRect& rect) { return TRUE; } /** * Check if the given rect is fully contained inside the hard clip area. * If no hard clip area has been set FALSE should be returned. */ virtual BOOL IsContainedBy(const OpRect& rect) { return FALSE; } #ifdef SVG_SUPPORT_STENCIL /** * Clips the given rect against the current stencil. */ virtual void ApplyClipToRegion(OpRect& iorect) {} #endif // SVG_SUPPORT_STENCIL #if defined SVG_SUPPORT_MEDIA && defined PI_VIDEO_LAYER /** Check if it is safe to use Video Layer "overlays". */ virtual BOOL UseVideoOverlay() { return FALSE; } #endif // defined SVG_SUPPORT_MEDIA && defined PI_VIDEO_LAYER protected: SVGCanvas() : m_base_scale(1), m_render_mode(RENDERMODE_DRAW), m_clip_mode(STENCIL_USE), m_mask_mode(STENCIL_USE) {} SVGNumber m_base_scale; RenderMode m_render_mode; StencilMode m_clip_mode; StencilMode m_mask_mode; }; /** * Intermediary helper class which converts primitive calls into * actual rendering geometry (using VEGAPath/VEGAPrimitive) and pass * that along to a ProcessPrimitive-hook which subclasses need to * implement. * Also handles stroke and pointer-events (if required by concrete class). */ class SVGGeometryCanvas : public SVGCanvas { public: SVGGeometryCanvas(BOOL use_pointer_events) : m_use_pointer_events(use_pointer_events) {} #ifdef SVG_SUPPORT_STENCIL virtual OP_STATUS AddClipRect(const SVGRect& cliprect); virtual OP_STATUS BeginClip() = 0; virtual void EndClip() = 0; virtual void RemoveClip() = 0; #endif // SVG_SUPPORT_STENCIL virtual OP_STATUS DrawLine(SVGNumber x1, SVGNumber y1, SVGNumber x2, SVGNumber y2); virtual OP_STATUS DrawRect(SVGNumber x, SVGNumber y, SVGNumber w, SVGNumber h, SVGNumber rx, SVGNumber ry); virtual OP_STATUS DrawEllipse(SVGNumber x, SVGNumber y, SVGNumber rx, SVGNumber ry); virtual OP_STATUS DrawPolygon(const SVGVector& list, BOOL closed); virtual OP_STATUS DrawPath(const OpBpath *path, SVGNumber path_length = -1); virtual OP_STATUS DrawImage(OpBitmap* bitmap, const OpRect& source, const SVGRect& dest, ImageRenderQuality quality); virtual OP_STATUS DrawImage(SVGSurface* bitmap_surface, const OpRect& source, const SVGRect& dest, ImageRenderQuality quality); BOOL IsPointerEventsSensitive(int type) { return m_use_pointer_events && AllowPointerEvents(type); } protected: struct VPrimitive { VEGAPath* vpath; VEGAPrimitive* vprim; enum GeometryType { GEOM_FILL, GEOM_STROKE, GEOM_IMAGE }; GeometryType geom_type; BOOL do_intersection_test; }; virtual OP_STATUS ProcessPrimitive(VPrimitive& prim) = 0; OP_STATUS CreateStrokePath(VEGAPath& vpath, VEGAPath& vstrokepath, VEGA_FIX precompPathLength = VEGA_INTTOFIX(-1)); OP_STATUS ProcessImage(const SVGRect& dest); OP_STATUS FillStrokePath(VEGAPath& vpath, VEGA_FIX pathLength); OP_STATUS FillStrokePrimitive(VEGAPrimitive& vprimitive); void SetVegaTransform(); VEGATransform m_vtransform; BOOL m_use_pointer_events; }; /** * Intermediary helper class which keeps a stateful (but dummy) * implementation for the different *Painter* methods. */ class SVGCanvasFakePainter : public SVGGeometryCanvas { public: SVGCanvasFakePainter() : SVGGeometryCanvas(TRUE), m_painter_active(FALSE) {} virtual void SetPainterRect(const OpRect& rect) {} virtual OP_STATUS GetPainter(unsigned int font_overhang) { m_painter_active = TRUE; return OpStatus::OK; } virtual OP_STATUS GetPainter(const OpRect& rect, OpPainter*& painter) { return OpStatus::ERR; } virtual void ReleasePainter() { m_painter_active = FALSE; } virtual BOOL IsPainterActive() { return m_painter_active; } protected: BOOL m_painter_active; }; /** * SVGCanvas implementation used during intersection-testing. Tracks * resources in the form of geometric shapes and performs * intersection-testing ("hit-testing") on said geometry. * (previously available as RENDERMODE_INTERSECT* in SVGCanvasVega) */ class SVGIntersectionCanvas : public SVGCanvasFakePainter { public: virtual ~SVGIntersectionCanvas(); void SetIntersectionMode(const SVGNumberPair& intersection_point); void SetIntersectionMode(const SVGRect& intersection_rect); void SetEnclosureMode(const SVGRect& intersection_rect); /** * Set a list to add intersected elements to * * @param lst List to which intersected elements will be added */ void SetSelectionList(OpVector<HTML_Element>* lst) { m_selected_list = lst; } /** * Adds the current element to the list of selected items */ void SelectCurrentElement() { if (m_selected_list) m_selected_list->Add(m_current.element); } virtual void Clean(); virtual void DrawStringPainter(OpFont* font, const OpPoint& pos, uni_char* text, UINT32 len, INT32 extra_char_spacing, int* caret_x = NULL); virtual void DrawSelectedStringPainter(const OpRect& selected, COLORREF sel_bgcolor, COLORREF sel_fgcolor, OpFont* font, const OpPoint& pos, uni_char* text, UINT32 len, INT32 extra_char_spacing); virtual const SVGNumberPair& GetIntersectionPoint() { return m_intersection_point; } virtual const OpPoint& GetIntersectionPointInt() { return m_intersection_point_i; } #ifdef SVG_SUPPORT_STENCIL virtual OP_STATUS BeginClip(); virtual void EndClip(); virtual void RemoveClip(); // SVGClipPathInfo needs to be declared public to be able to use // this struct inside SVGClipPathSet Used for intersection testing struct SVGClipPathInfo : public ListElement<SVGClipPathInfo> { SVGClipPathInfo(SVGFillRule rule) : clip_rule(rule) {} VEGAPath path; SVGFillRule clip_rule; }; #endif // SVG_SUPPORT_STENCIL protected: virtual OP_STATUS ProcessPrimitive(VPrimitive& prim); #ifdef SVG_SUPPORT_STENCIL struct SVGClipPathSet : public ListElement<SVGClipPathSet> { SVGClipPathSet(StencilMode in_prev_mode) : prev_mode(in_prev_mode) {} AutoDeleteList<SVGClipPathInfo> paths; StencilMode prev_mode; }; AutoDeleteList<SVGClipPathSet> m_active_clipsets; AutoDeleteList<SVGClipPathSet> m_partial_clipsets; BOOL IntersectClip(); #endif // SVG_SUPPORT_STENCIL void IntersectPath(VEGAPath* path, SVGFillRule fillrule); SVGNumberPair m_intersection_point; OpPoint m_intersection_point_i; SVGRect m_intersection_rect; // Used for RENDERMODE_INTERSECT_RECT and RENDERMODE_ENCLOSURE OpVector<HTML_Element>* m_selected_list; ///< List of selected elements }; /** * SVGCanvas implementation used during invalidation/layout. Does * little except track resources using during invalidation, and * calculate extents for primitives drawn. * (previously available as RENDERMODE_INVALIDATION_CALC in SVGCanvasVega). */ class SVGInvalidationCanvas : public SVGCanvasFakePainter { public: SVGInvalidationCanvas() : SVGCanvasFakePainter() { m_render_mode = RENDERMODE_INVALID_CALC; } virtual void Clean(); virtual void DrawStringPainter(OpFont* font, const OpPoint& pos, uni_char* text, UINT32 len, INT32 extra_char_spacing, int* caret_x = NULL); virtual void DrawSelectedStringPainter(const OpRect& selected, COLORREF sel_bgcolor, COLORREF sel_fgcolor, OpFont* font, const OpPoint& pos, uni_char* text, UINT32 len, INT32 extra_char_spacing); virtual const SVGNumberPair& GetIntersectionPoint() { return m_dummy_numpair; } virtual const OpPoint& GetIntersectionPointInt() { return m_dummy_point; } #ifdef SVG_SUPPORT_STENCIL virtual OP_STATUS BeginClip(); virtual void EndClip(); virtual void RemoveClip(); virtual OP_STATUS BeginMask(); virtual void EndMask(); virtual void RemoveMask(); virtual void ApplyClipToRegion(OpRect& region); #endif // SVG_SUPPORT_STENCIL virtual OpRect GetDirtyRect(); virtual void AddToDirtyRect(const OpRect& new_dirty_area); virtual void ResetDirtyRect(); protected: virtual OP_STATUS ProcessPrimitive(VPrimitive& prim); #ifdef SVG_SUPPORT_STENCIL public: // Stencil needs to be declared public to be able to use // this struct inside StencilState: struct Stencil : public ListElement<Stencil> { Stencil(StencilMode in_prev_mode) : prev_mode(in_prev_mode) {} OpRect area; StencilMode prev_mode; }; protected: AutoDeleteList<Stencil> m_active_clips; AutoDeleteList<Stencil> m_partial_clips; AutoDeleteList<Stencil> m_active_masks; AutoDeleteList<Stencil> m_partial_masks; #endif // SVG_SUPPORT_STENCIL OpRect m_dirty_area; SVGNumberPair m_dummy_numpair; OpPoint m_dummy_point; }; /** * This is an implementation of the SVGCanvas interface that is * supposed to do nothing in most cases. This can be used in all cases * where a canvas is needed (traversing), but the actual contents, or * what ends up on the canvas is not of interest (since it still * inherits from SVGCanvasState, state-handling will still work as * expected though). */ class SVGNullCanvas : public SVGCanvas { public: #ifdef SVG_SUPPORT_STENCIL virtual OP_STATUS AddClipRect(const SVGRect& cliprect) { return OpStatus::OK; } virtual OP_STATUS BeginClip() { return OpStatus::OK; } virtual void EndClip() {} virtual void RemoveClip() {} #endif // SVG_SUPPORT_STENCIL virtual const SVGNumberPair& GetIntersectionPoint() { return m_dummy_isect_pt; } virtual const OpPoint& GetIntersectionPointInt() { return m_dummy_isect_pti; } virtual OP_STATUS DrawLine(SVGNumber x1, SVGNumber y1, SVGNumber x2, SVGNumber y2) { return OpStatus::OK; } virtual OP_STATUS DrawRect(SVGNumber x, SVGNumber y, SVGNumber w, SVGNumber h, SVGNumber rx, SVGNumber ry) { return OpStatus::OK; } virtual OP_STATUS DrawEllipse(SVGNumber x, SVGNumber y, SVGNumber rx, SVGNumber ry) { return OpStatus::OK; } virtual OP_STATUS DrawPolygon(const SVGVector &list, BOOL closed) { return OpStatus::OK; } virtual OP_STATUS DrawPath(const OpBpath *path, SVGNumber path_length = -1) { return OpStatus::OK; } virtual OP_STATUS DrawImage(OpBitmap* bitmap, const OpRect& source, const SVGRect& dest, ImageRenderQuality quality) { return OpStatus::OK; } virtual OP_STATUS DrawImage(SVGSurface* bitmap_surface, const OpRect& source, const SVGRect& dest, ImageRenderQuality quality) { return OpStatus::OK; } virtual void SetPainterRect(const OpRect& rect) {} virtual OP_STATUS GetPainter(unsigned int font_overhang) { return OpStatus::OK; } virtual OP_STATUS GetPainter(const OpRect& rect, OpPainter*& painter) { return OpStatus::OK; } virtual void ReleasePainter() {} virtual BOOL IsPainterActive() { return FALSE; } // FIXME: Need to track this? virtual void DrawStringPainter(OpFont* font, const OpPoint& pos, uni_char* text, UINT32 len, INT32 extra_char_spacing, int* caret_x = NULL) {} virtual void DrawSelectedStringPainter(const OpRect& selected, COLORREF sel_bg_color, COLORREF sel_fg_color, OpFont* font, const OpPoint& pos, uni_char* text, UINT32 len, INT32 extra_char_spacing) {} private: SVGNumberPair m_dummy_isect_pt; OpPoint m_dummy_isect_pti; }; #endif // SVG_SUPPORT #endif // SVGCANVAS_H
// // Search.hpp // A_STAR // // Created by Reb and Santi on 1/30/18 // Copyright 2018 Smols. All rights reserved. // #ifndef Search_hpp #define Search_hpp class Search { private: Graph g; public: Search(Graph g) : g(g) {}; friend std::ostream &operator<<(std::ostream &os, Search &s); std::vector<std::string> execute(Graph g); //std::vector<std::string> get_path(std::string n, std::map<std::string, Node> nodes); std::vector<std::string> get_path(std::string end, std::map<std::string, std::string> parents); }; #endif /* Search_hpp */
#ifndef SENDER_H #define SENDER_H #include <QWidget> #include <QtNetwork> #include <QFont> #include <QDebug> #include "m580_button.h" #include "ui_sender.h" class Sender : public QWidget, private Ui::Sender { Q_OBJECT public: Sender(); ~Sender(); void WriteText(QString text); void setroot(bool c); bool getroot(); private slots: void on_btnbind_clicked(); void on_command_returnPressed(); void donneesRecues(); private: QUdpSocket *socket; // Représente le serveur quint16 tailleMessage; QString message; QString display; bool root =0; }; #endif // SENDER_H
#include <cppunit/extensions/HelperMacros.h> #include "cppunit/BetterAssert.h" #include "util/ClassInfo.h" using namespace std; namespace BeeeOn { class ClassInfoTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ClassInfoTest); CPPUNIT_TEST(testEmptyConstructor); CPPUNIT_TEST(testConstruct); CPPUNIT_TEST(testForPointerNull); CPPUNIT_TEST(testId); CPPUNIT_TEST(testName); CPPUNIT_TEST(testNameWithInheritance); CPPUNIT_TEST(testIs); CPPUNIT_TEST(testByName); CPPUNIT_TEST_SUITE_END(); public: void testEmptyConstructor(); void testConstruct(); void testForPointerNull(); void testId(); void testName(); void testNameWithInheritance(); void testIs(); void testByName(); }; CPPUNIT_TEST_SUITE_REGISTRATION(ClassInfoTest); class TestObject0 { }; class TestObject1 { }; void ClassInfoTest::testEmptyConstructor() { ClassInfo info0 = ClassInfo::forClass<TestObject0>(); ClassInfo info1 = ClassInfo::forClass<TestObject0>(); ClassInfo info2 = ClassInfo::forClass<TestObject1>(); CPPUNIT_ASSERT(info0 == info1); CPPUNIT_ASSERT(info0 != info2); CPPUNIT_ASSERT(info1 != info2); } void ClassInfoTest::testConstruct() { TestObject0 o0; TestObject1 o1; ClassInfo info0(typeid(o0)); ClassInfo info1(typeid(o1)); ClassInfo info2(typeid(TestObject0)); ClassInfo info3(typeid(TestObject1)); ClassInfo info4(o0); ClassInfo info5(o1); ClassInfo info6 = ClassInfo::forPointer(&o0); ClassInfo info7 = ClassInfo::forPointer(&o1); CPPUNIT_ASSERT(info0 == info2); CPPUNIT_ASSERT(info2 == info4); CPPUNIT_ASSERT(info4 == info6); CPPUNIT_ASSERT(info1 == info3); CPPUNIT_ASSERT(info3 == info5); CPPUNIT_ASSERT(info5 == info7); CPPUNIT_ASSERT(info0 != info1); CPPUNIT_ASSERT(info2 != info3); CPPUNIT_ASSERT(info4 != info5); CPPUNIT_ASSERT(info6 != info7); } void ClassInfoTest::testForPointerNull() { TestObject0 *o = NULL; CPPUNIT_ASSERT(ClassInfo::forPointer(o) == ClassInfo()); } void ClassInfoTest::testId() { TestObject0 o; ClassInfo info0(typeid(o)); ClassInfo info1(typeid(TestObject0)); ClassInfo info2(o); ClassInfo info3 = ClassInfo::forPointer(&o); CPPUNIT_ASSERT_EQUAL("N6BeeeOn11TestObject0E", info0.id()); CPPUNIT_ASSERT_EQUAL("N6BeeeOn11TestObject0E", info1.id()); CPPUNIT_ASSERT_EQUAL("N6BeeeOn11TestObject0E", info2.id()); CPPUNIT_ASSERT_EQUAL("N6BeeeOn11TestObject0E", info3.id()); } void ClassInfoTest::testName() { TestObject0 o; ClassInfo info0(typeid(o)); ClassInfo info1(typeid(TestObject0)); ClassInfo info2(o); ClassInfo info3 = ClassInfo::forPointer(&o); CPPUNIT_ASSERT_EQUAL("BeeeOn::TestObject0", info0.name()); CPPUNIT_ASSERT_EQUAL("BeeeOn::TestObject0", info1.name()); CPPUNIT_ASSERT_EQUAL("BeeeOn::TestObject0", info2.name()); CPPUNIT_ASSERT_EQUAL("BeeeOn::TestObject0", info3.name()); } class A { public: virtual ~A() {} }; class B { public: }; class C : public A { public: }; class D : public B { public: }; class E : public A, public B { public: }; void ClassInfoTest::testNameWithInheritance() { A a; B b; C c; D d; E e; A &cAsA = c; B &dAsB = d; A &eAsA = e; B &eAsB = e; CPPUNIT_ASSERT("BeeeOn::A" == ClassInfo(typeid(a)).name()); CPPUNIT_ASSERT("BeeeOn::B" == ClassInfo(typeid(b)).name()); CPPUNIT_ASSERT("BeeeOn::C" == ClassInfo(typeid(c)).name()); CPPUNIT_ASSERT("BeeeOn::D" == ClassInfo(typeid(d)).name()); CPPUNIT_ASSERT("BeeeOn::E" == ClassInfo(typeid(e)).name()); CPPUNIT_ASSERT("BeeeOn::C" == ClassInfo(typeid(cAsA)).name()); CPPUNIT_ASSERT("BeeeOn::B" == ClassInfo(typeid(dAsB)).name()); CPPUNIT_ASSERT("BeeeOn::E" == ClassInfo(typeid(eAsA)).name()); CPPUNIT_ASSERT("BeeeOn::B" == ClassInfo(typeid(eAsB)).name()); CPPUNIT_ASSERT("BeeeOn::A" == ClassInfo(typeid(&a)).name()); CPPUNIT_ASSERT("BeeeOn::B" == ClassInfo(typeid(&b)).name()); CPPUNIT_ASSERT("BeeeOn::C" == ClassInfo(typeid(&c)).name()); CPPUNIT_ASSERT("BeeeOn::D" == ClassInfo(typeid(&d)).name()); CPPUNIT_ASSERT("BeeeOn::E" == ClassInfo(typeid(&e)).name()); CPPUNIT_ASSERT("BeeeOn::A" == ClassInfo(typeid(&cAsA)).name()); CPPUNIT_ASSERT("BeeeOn::B" == ClassInfo(typeid(&dAsB)).name()); CPPUNIT_ASSERT("BeeeOn::A" == ClassInfo(typeid(&eAsA)).name()); CPPUNIT_ASSERT("BeeeOn::B" == ClassInfo(typeid(&eAsB)).name()); } void ClassInfoTest::testIs() { ClassInfo info(typeid(A)); CPPUNIT_ASSERT(info.is<A>()); CPPUNIT_ASSERT(!info.is<B>()); CPPUNIT_ASSERT(!info.is<C>()); A a; CPPUNIT_ASSERT(ClassInfo::forPointer(&a).is<A>()); CPPUNIT_ASSERT(!ClassInfo::forPointer(&a).is<B>()); CPPUNIT_ASSERT(!ClassInfo::forPointer(&a).is<C>()); CPPUNIT_ASSERT(ClassInfo::forClass<A>().is<A>()); CPPUNIT_ASSERT(!ClassInfo::forClass<A>().is<B>()); CPPUNIT_ASSERT(!ClassInfo::forClass<A>().is<C>()); } } BEEEON_CLASS(BeeeOn::TestObject0) namespace BeeeOn { void ClassInfoTest::testByName() { ClassInfo info = ClassInfo::byName("BeeeOn::TestObject0"); CPPUNIT_ASSERT_EQUAL("BeeeOn::TestObject0", info.name()); CPPUNIT_ASSERT(type_index(typeid(TestObject0)) == info.index()); ClassInfo::registerClass<TestObject1>("xxx"); ClassInfo xxx = ClassInfo::byName("xxx"); CPPUNIT_ASSERT_EQUAL("BeeeOn::TestObject1", xxx.name()); CPPUNIT_ASSERT(type_index(typeid(TestObject1)) == xxx.index()); } }
/* kamalsam */ #include<iostream> #include<stdio.h> using namespace std; int main() { int n,t,i; scanf("%d",&t); for(i=0;i<t;i++) { scanf("%d",&n); printf("%d\n",max(0,n-2)); } return 0; }
#include "MyImage.h" CMyImage::CMyImage(void) { m_pImage = NULL; } CMyImage::~CMyImage(void) { if (m_pImage) delete m_pImage; m_pImage = NULL; } void CMyImage::Load(char *lpstrFile) { if (m_pImage) delete m_pImage; WCHAR file[MAX_PATH]; MultiByteToWideChar(CP_ACP, NULL, lpstrFile, -1, file, MAX_PATH); m_pImage = Image::FromFile(file); } void CMyImage::Draw(Graphics *g, int x, int y) { g->DrawImage(m_pImage, x, y); } void CMyImage::DrawCenter(Graphics *g, int x, int y, int xCenter, int yCenter) { x = x - (xCenter / 72.0f * 96.0f); y = y - (yCenter / 72.0f * 96.0f); g->DrawImage(m_pImage, x, y, 0, 0, m_pImage->GetWidth(), m_pImage->GetHeight(), Gdiplus::UnitPixel); } void CMyImage::Draw(Graphics *g, int x, int y, int width, int height) { g->DrawImage(m_pImage, x, y, width, height); } void CMyImage::Draw(Graphics *g, int dstX, int dstY, int srcX, int srcY, int width, int height) { g->DrawImage(m_pImage, dstX, dstY, srcX, srcY, width, height, Gdiplus::UnitPixel); }
#include "2-1.h" #include <stdlib.h> #define STACK_MAX 10 char stack[STACK_MAX]; int top = -1; int Precedence(char ch) { switch (ch) { case '+': return 12; break; case '-': return 12; break; case '*': return 13; break; case '/': return 13; break; default: return 0; } } char POP() { return stack[top--]; } void PUSH(char val) { stack[++top]= val; } int main() { char InfixEq[10] = "6/2-3+4*2"; char PostEq[10] = { 0 }; int j = 0; //POP(); //PUSH('+'); for (int i = 0; i < 9; i++) { if (Precedence(InfixEq[i]) == 0) PostEq[j++] = InfixEq[i]; else if (Precedence(InfixEq[i]) <= Precedence(stack[top])) { PostEq[j++]=POP(); PUSH(InfixEq[i]); } else { PUSH(InfixEq[i]); } } while (top != -1) { PostEq[j++]=POP(); } cout << PostEq << endl; return 0; }
// https://oj.leetcode.com/problems/multiply-strings/ class Solution { string add(vector<string> &strs) { int carry = 0; string ret = ""; int idx = 0; while (true) { bool processed_all = true; int sum = carry; for (int i = 0; i < strs.size(); i++) { if (idx >= strs[i].size()) { continue; } processed_all = false; sum += (strs[i][idx] - '0'); } if (processed_all) { break; } int cur_digit = sum % 10; carry = sum / 10; ret = static_cast<char>(cur_digit + '0') + ret; idx++; } while (carry > 0) { int digit = carry % 10; ret = static_cast<char>(digit + '0') + ret; carry = carry / 10; } // removing heading 0s int i = 0; while (i < ret.size()) { if (ret[i] != '0') { break; } i++; } return (i == ret.size()) ? "0" : ret.substr(i); } public: string multiply(string num1, string num2) { int size1 = num1.size(), size2 = num2.size(); if (size1 == 0 || size2 == 0) { return ""; } vector<string> lines; int zero_paddings = 0; for (int i = size1 - 1; i >= 0; i--) { string cur_line = ""; int carry = 0; for (int j = size2 - 1; j >= 0; j--) { int d1 = num1[i] - '0'; int d2 = num2[j] - '0'; int tmp = d1 * d2 + carry; int digit = tmp % 10; carry = tmp / 10; cur_line += static_cast<char>(digit + '0'); } if (carry != 0) { cur_line += static_cast<char>(carry + '0'); } for (int j = 0; j < zero_paddings; j++) { cur_line = '0' + cur_line; } zero_paddings++; lines.push_back(cur_line); } return add(lines); } };
#include <iostream> #include <math.h> using namespace std; double babylonianRoot(double n){ return sqrt(n); } int main(){ double n;char a; do{ cout<<"enter a value: "; cin>>n; cout<<"square root of "<<n<<" is "<<babylonianRoot(n)<<endl; cout<<"continue? (y/n): "; cin>>a; } while (a=='y'); return 0; }
/** @file ***************************************************************************** * @author This file is part of libsnark, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #include "algebra/curves/bls48/bls48_pairing.hpp" #include "algebra/curves/bls48/bls48_init.hpp" #include "algebra/curves/bls48/bls48_g1.hpp" #include "algebra/curves/bls48/bls48_g2.hpp" #include <cassert> #include "common/profiling.hpp" #include <iostream> namespace libsnark { bool bls48_ate_G1_precomp::operator==(const bls48_ate_G1_precomp &other) const { return (this->PX == other.PX && this->PY == other.PY); } std::ostream& operator<<(std::ostream &out, const bls48_ate_G1_precomp &prec_P) { out << prec_P.PX << OUTPUT_SEPARATOR << prec_P.PY; return out; } std::istream& operator>>(std::istream &in, bls48_ate_G1_precomp &prec_P) { in >> prec_P.PX; consume_OUTPUT_SEPARATOR(in); in >> prec_P.PY; return in; } /* bool bls48_ate_ell_coeffs::operator==(const bls48_ate_ell_coeffs &other) const { return (this->ell_0 == other.ell_0 && this->ell_VW == other.ell_VW && this->ell_VV == other.ell_VV); } std::ostream& operator<<(std::ostream &out, const bls48_ate_ell_coeffs &c) { out << c.ell_0 << OUTPUT_SEPARATOR << c.ell_VW << OUTPUT_SEPARATOR << c.ell_VV; return out; } std::istream& operator>>(std::istream &in, bls48_ate_ell_coeffs &c) { in >> c.ell_0; consume_OUTPUT_SEPARATOR(in); in >> c.ell_VW; consume_OUTPUT_SEPARATOR(in); in >> c.ell_VV; return in; } */ bool bls48_ate_G2_precomp::operator==(const bls48_ate_G2_precomp &other) const { return (this->QX == other.QX && this->QY == other.QY); //&&this->coeffs == other.coeffs); } /* std::ostream& operator<<(std::ostream& out, const bls48_ate_G2_precomp &prec_Q) { out << prec_Q.QX << OUTPUT_SEPARATOR << prec_Q.QY << "\n"; out << prec_Q.coeffs.size() << "\n"; for (const bls48_ate_ell_coeffs &c : prec_Q.coeffs) { out << c << OUTPUT_NEWLINE; } return out; } std::istream& operator>>(std::istream& in, bls48_ate_G2_precomp &prec_Q) { in >> prec_Q.QX; consume_OUTPUT_SEPARATOR(in); in >> prec_Q.QY; consume_newline(in); prec_Q.coeffs.clear(); size_t s; in >> s; consume_newline(in); prec_Q.coeffs.reserve(s); for (size_t i = 0; i < s; ++i) { bls48_ate_ell_coeffs c; in >> c; consume_OUTPUT_NEWLINE(in); prec_Q.coeffs.emplace_back(c); } return in; } */ /* final exponentiations */ bls48_Fq48 bls48_final_exponentiation_first_chunk(const bls48_Fq48 &elt)//easy part { enter_block("Call to bls48_final_exponentiation_first_chunk"); /* Computes result = elt^((q^24-1)*(q^8+1)). Follows, e.g., Beuchat et al page 9, by computing result as follows: elt^((q^24-1)*(q^8+1)) = (conj(elt) * elt^(-1))^(q^8+1) More precisely: A = conj(elt) B = elt.inverse() C = A * B D = C.Frobenius_map(8) result = D * C */ const bls48_Fq48 A = bls48_Fq48(elt.c0,-elt.c1); const bls48_Fq48 B = elt.inverse(); const bls48_Fq48 C = A * B; const bls48_Fq48 D = C.Frobenius_map(8); const bls48_Fq48 result = D * C; leave_block("Call to bls48_final_exponentiation_first_chunk"); return result; } bls48_Fq48 bls48_exp_by_neg_z(const bls48_Fq48 &elt) { enter_block("Call to bls48_exp_by_neg_z"); bls48_Fq48 result = elt^bls48_final_exponent_z; if (!bls48_final_exponent_is_z_neg) { result = result.unitary_inverse(); } leave_block("Call to bls48_exp_by_neg_z"); return result; } bls48_Fq48 bls48_final_exponentiation_last_chunk(const bls48_Fq48 &elt)//hard part { enter_block("Call to bls48_final_exponentiation_last_chunk"); /* result = which equals result = elt^((q^16 - q^8 + 1)/r). Using the following addition chain: m_1 = exp_by_neg_z(elt) // elt^(-z) result = V */ const bls48_Fq48 m_1_temp = bls48_exp_by_neg_z(elt); const bls48_Fq48 m_2 = bls48_exp_by_neg_z(m_1_temp); const bls48_Fq48 m_1_temp_squared = m_1_temp.squared(); const bls48_Fq48 m_1 = m_1_temp_squared.unitary_inverse(); const bls48_Fq48 mu_15 = m_2*m_1*elt; const bls48_Fq48 mu_14 = bls48_exp_by_neg_z(mu_15); const bls48_Fq48 mu_13 = bls48_exp_by_neg_z(mu_14); const bls48_Fq48 mu_12 = bls48_exp_by_neg_z(mu_13); const bls48_Fq48 mu_11 = bls48_exp_by_neg_z(mu_12); const bls48_Fq48 mu_10 = bls48_exp_by_neg_z(mu_11); const bls48_Fq48 mu_9 = bls48_exp_by_neg_z(mu_10); const bls48_Fq48 mu_8 = bls48_exp_by_neg_z(mu_9); const bls48_Fq48 mu_15_inv = mu_15.unitary_inverse(); const bls48_Fq48 mu_7 = bls48_exp_by_neg_z(mu_8)*mu_15_inv; const bls48_Fq48 mu_6 = bls48_exp_by_neg_z(mu_7); const bls48_Fq48 mu_5 = bls48_exp_by_neg_z(mu_6); const bls48_Fq48 mu_4 = bls48_exp_by_neg_z(mu_5); const bls48_Fq48 mu_3 = bls48_exp_by_neg_z(mu_4); const bls48_Fq48 mu_2 = bls48_exp_by_neg_z(mu_3); const bls48_Fq48 mu_1 = bls48_exp_by_neg_z(mu_2); const bls48_Fq48 mu_0_temp = bls48_exp_by_neg_z(mu_1);// const bls48_Fq48 m_cubed = elt*elt*elt;//m_1_temp_squared*m_1_temp;//elt^3 const bls48_Fq48 mu_0 = mu_0_temp*m_cubed; const bls48_Fq48 f_15_frob = mu_15.Frobenius_map(1); const bls48_Fq48 f_14 = f_15_frob*mu_14; const bls48_Fq48 f_14_frob = f_14.Frobenius_map(1); const bls48_Fq48 f_13 = f_14_frob*mu_13; const bls48_Fq48 f_13_frob = f_13.Frobenius_map(1); const bls48_Fq48 f_12 = f_13_frob*mu_12; const bls48_Fq48 f_12_frob = f_12.Frobenius_map(1); const bls48_Fq48 f_11 = f_12_frob*mu_11; const bls48_Fq48 f_11_frob = f_11.Frobenius_map(1); const bls48_Fq48 f_10 = f_11_frob*mu_10; const bls48_Fq48 f_10_frob = f_10.Frobenius_map(1); const bls48_Fq48 f_9 = f_10_frob*mu_9; const bls48_Fq48 f_9_frob = f_9.Frobenius_map(1); const bls48_Fq48 f_8 = f_9_frob*mu_8; const bls48_Fq48 f_8_frob = f_8.Frobenius_map(1); const bls48_Fq48 f_7 = f_8_frob*mu_7; const bls48_Fq48 f_7_frob = f_7.Frobenius_map(1); const bls48_Fq48 f_6 = f_7_frob*mu_6; const bls48_Fq48 f_6_frob = f_6.Frobenius_map(1); const bls48_Fq48 f_5 = f_6_frob*mu_5; const bls48_Fq48 f_5_frob = f_5.Frobenius_map(1); const bls48_Fq48 f_4 = f_5_frob*mu_4; const bls48_Fq48 f_4_frob = f_4.Frobenius_map(1); const bls48_Fq48 f_3 = f_4_frob*mu_3; const bls48_Fq48 f_3_frob = f_3.Frobenius_map(1); const bls48_Fq48 f_2 = f_3_frob*mu_2; const bls48_Fq48 f_2_frob = f_2.Frobenius_map(1); const bls48_Fq48 f_1 = f_2_frob*mu_1; const bls48_Fq48 f_1_frob = f_1.Frobenius_map(1); const bls48_Fq48 f = f_1_frob*mu_0; const bls48_Fq48 result = f; leave_block("Call to bls48_final_exponentiation_last_chunk"); return result; } bls48_GT bls48_final_exponentiation(const bls48_Fq48 &elt) { enter_block("Call to bls48_final_exponentiation"); // OLD naive version: //bls48_GT result = elt^bls48_final_exponent; bls48_Fq48 A = bls48_final_exponentiation_first_chunk(elt); bls48_GT result = bls48_final_exponentiation_last_chunk(A); leave_block("Call to bls48_final_exponentiation"); return result; } /* ate pairing */ bls48_ate_G1_precomp bls48_ate_precompute_G1(const bls48_G1& P) { enter_block("Call to bls48_ate_precompute_G1"); bls48_G1 Pcopy = P; Pcopy.to_affine_coordinates(); //assert(Pcopy.Y.squared() == Pcopy.X.squared()*Pcopy.X + bls48_Fq::one()); bls48_ate_G1_precomp result; result.PX = Pcopy.X; result.PY = Pcopy.Y; leave_block("Call to bls48_ate_precompute_G1"); return result; } bls48_ate_G2_precomp bls48_ate_precompute_G2(const bls48_G2& Q) { enter_block("Call to bls48_ate_precompute_G2"); bls48_G2 Qcopy(Q);//bls48_G2 Qcopy = Q; Qcopy.to_affine_coordinates(); //assert(Qcopy.Y.squared() == Qcopy.X.squared()*Qcopy.X + bls48_twist_coeff_b); //bls48_Fq two_inv = (bls48_Fq("2").inverse()); // could add to global params if needed bls48_ate_G2_precomp result; result.QX = Qcopy.X; result.QY = Qcopy.Y; leave_block("Call to bls48_ate_precompute_G2"); return result; } bls48_Fq48 bls48_ate_miller_loop(const bls48_G1_precomp &prec_P, const bls48_G2_precomp &prec_Q) { enter_block("Call to bls48_ate_miller_loop"); bls48_Fq48 f = bls48_Fq48::one();//f <- 1 bls48_G2 Q;//Q <- Q Q.X = prec_Q.QX; Q.Y = prec_Q.QY; Q.Z = bls48_Fq8::one(); bls48_G2 T;//T <- Q T.X = prec_Q.QX; T.Y = prec_Q.QY; T.Z = bls48_Fq8::one(); //std::cout << "T.Y = " << T.Y << std::endl; //std::cout << "T.Y + Q.Y = " << T.Y + Q.Y << std::endl; //assert(T.Y.squared() - T.X.squared()*T.X == bls48_twist_coeff_b); //long long j = -1; bls48_Fq48 l; l.c0.c0 = prec_P.PY*bls48_Fq8::one(); bls48_Fq8 ramda; bls48_Fq8 c; bls48_Fq two = bls48_Fq::one() + bls48_Fq::one(); bls48_Fq three = two + bls48_Fq::one(); bls48_Fq8 u = bls48_Fq8(bls48_Fq4(bls48_Fq2(bls48_Fq::zero(),bls48_Fq::one()),bls48_Fq2::zero()),bls48_Fq4::zero());//bls48_Fq8 :: ( 1, u, v, uv, w, u*w, v*w, u*v*w ) bls48_Fq8 xPu = prec_P.PX * u; //bool found_nonzero = false; //const bigint<bls48_Fr::num_limbs> &loop_count = bls48_ate_loop_count;//error //const bigint<bls48_Fq::num_limbs> &loop_count = bls48_ate_loop_count; //for (long i = loop_count.max_bits(); i >= 0; --i) for (int i = 31; i >= 0; --i) { /* const bool bit = loop_count.test_bit(i); if (!found_nonzero) { // this skips the MSB itself found_nonzero |= bit; continue; } */ /* code below gets executed for all bits (EXCEPT the MSB itself) of bls48_param_p (skipping leading zeros) in MSB to LSB order */ //j = 2*j; ////////// // l function ////////// ramda = two*T.Y;//2y ramda = ramda.inverse();//1/(2y) //assert(ramda*two*T.Y == bls48_Fq8::one()); ramda = three*(T.X.squared())*ramda;//3*x^2/(2*y) c = ramda*T.X - T.Y;//y = ramda*x + -c l.c1.c0 = (-ramda)*xPu;//(-ramda*xP)*u where u in Fq8 and ramda is slope l.c1.c1 = c*u;//c*u where u is y-segment //std::cout << "l_TT(P)" << std::endl; //l.print(); //std::cout << "end of print l_TT(P)" << std::endl; ////////// f = f.squared();//f <- f^2 f = f*l;//f^2*l_{T,T}(P) T = T.dbl(); T.to_affine_coordinates();//T <- 2T if (i==30 || i==10 ) { //std::cout << "i = " << i << std::endl; ramda = Q.X - T.X; ramda = ramda.inverse(); ramda = (Q.Y - T.Y)*ramda;//(yQ - yT)/(xQ - XT) c = ramda*Q.X - Q.Y; l.c1.c0 = (-ramda)*xPu;//(-ramda*xP)*u where u in Fq8 and ramda is slope l.c1.c1 = c*u;//c*u where c is - y-segment f = f*l;//f^2*l_{T,-Q}(P) T = T + Q; T.to_affine_coordinates(); //j = j - 1; } if(i==0){ //std::cout << "i = " << i << std::endl; ramda = Q.X - T.X; ramda = ramda.inverse(); ramda = (Q.Y - T.Y)*ramda;//(yQ - yT)/(xQ - XT) c = ramda*Q.X - Q.Y; l.c1.c0 = (-ramda)*xPu;//(-ramda*xP)*u where u in Fq8 and ramda is slope l.c1.c1 = c*u; f = f*l;//f*l_{T,-Q}(P) //T = T + Q; //T.to_affine_coordinates(); //assert(T == bls48_ate_loop_count*Q); } if(i==7){ //std::cout << "i = " << i << std::endl; ramda = Q.X - T.X; ramda = ramda.inverse(); ramda = (- Q.Y - T.Y)*ramda;//(y-Q - yT)/(x-Q - XT) c = ramda*Q.X + Q.Y; l.c1.c0 = (-ramda)*xPu; l.c1.c1 = c*u; f = f*l;//f*l_{T,Q}(P) T = T - Q; T.to_affine_coordinates(); //j = j + 1; } //assert(T.Y.squared() - T.X.squared()*T.X == bls48_twist_coeff_b); } //std::cout << "j = " << j << std::endl; if (!bls48_ate_is_loop_count_neg) { //std::cout << "inverse" << std::endl; f = f.unitary_inverse(); } //std::cout << "f = " << f << std::endl; leave_block("Call to bls48_ate_miller_loop"); return f; } bls48_Fq48 bls48_ate_pairing(const bls48_G1& P, const bls48_G2 &Q) { enter_block("Call to bls48_ate_pairing"); bls48_ate_G1_precomp prec_P = bls48_ate_precompute_G1(P); //assert(prec_P.PY.squared() - prec_P.PX.squared()*prec_P.PX == bls48_Fq::one()); bls48_ate_G2_precomp prec_Q = bls48_ate_precompute_G2(Q); //assert(prec_Q.QY.squared() - prec_Q.QX.squared()*prec_Q.QX == bls48_twist_coeff_b); bls48_Fq48 result = bls48_ate_miller_loop(prec_P, prec_Q); leave_block("Call to bls48_ate_pairing"); //std::cout << "after miller_loop result = " << result << std::endl; return result; } bls48_GT bls48_ate_reduced_pairing(const bls48_G1 &P, const bls48_G2 &Q) { enter_block("Call to bls48_ate_reduced_pairing"); const bls48_Fq48 f = bls48_ate_pairing(P, Q); const bls48_GT result = bls48_final_exponentiation(f); leave_block("Call to bls48_ate_reduced_pairing"); //std::cout << "reduced result = " << result << std::endl; return result; } /* choice of pairing */ bls48_G1_precomp bls48_precompute_G1(const bls48_G1& P) { return bls48_ate_precompute_G1(P); } bls48_G2_precomp bls48_precompute_G2(const bls48_G2& Q) { return bls48_ate_precompute_G2(Q); } bls48_Fq48 bls48_miller_loop(const bls48_G1_precomp &prec_P, const bls48_G2_precomp &prec_Q) { return bls48_ate_miller_loop(prec_P, prec_Q); } bls48_Fq48 bls48_pairing(const bls48_G1& P, const bls48_G2 &Q) { return bls48_ate_pairing(P, Q); } bls48_GT bls48_reduced_pairing(const bls48_G1 &P, const bls48_G2 &Q) { return bls48_ate_reduced_pairing(P, Q); } } // libsnark
#include "ogesolver.h"
#ifndef _CGetProductRoomConfig_h_ #define _CGetProductRoomConfig_h_ #pragma once #include <string> #include "CHttpRequestHandler.h" class CGetProductRoomConfig : public CHttpRequestHandler { public: CGetProductRoomConfig(){} ~CGetProductRoomConfig(){} virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out); private: }; #endif
#ifndef FORMTSTATCONFIG_H #define FORMTSTATCONFIG_H #include "config.h" #include <QWidget> namespace Ui { class FormTStatConfig; } class FormTStatConfig : public QWidget { Q_OBJECT signals: void SaveConfig(); public: FormTStatConfig(SysConfig *config, DevSettings *devSettings, QWidget *parent = nullptr); ~FormTStatConfig(); void LoadConfig(); SysConfig *config; DevSettings *settings; private slots: void on_buttonBox_accepted(); void on_buttonBox_rejected(); private: Ui::FormTStatConfig *ui; }; #endif // FORMTSTATCONFIG_H
/****************************************************************************** * * * Copyright 2018 Jan Henrik Weinstock * * * * 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 "vcml/common/thctl.h" #include "vcml/common/report.h" #include "vcml/common/systemc.h" namespace vcml { static pthread_t thctl_init(); static pthread_t g_thctl_sysc_thread = pthread_self(); static pthread_t g_thctl_mutex_owner = thctl_init(); static pthread_mutex_t g_thctl_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_thctl_notify = PTHREAD_COND_INITIALIZER; static void thctl_cycle() { thctl_exit_critical(); thctl_enter_critical(); } pthread_t thctl_sysc_thread() { return g_thctl_sysc_thread; } bool thctl_is_sysc_thread() { return g_thctl_sysc_thread == pthread_self(); } void thctl_enter_critical() { VCML_ERROR_ON(thctl_in_critical(), "thread already in critical section"); pthread_mutex_lock(&g_thctl_mutex); g_thctl_mutex_owner = pthread_self(); } void thctl_exit_critical() { VCML_ERROR_ON(!thctl_in_critical(), "thread not in critical section"); g_thctl_mutex_owner = 0; pthread_mutex_unlock(&g_thctl_mutex); } bool thctl_in_critical() { return g_thctl_mutex_owner == pthread_self(); } void thctl_suspend() { VCML_ERROR_ON(!thctl_is_sysc_thread(), "thctl_suspend must be called from SystemC thread"); VCML_ERROR_ON(!thctl_in_critical(), "thread not in critical section"); g_thctl_mutex_owner = 0; int res = pthread_cond_wait(&g_thctl_notify, &g_thctl_mutex); VCML_ERROR_ON(res != 0, "pthread_cond_wait: %s", strerror(res)); g_thctl_mutex_owner = pthread_self(); } void thctl_resume() { VCML_ERROR_ON(thctl_is_sysc_thread(), "SystemC thread cannot resume itself"); int res = pthread_cond_signal(&g_thctl_notify); VCML_ERROR_ON(res != 0, "pthread_cond_signal: %s", strerror(res)); } #ifdef SNPS_VP_SC_VERSION static void snps_enter_critical(void* unused) { (void)unused; thctl_enter_critical(); } static void snps_exit_critical(void* unused) { (void)unused; thctl_exit_critical(); } #endif static pthread_t thctl_init() { #ifdef SNPS_VP_SC_VERSION sc_simcontext* simc = sc_get_curr_simcontext(); simc->add_phase_callback(snps::sc::PCB_BEGIN_OF_EVALUATE_PHASE, &snps_enter_critical); simc->add_phase_callback(snps::sc::PCB_END_OF_EVALUATE_PHASE, &snps_exit_critical); return 0; #else pthread_mutex_init(&g_thctl_mutex, nullptr); pthread_cond_init(&g_thctl_notify, nullptr); pthread_mutex_lock(&g_thctl_mutex); on_each_delta_cycle(&thctl_cycle); return pthread_self(); #endif } }
#include <iostream> using namespace std; struct nod { int info; nod *next; }; nod *prim, *ultim; void primul_element() { prim=new nod; cout<<"Noul element ce urmeaza sa fie inserat in lista: "; cin>>prim->info; prim->next=NULL; ultim=prim; // si ultimul } void adaugare() { nod *c; c=new nod; cout<<"Noul element ce urmeaza sa fie inserat in lista: "; cin>>c -> info; if(prim->info < c->info) { ultim -> next=c; ultim=c; ultim -> next=NULL; } else { c -> next=prim; prim=c; } } void afisare() { nod *c; c=prim; while(c!=0) { cout<<c -> info<<" "; c= c-> next; } } int main() { int n; cout<<"n="; cin>>n; if(n!=0) primul_element(); for(int i=0; i<n-1; i++) adaugare(); if(n!=0) { cout<<"Lista ordonata arata astfel: "; afisare(); } else cout<<"Lista nu are elemente"; return 0; }
#include <cmath> #include <map> #include <random> #include <set> #include "../space/initial_triangulation.hpp" #include "../time/bilinear_form.hpp" #include "heat_equation.hpp" int bsd_rnd() { static unsigned int seed = 0; int a = 1103515245; int c = 12345; unsigned int m = 2147483648; return (seed = (a * seed + c) % m); } using namespace applications; using namespace spacetime; using namespace space; using namespace Time; using namespace datastructures; constexpr int level = 12; constexpr int heateq_iters = 5; constexpr int inner_iters = 10; constexpr bool use_cache = true; int main() { auto B = Time::Bases(); auto T = InitialTriangulation::UnitSquare(); T.hierarch_basis_tree.UniformRefine(::level); B.ortho_tree.UniformRefine(::level); B.three_point_tree.UniformRefine(::level); for (size_t j = 0; j < ::heateq_iters; ++j) { auto X_delta = DoubleTreeView<ThreePointWaveletFn, HierarchicalBasisFn>( B.three_point_tree.meta_root(), T.hierarch_basis_tree.meta_root()); X_delta.SparseRefine(::level); HeatEquation heat_eq(X_delta); // Generate some random input. for (auto nv : heat_eq.vec_X()->Bfs()) { if (nv->node_1()->on_domain_boundary()) continue; nv->set_random(); } auto v_in = heat_eq.vec_X()->ToVectorContainer(); for (size_t k = 0; k < ::inner_iters; k++) { heat_eq.S()->Apply(v_in); } } return 0; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/common/test/TestUtils.h> #include <fizz/crypto/test/TestUtil.h> #include <fizz/protocol/clock/test/Mocks.h> #include <fizz/protocol/test/Mocks.h> #include <quic/api/QuicTransportFunctions.h> #include <quic/codec/DefaultConnectionIdAlgo.h> #include <quic/codec/QuicConnectionId.h> #include <quic/fizz/handshake/QuicFizzFactory.h> #include <quic/fizz/server/handshake/AppToken.h> #include <quic/handshake/test/Mocks.h> #include <quic/server/handshake/StatelessResetGenerator.h> #include <quic/state/AckEvent.h> #include <quic/state/LossState.h> #include <quic/state/OutstandingPacket.h> #include <quic/state/stream/StreamSendHandlers.h> using namespace testing; namespace quic { namespace test { std::function<MockClock::time_point()> MockClock::mockNow; const RegularQuicWritePacket& writeQuicPacket( QuicServerConnectionState& conn, ConnectionId srcConnId, ConnectionId dstConnId, folly::test::MockAsyncUDPSocket& sock, QuicStreamState& stream, const folly::IOBuf& data, bool eof) { auto version = conn.version.value_or(*conn.originalVersion); auto aead = createNoOpAead(); auto headerCipher = createNoOpHeaderCipher(); writeDataToQuicStream(stream, data.clone(), eof); writeQuicDataToSocket( sock, conn, srcConnId, dstConnId, *aead, *headerCipher, version, conn.transportSettings.writeConnectionDataPacketsLimit); CHECK( conn.outstandings.packets.rend() != getLastOutstandingPacket(conn, PacketNumberSpace::AppData)); return getLastOutstandingPacket(conn, PacketNumberSpace::AppData)->packet; } PacketNum rstStreamAndSendPacket( QuicServerConnectionState& conn, QuicAsyncUDPSocketType& sock, QuicStreamState& stream, ApplicationErrorCode errorCode) { auto aead = createNoOpAead(); auto headerCipher = createNoOpHeaderCipher(); auto version = conn.version.value_or(*conn.originalVersion); sendRstSMHandler(stream, errorCode); writeQuicDataToSocket( sock, conn, *conn.clientConnectionId, *conn.serverConnectionId, *aead, *headerCipher, version, conn.transportSettings.writeConnectionDataPacketsLimit); for (const auto& packet : conn.outstandings.packets) { for (const auto& frame : packet.packet.frames) { auto rstFrame = frame.asRstStreamFrame(); if (!rstFrame) { continue; } if (rstFrame->streamId == stream.id) { return packet.packet.header.getPacketSequenceNum(); } } } CHECK(false) << "no packet with reset stream"; // some compilers are weird. return 0; } RegularQuicPacketBuilder::Packet createAckPacket( QuicConnectionStateBase& dstConn, PacketNum pn, AckBlocks& acks, PacketNumberSpace pnSpace, const Aead* aead, std::chrono::microseconds ackDelay) { auto builder = AckPacketBuilder() .setDstConn(&dstConn) .setPacketNumberSpace(pnSpace) .setAckPacketNum(pn) .setAckBlocks(acks) .setAckDelay(ackDelay); if (aead) { builder.setAead(aead); } return std::move(builder).build(); } static std::shared_ptr<fizz::SelfCert> readCert() { auto certificate = fizz::test::getCert(fizz::test::kP256Certificate); auto privKey = fizz::test::getPrivateKey(fizz::test::kP256Key); std::vector<folly::ssl::X509UniquePtr> certs; certs.emplace_back(std::move(certificate)); return std::make_shared<fizz::SelfCertImpl<fizz::KeyType::P256>>( std::move(privKey), std::move(certs)); } std::shared_ptr<fizz::server::FizzServerContext> createServerCtx() { auto cert = readCert(); auto certManager = std::make_unique<fizz::server::CertManager>(); certManager->addCert(std::move(cert), true); auto serverCtx = std::make_shared<fizz::server::FizzServerContext>(); serverCtx->setFactory(std::make_shared<QuicFizzFactory>()); serverCtx->setCertManager(std::move(certManager)); serverCtx->setOmitEarlyRecordLayer(true); serverCtx->setClock(std::make_shared<NiceMock<fizz::test::MockClock>>()); return serverCtx; } class AcceptingTicketCipher : public fizz::server::TicketCipher { public: ~AcceptingTicketCipher() override = default; folly::SemiFuture<folly::Optional< std::pair<std::unique_ptr<folly::IOBuf>, std::chrono::seconds>>> encrypt(fizz::server::ResumptionState) const override { // Fake handshake, no need todo anything here. return std::make_pair(folly::IOBuf::create(0), 2s); } void setPsk(const QuicCachedPsk& cachedPsk) { cachedPsk_ = cachedPsk; } fizz::server::ResumptionState createResumptionState() const { fizz::server::ResumptionState resState; resState.version = cachedPsk_.cachedPsk.version; resState.cipher = cachedPsk_.cachedPsk.cipher; resState.resumptionSecret = folly::IOBuf::copyBuffer(cachedPsk_.cachedPsk.secret); resState.serverCert = cachedPsk_.cachedPsk.serverCert; resState.alpn = cachedPsk_.cachedPsk.alpn; resState.ticketAgeAdd = 0; resState.ticketIssueTime = std::chrono::system_clock::time_point(); resState.handshakeTime = std::chrono::system_clock::time_point(); AppToken appToken; appToken.transportParams = createTicketTransportParameters( kDefaultIdleTimeout.count(), kDefaultUDPReadBufferSize, kDefaultConnectionFlowControlWindow, kDefaultStreamFlowControlWindow, kDefaultStreamFlowControlWindow, kDefaultStreamFlowControlWindow, kDefaultMaxStreamsBidirectional, kDefaultMaxStreamsUnidirectional); appToken.version = QuicVersion::MVFST; resState.appToken = encodeAppToken(appToken); return resState; } folly::SemiFuture< std::pair<fizz::PskType, folly::Optional<fizz::server::ResumptionState>>> decrypt(std::unique_ptr<folly::IOBuf>) const override { return std::make_pair(fizz::PskType::Resumption, createResumptionState()); } private: QuicCachedPsk cachedPsk_; }; void setupZeroRttOnServerCtx( fizz::server::FizzServerContext& serverCtx, const QuicCachedPsk& cachedPsk) { serverCtx.setEarlyDataSettings( true, fizz::server::ClockSkewTolerance{-100000ms, 100000ms}, std::make_shared<fizz::server::AllowAllReplayReplayCache>()); auto ticketCipher = std::make_shared<AcceptingTicketCipher>(); ticketCipher->setPsk(cachedPsk); serverCtx.setTicketCipher(ticketCipher); } QuicCachedPsk setupZeroRttOnClientCtx( fizz::client::FizzClientContext& clientCtx, std::string hostname) { clientCtx.setSendEarlyData(true); QuicCachedPsk quicCachedPsk; auto& psk = quicCachedPsk.cachedPsk; psk.psk = std::string("psk"); psk.secret = std::string("secret"); psk.type = fizz::PskType::Resumption; psk.version = clientCtx.getSupportedVersions()[0]; psk.cipher = clientCtx.getSupportedCiphers()[0]; psk.group = clientCtx.getSupportedGroups()[0]; auto mockCert = std::make_shared<NiceMock<fizz::test::MockCert>>(); ON_CALL(*mockCert, getIdentity()).WillByDefault(Return(hostname)); psk.serverCert = mockCert; psk.alpn = clientCtx.getSupportedAlpns()[0]; psk.ticketAgeAdd = 1; psk.ticketIssueTime = std::chrono::system_clock::time_point(); psk.ticketExpirationTime = std::chrono::system_clock::time_point(std::chrono::minutes(100)); psk.ticketHandshakeTime = std::chrono::system_clock::time_point(); psk.maxEarlyDataSize = 2; quicCachedPsk.transportParams.idleTimeout = kDefaultIdleTimeout.count(); quicCachedPsk.transportParams.maxRecvPacketSize = kDefaultUDPReadBufferSize; quicCachedPsk.transportParams.initialMaxData = kDefaultConnectionFlowControlWindow; quicCachedPsk.transportParams.initialMaxStreamDataBidiLocal = kDefaultStreamFlowControlWindow; quicCachedPsk.transportParams.initialMaxStreamDataBidiRemote = kDefaultStreamFlowControlWindow; quicCachedPsk.transportParams.initialMaxStreamDataUni = kDefaultStreamFlowControlWindow; quicCachedPsk.transportParams.initialMaxStreamsBidi = kDefaultMaxStreamsBidirectional; quicCachedPsk.transportParams.initialMaxStreamsUni = kDefaultMaxStreamsUnidirectional; return quicCachedPsk; } void setupCtxWithTestCert(fizz::server::FizzServerContext& ctx) { auto cert = readCert(); auto certManager = std::make_unique<fizz::server::CertManager>(); certManager->addCert(std::move(cert), true); ctx.setCertManager(std::move(certManager)); } std::unique_ptr<MockAead> createNoOpAead(uint64_t cipherOverhead) { return createNoOpAeadImpl<MockAead>(cipherOverhead); } std::unique_ptr<MockPacketNumberCipher> createNoOpHeaderCipher() { auto headerCipher = std::make_unique<NiceMock<MockPacketNumberCipher>>(); ON_CALL(*headerCipher, mask(_)).WillByDefault(Return(HeaderProtectionMask{})); ON_CALL(*headerCipher, keyLength()).WillByDefault(Return(16)); return headerCipher; } RegularQuicPacketBuilder::Packet createStreamPacket( ConnectionId srcConnId, ConnectionId dstConnId, PacketNum packetNum, StreamId streamId, folly::IOBuf& data, uint8_t cipherOverhead, PacketNum largestAcked, folly::Optional<std::pair<LongHeader::Types, QuicVersion>> longHeaderOverride, bool eof, folly::Optional<ProtectionType> shortHeaderOverride, uint64_t offset, uint64_t packetSizeLimit) { std::unique_ptr<RegularQuicPacketBuilder> builder; if (longHeaderOverride) { LongHeader header( longHeaderOverride->first, srcConnId, dstConnId, packetNum, longHeaderOverride->second); builder.reset(new RegularQuicPacketBuilder( packetSizeLimit, std::move(header), largestAcked)); } else { ProtectionType protectionType = ProtectionType::KeyPhaseZero; if (shortHeaderOverride) { protectionType = *shortHeaderOverride; } ShortHeader header(protectionType, dstConnId, packetNum); builder.reset(new RegularQuicPacketBuilder( packetSizeLimit, std::move(header), largestAcked)); } builder->encodePacketHeader(); builder->accountForCipherOverhead(cipherOverhead); auto dataLen = *writeStreamFrameHeader( *builder, streamId, offset, data.computeChainDataLength(), data.computeChainDataLength(), eof, folly::none /* skipLenHint */); writeStreamFrameData( *builder, data.clone(), std::min(folly::to<size_t>(dataLen), data.computeChainDataLength())); return std::move(*builder).buildPacket(); } RegularQuicPacketBuilder::Packet createInitialCryptoPacket( ConnectionId srcConnId, ConnectionId dstConnId, PacketNum packetNum, QuicVersion version, folly::IOBuf& data, const Aead& aead, PacketNum largestAcked, uint64_t offset, std::string token, const BuilderProvider& builderProvider) { LongHeader header( LongHeader::Types::Initial, srcConnId, dstConnId, packetNum, version, std::move(token)); LongHeader copyHeader(header); PacketBuilderInterface* builder = nullptr; if (builderProvider) { builder = builderProvider(std::move(header), largestAcked); } RegularQuicPacketBuilder fallbackBuilder( kDefaultUDPSendPacketLen, std::move(copyHeader), largestAcked); if (!builder) { builder = &fallbackBuilder; } builder->encodePacketHeader(); builder->accountForCipherOverhead(aead.getCipherOverhead()); auto res = writeCryptoFrame(offset, data.clone(), *builder); CHECK(res.hasValue()) << "failed to write crypto frame"; return std::move(*builder).buildPacket(); } RegularQuicPacketBuilder::Packet createCryptoPacket( ConnectionId srcConnId, ConnectionId dstConnId, PacketNum packetNum, QuicVersion version, ProtectionType protectionType, folly::IOBuf& data, const Aead& aead, PacketNum largestAcked, uint64_t offset, uint64_t packetSizeLimit) { folly::Optional<PacketHeader> header; switch (protectionType) { case ProtectionType::Initial: header = LongHeader( LongHeader::Types::Initial, srcConnId, dstConnId, packetNum, version); break; case ProtectionType::Handshake: header = LongHeader( LongHeader::Types::Handshake, srcConnId, dstConnId, packetNum, version); break; case ProtectionType::ZeroRtt: header = LongHeader( LongHeader::Types::ZeroRtt, srcConnId, dstConnId, packetNum, version); break; case ProtectionType::KeyPhaseOne: case ProtectionType::KeyPhaseZero: header = ShortHeader(protectionType, dstConnId, packetNum); break; } RegularQuicPacketBuilder builder( packetSizeLimit, std::move(*header), largestAcked); builder.encodePacketHeader(); builder.accountForCipherOverhead(aead.getCipherOverhead()); auto res = writeCryptoFrame(offset, data.clone(), builder); CHECK(res.hasValue()) << "failed to write crypto frame"; return std::move(builder).buildPacket(); } Buf packetToBuf(const RegularQuicPacketBuilder::Packet& packet) { auto packetBuf = packet.header->clone(); if (packet.body) { packetBuf->prependChain(packet.body->clone()); } return packetBuf; } Buf packetToBufCleartext( const RegularQuicPacketBuilder::Packet& packet, const Aead& cleartextCipher, const PacketNumberCipher& headerCipher, PacketNum packetNum) { VLOG(10) << __func__ << " packet header: " << folly::hexlify(packet.header->clone()->moveToFbString()); auto packetBuf = packet.header->clone(); Buf body; if (packet.body) { packet.body->coalesce(); body = packet.body->clone(); } else { body = folly::IOBuf::create(0); } auto headerForm = packet.packet.header.getHeaderForm(); packet.header->coalesce(); auto tagLen = cleartextCipher.getCipherOverhead(); if (body->tailroom() < tagLen) { body->prependChain(folly::IOBuf::create(tagLen)); } body->coalesce(); auto encryptedBody = cleartextCipher.inplaceEncrypt( std::move(body), packet.header.get(), packetNum); encryptedBody->coalesce(); encryptPacketHeader( headerForm, packet.header->writableData(), packet.header->length(), encryptedBody->data(), encryptedBody->length(), headerCipher); packetBuf->prependChain(std::move(encryptedBody)); return packetBuf; } uint64_t computeExpectedDelay( std::chrono::microseconds ackDelay, uint8_t ackDelayExponent) { uint64_t divide = uint64_t(ackDelay.count()) >> ackDelayExponent; return divide << ackDelayExponent; } ConnectionId getTestConnectionId(uint32_t hostId, ConnectionIdVersion version) { ServerConnectionIdParams params(version, hostId, 0, 0); DefaultConnectionIdAlgo connIdAlgo; auto connId = *connIdAlgo.encodeConnectionId(params); // Clear random part of CID, some existing tests expect same CID value // when repeatedly calling with the same hostId. if (version == ConnectionIdVersion::V1) { connId.data()[3] = 3; connId.data()[4] = 4; connId.data()[5] = 5; connId.data()[6] = 6; connId.data()[7] = 7; } else if (version == ConnectionIdVersion::V2) { connId.data()[0] &= 0xC0; connId.data()[5] = 5; connId.data()[6] = 6; connId.data()[7] = 7; } else { CHECK(false) << "Unsupported CID version"; } return connId; } ProtectionType encryptionLevelToProtectionType( fizz::EncryptionLevel encryptionLevel) { switch (encryptionLevel) { case fizz::EncryptionLevel::Plaintext: return ProtectionType::Initial; case fizz::EncryptionLevel::Handshake: // TODO: change this in draft-14 return ProtectionType::Initial; case fizz::EncryptionLevel::EarlyData: return ProtectionType::ZeroRtt; case fizz::EncryptionLevel::AppTraffic: return ProtectionType::KeyPhaseZero; } folly::assume_unreachable(); } void updateAckState( QuicConnectionStateBase& conn, PacketNumberSpace pnSpace, PacketNum packetNum, bool pkHasRetransmittableData, bool pkHasCryptoData, TimePoint receivedTime) { uint64_t distance = updateLargestReceivedPacketNum( conn, getAckState(conn, pnSpace), packetNum, receivedTime); updateAckSendStateOnRecvPacket( conn, getAckState(conn, pnSpace), distance, pkHasRetransmittableData, pkHasCryptoData); } std::unique_ptr<folly::IOBuf> buildRandomInputData(size_t length) { auto buf = folly::IOBuf::create(length); buf->append(length); folly::Random::secureRandom(buf->writableData(), buf->length()); return buf; } void addAckStatesWithCurrentTimestamps( AckState& ackState, PacketNum start, PacketNum end) { ackState.acks.insert(start, end); ackState.largestRecvdPacketTime = Clock::now(); } OutstandingPacketWrapper makeTestingWritePacket( PacketNum desiredPacketSeqNum, size_t desiredSize, uint64_t totalBytesSent, TimePoint sentTime /* = Clock::now() */, uint64_t inflightBytes /* = 0 */, uint64_t writeCount /* = 0 */) { LongHeader longHeader( LongHeader::Types::ZeroRtt, getTestConnectionId(1), getTestConnectionId(), desiredPacketSeqNum, QuicVersion::MVFST); RegularQuicWritePacket packet(std::move(longHeader)); return OutstandingPacketWrapper( packet, sentTime, desiredSize, 0, false, totalBytesSent, 0, inflightBytes, 0, LossState(), writeCount, OutstandingPacketMetadata::DetailsPerStream()); } CongestionController::AckEvent makeAck( PacketNum seq, uint64_t ackedSize, TimePoint ackedTime, TimePoint sentTime) { CHECK(sentTime < ackedTime); RegularQuicWritePacket packet( ShortHeader(ProtectionType::KeyPhaseZero, getTestConnectionId(), seq)); auto ack = AckEvent::Builder() .setAckTime(ackedTime) .setAdjustedAckTime(ackedTime) .setAckDelay(0us) .setPacketNumberSpace(PacketNumberSpace::AppData) .setLargestAckedPacket(seq) .build(); ack.ackedBytes = ackedSize; ack.largestNewlyAckedPacket = seq; ack.ackedPackets.emplace_back( CongestionController::AckEvent::AckPacket::Builder() .setPacketNum(seq) .setNonDsrPacketSequenceNumber(seq) .setOutstandingPacketMetadata(OutstandingPacketMetadata( sentTime, ackedSize /* encodedSize */, ackedSize /* encodedBodySize */, false /* isHandshake */, 0 /* totalBytesSent */, 0 /* totalBodyBytesSent */, 0 /* inflightBytes */, 0 /* numOutstanding */, LossState() /* lossState */, 0 /* writeCount */, OutstandingPacketMetadata::DetailsPerStream())) .setDetailsPerStream(AckEvent::AckPacket::DetailsPerStream()) .build()); ack.largestNewlyAckedPacketSentTime = sentTime; return ack; } BufQueue bufToQueue(Buf buf) { BufQueue queue; buf->coalesce(); queue.append(std::move(buf)); return queue; } StatelessResetToken generateStatelessResetToken() { StatelessResetSecret secret; folly::Random::secureRandom(secret.data(), secret.size()); folly::SocketAddress address("1.2.3.4", 8080); StatelessResetGenerator generator(secret, address.getFullyQualified()); return generator.generateToken(ConnectionId({0x14, 0x35, 0x22, 0x11})); } std::array<uint8_t, kStatelessResetTokenSecretLength> getRandSecret() { std::array<uint8_t, kStatelessResetTokenSecretLength> secret; folly::Random::secureRandom(secret.data(), secret.size()); return secret; } RegularQuicWritePacket createNewPacket( PacketNum packetNum, PacketNumberSpace pnSpace) { switch (pnSpace) { case PacketNumberSpace::Initial: return RegularQuicWritePacket(LongHeader( LongHeader::Types::Initial, getTestConnectionId(1), getTestConnectionId(2), packetNum, QuicVersion::QUIC_DRAFT)); case PacketNumberSpace::Handshake: return RegularQuicWritePacket(LongHeader( LongHeader::Types::Handshake, getTestConnectionId(0), getTestConnectionId(4), packetNum, QuicVersion::QUIC_DRAFT)); case PacketNumberSpace::AppData: return RegularQuicWritePacket(ShortHeader( ProtectionType::KeyPhaseOne, getTestConnectionId(), packetNum)); } folly::assume_unreachable(); } std::vector<QuicVersion> versionList( std::initializer_list<QuicVersionType> types) { std::vector<QuicVersion> versions; for (auto type : types) { versions.push_back(static_cast<QuicVersion>(type)); } return versions; } RegularQuicWritePacket createRegularQuicWritePacket( StreamId streamId, uint64_t offset, uint64_t len, bool fin) { auto regularWritePacket = createNewPacket(10, PacketNumberSpace::Initial); WriteStreamFrame frame(streamId, offset, len, fin); regularWritePacket.frames.emplace_back(frame); return regularWritePacket; } VersionNegotiationPacket createVersionNegotiationPacket() { auto versions = {QuicVersion::VERSION_NEGOTIATION, QuicVersion::MVFST}; auto packet = VersionNegotiationPacketBuilder( getTestConnectionId(0), getTestConnectionId(1), versions) .buildPacket() .first; return packet; } RegularQuicWritePacket createPacketWithAckFrames() { RegularQuicWritePacket packet = createNewPacket(100, PacketNumberSpace::Initial); WriteAckFrame ackFrame; ackFrame.ackDelay = 111us; ackFrame.ackBlocks.emplace_back(900, 1000); ackFrame.ackBlocks.emplace_back(500, 700); packet.frames.emplace_back(std::move(ackFrame)); return packet; } RegularQuicWritePacket createPacketWithPaddingFrames() { RegularQuicWritePacket packet = createNewPacket(100, PacketNumberSpace::Initial); PaddingFrame paddingFrame{20}; packet.frames.emplace_back(paddingFrame); return packet; } std::vector<int> getQLogEventIndices( QLogEventType type, const std::shared_ptr<FileQLogger>& q) { std::vector<int> indices; for (uint64_t i = 0; i < q->logs.size(); ++i) { if (q->logs[i]->eventType == type) { indices.push_back(i); } } return indices; } bool matchError(QuicError errorCode, LocalErrorCode error) { return errorCode.code.type() == QuicErrorCode::Type::LocalErrorCode && *errorCode.code.asLocalErrorCode() == error; } bool matchError(QuicError errorCode, TransportErrorCode error) { return errorCode.code.type() == QuicErrorCode::Type::TransportErrorCode && *errorCode.code.asTransportErrorCode() == error; } bool matchError(QuicError errorCode, ApplicationErrorCode error) { return errorCode.code.type() == QuicErrorCode::Type::ApplicationErrorCode && *errorCode.code.asApplicationErrorCode() == error; } CongestionController::AckEvent::AckPacket makeAckPacketFromOutstandingPacket( OutstandingPacketWrapper outstandingPacket) { return CongestionController::AckEvent::AckPacket::Builder() .setPacketNum(outstandingPacket.packet.header.getPacketSequenceNum()) .setNonDsrPacketSequenceNumber( outstandingPacket.packet.header.getPacketSequenceNum()) .setOutstandingPacketMetadata(std::move(outstandingPacket.metadata)) .setLastAckedPacketInfo(std::move(outstandingPacket.lastAckedPacketInfo)) .setAppLimited(outstandingPacket.isAppLimited) .setDetailsPerStream( CongestionController::AckEvent::AckPacket::DetailsPerStream()) .build(); } folly::Optional<WriteCryptoFrame> writeCryptoFrame(uint64_t offsetIn, Buf data, PacketBuilderInterface& builder) { BufQueue bufQueue(std::move(data)); return writeCryptoFrame(offsetIn, bufQueue, builder); } void overridePacketWithToken( PacketBuilderInterface::Packet& packet, const StatelessResetToken& token) { overridePacketWithToken(*packet.body, token); } void overridePacketWithToken( folly::IOBuf& bodyBuf, const StatelessResetToken& token) { bodyBuf.coalesce(); CHECK(bodyBuf.length() > sizeof(StatelessResetToken)); memcpy( bodyBuf.writableData() + bodyBuf.length() - sizeof(StatelessResetToken), token.data(), token.size()); } bool writableContains(QuicStreamManager& streamManager, StreamId streamId) { return streamManager.writeQueue().count(streamId) > 0 || streamManager.controlWriteQueue().count(streamId) > 0; } std::unique_ptr<PacketNumberCipher> FizzCryptoTestFactory::makePacketNumberCipher(fizz::CipherSuite) const { return std::move(packetNumberCipher_); } std::unique_ptr<PacketNumberCipher> FizzCryptoTestFactory::makePacketNumberCipher(folly::ByteRange secret) const { return _makePacketNumberCipher(secret); } void FizzCryptoTestFactory::setMockPacketNumberCipher( std::unique_ptr<PacketNumberCipher> packetNumberCipher) { packetNumberCipher_ = std::move(packetNumberCipher); } void FizzCryptoTestFactory::setDefault() { ON_CALL(*this, _makePacketNumberCipher(_)) .WillByDefault(Invoke([&](folly::ByteRange secret) { return FizzCryptoFactory::makePacketNumberCipher(secret); })); } void TestPacketBatchWriter::reset() { bufNum_ = 0; bufSize_ = 0; } bool TestPacketBatchWriter::append( std::unique_ptr<folly::IOBuf>&& /*unused*/, size_t size, const folly::SocketAddress& /*unused*/, QuicAsyncUDPSocketType* /*unused*/) { bufNum_++; bufSize_ += size; return ((maxBufs_ < 0) || (bufNum_ >= maxBufs_)); } ssize_t TestPacketBatchWriter::write( QuicAsyncUDPSocketType& /*unused*/, const folly::SocketAddress& /*unused*/) { return bufSize_; } TrafficKey getQuicTestKey() { TrafficKey testKey; testKey.key = folly::IOBuf::copyBuffer( folly::unhexlify("000102030405060708090A0B0C0D0E0F")); testKey.iv = folly::IOBuf::copyBuffer(folly::unhexlify("000102030405060708090A0B")); return testKey; } std::unique_ptr<folly::IOBuf> getProtectionKey() { FizzCryptoFactory factory; auto secret = folly::range(getRandSecret()); auto pnCipher = factory.makePacketNumberCipher(fizz::CipherSuite::TLS_AES_128_GCM_SHA256); auto deriver = factory.getFizzFactory()->makeKeyDeriver( fizz::CipherSuite::TLS_AES_128_GCM_SHA256); return deriver->expandLabel( secret, kQuicPNLabel, folly::IOBuf::create(0), pnCipher->keyLength()); } } // namespace test } // namespace quic
#pragma once #include"ybBasicMacro.h" #include"ybMatrix.h" #include"ybVector.h" NS_YB_BEGIN class Math { public: static void Multiply(Matrix4x4& out, const Matrix4x4& mat1, const Matrix4x4& mat2); static void Multiply(Vector4& out, const Matrix4x4& mat, const Vector4& vec); static void Identity(Matrix4x4& out); static double Distance(const Vector4& vec1,const Vector4& vec2); static double Distance(const Vector3& vec1,const Vector3& vec2); }; NS_YB_END
#include <iomanip> #include <stdexcept> #include <string> #include "performance.h" #include "opencv2/core/cuda.hpp" using namespace std; using namespace cv; using namespace cv::cuda; void TestSystem::run() { if (is_list_mode_) { for (vector<Runnable*>::iterator it = tests_.begin(); it != tests_.end(); ++it) cout << (*it)->name() << endl; return; } // Run test initializers for (vector<Runnable*>::iterator it = inits_.begin(); it != inits_.end(); ++it) { if ((*it)->name().find(test_filter_, 0) != string::npos) (*it)->run(); } printHeading(); // Run tests for (vector<Runnable*>::iterator it = tests_.begin(); it != tests_.end(); ++it) { try { if ((*it)->name().find(test_filter_, 0) != string::npos) { cout << endl << (*it)->name() << ":\n"; (*it)->run(); finishCurrentSubtest(); } } catch (const Exception&) { // Message is printed via callback resetCurrentSubtest(); } catch (const runtime_error& e) { printError(e.what()); resetCurrentSubtest(); } } printSummary(); } void TestSystem::finishCurrentSubtest() { if (cur_subtest_is_empty_) // There is no need to print subtest statistics return; double cpu_time = cpu_elapsed_ / getTickFrequency() * 1000.0; double gpu_time = gpu_elapsed_ / getTickFrequency() * 1000.0; double speedup = static_cast<double>(cpu_elapsed_) / std::max(1.0, gpu_elapsed_); speedup_total_ += speedup; printMetrics(cpu_time, gpu_time, speedup); num_subtests_called_++; resetCurrentSubtest(); } double TestSystem::meanTime(const vector<int64> &samples) { double sum = accumulate(samples.begin(), samples.end(), 0.); if (samples.size() > 1) return (sum - samples[0]) / (samples.size() - 1); return sum; } void TestSystem::printHeading() { cout << endl; cout << setiosflags(ios_base::left); cout << TAB << setw(10) << "CPU, ms" << setw(10) << "GPU, ms" << setw(14) << "SPEEDUP" << "DESCRIPTION\n"; cout << resetiosflags(ios_base::left); } void TestSystem::printSummary() { cout << setiosflags(ios_base::fixed); cout << "\naverage GPU speedup: x" << setprecision(3) << speedup_total_ / std::max(1, num_subtests_called_) << endl; cout << resetiosflags(ios_base::fixed); } void TestSystem::printMetrics(double cpu_time, double gpu_time, double speedup) { cout << TAB << setiosflags(ios_base::left); stringstream stream; stream << cpu_time; cout << setw(10) << stream.str(); stream.str(""); stream << gpu_time; cout << setw(10) << stream.str(); stream.str(""); stream << "x" << setprecision(3) << speedup; cout << setw(14) << stream.str(); cout << cur_subtest_description_.str(); cout << resetiosflags(ios_base::left) << endl; } void TestSystem::printError(const std::string& msg) { cout << TAB << "[error: " << msg << "] " << cur_subtest_description_.str() << endl; } void gen(Mat& mat, int rows, int cols, int type, Scalar low, Scalar high) { mat.create(rows, cols, type); RNG rng(0); rng.fill(mat, RNG::UNIFORM, low, high); } string abspath(const string& relpath) { return TestSystem::instance().workingDir() + relpath; } static int cvErrorCallback(int /*status*/, const char* /*func_name*/, const char* err_msg, const char* /*file_name*/, int /*line*/, void* /*userdata*/) { TestSystem::instance().printError(err_msg); return 0; } int main(int argc, const char* argv[]) { int num_devices = getCudaEnabledDeviceCount(); if (num_devices == 0) { cerr << "No GPU found or the library was compiled without CUDA support"; return -1; } redirectError(cvErrorCallback); const char* keys = "{ h help | | print help message }" "{ f filter | | filter for test }" "{ w workdir | | set working directory }" "{ l list | | show all tests }" "{ d device | 0 | device id }" "{ i iters | 10 | iteration count }"; CommandLineParser cmd(argc, argv, keys); if (cmd.has("help") || !cmd.check()) { cmd.printMessage(); cmd.printErrors(); return 0; } int device = cmd.get<int>("device"); if (device < 0 || device >= num_devices) { cerr << "Invalid device ID" << endl; return -1; } DeviceInfo dev_info(device); if (!dev_info.isCompatible()) { cerr << "CUDA module isn't built for GPU #" << device << " " << dev_info.name() << ", CC " << dev_info.majorVersion() << '.' << dev_info.minorVersion() << endl; return -1; } setDevice(device); printShortCudaDeviceInfo(device); string filter = cmd.get<string>("filter"); string workdir = cmd.get<string>("workdir"); bool list = cmd.has("list"); int iters = cmd.get<int>("iters"); if (!filter.empty()) TestSystem::instance().setTestFilter(filter); if (!workdir.empty()) { if (workdir[workdir.size() - 1] != '/' && workdir[workdir.size() - 1] != '\\') workdir += '/'; TestSystem::instance().setWorkingDir(workdir); } if (list) TestSystem::instance().setListMode(true); TestSystem::instance().setNumIters(iters); cout << "\nNote: the timings for GPU don't include data transfer" << endl; TestSystem::instance().run(); return 0; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #ifdef MVFST_USE_LIBEV #include <glog/logging.h> #include <quic/common/QuicEventBase.h> namespace quic { namespace { void libEvTimeoutCallback( struct ev_loop* /* loop */, ev_timer* w, int /* revents */) { auto asyncTimeout = static_cast<QuicAsyncTimeout*>(w->data); if (asyncTimeout) { asyncTimeout->timeoutExpired(); } } } // namespace QuicAsyncTimeout::QuicAsyncTimeout(QuicLibevEventBase* evb) { CHECK(evb != nullptr); eventBase_ = evb; timeoutWatcher_.data = this; } QuicAsyncTimeout::~QuicAsyncTimeout() { ev_timer_stop(eventBase_->getLibevLoop(), &timeoutWatcher_); } void QuicAsyncTimeout::scheduleTimeout(double seconds) { ev_timer_init( &timeoutWatcher_, libEvTimeoutCallback, seconds /* after */, 0. /* repeat */); ev_timer_start(eventBase_->getLibevLoop(), &timeoutWatcher_); } void QuicAsyncTimeout::cancelTimeout() { ev_timer_stop(eventBase_->getLibevLoop(), &timeoutWatcher_); } void QuicEventBase::setBackingEventBase(QuicLibevEventBase* evb) { backingEvb_ = evb; } QuicLibevEventBase* QuicEventBase::getBackingEventBase() const { return backingEvb_; } void QuicEventBase::runInLoop( QuicEventBaseLoopCallback* callback, bool thisIteration) { return backingEvb_->runInLoop(callback, thisIteration); } void QuicEventBase::runInLoop(folly::Function<void()> cb, bool thisIteration) { return backingEvb_->runInLoop(std::move(cb), thisIteration); } void QuicEventBase::runAfterDelay( folly::Function<void()> cb, uint32_t milliseconds) { return backingEvb_->runAfterDelay(std::move(cb), milliseconds); } void QuicEventBase::runInEventBaseThreadAndWait( folly::Function<void()> fn) noexcept { return backingEvb_->runInEventBaseThreadAndWait(std::move(fn)); } bool QuicEventBase::isInEventBaseThread() const { return backingEvb_->isInEventBaseThread(); } bool QuicEventBase::scheduleTimeoutHighRes( QuicAsyncTimeout* obj, std::chrono::microseconds timeout) { return backingEvb_->scheduleTimeoutHighRes(obj, timeout); } bool QuicEventBase::loopOnce(int flags) { return backingEvb_->loopOnce(flags); } bool QuicEventBase::loop() { return backingEvb_->loop(); } void QuicEventBase::loopForever() { return backingEvb_->loopForever(); } bool QuicEventBase::loopIgnoreKeepAlive() { return backingEvb_->loopIgnoreKeepAlive(); } void QuicEventBase::terminateLoopSoon() { return backingEvb_->terminateLoopSoon(); } void QuicEventBase::scheduleTimeout( QuicTimerCallback* callback, std::chrono::milliseconds timeout) { return backingEvb_->scheduleTimeout(callback, timeout); } std::chrono::milliseconds QuicEventBase::getTimerTickInterval() const { return backingEvb_->getTimerTickInterval(); } QuicLibevEventBase::QuicLibevEventBase(struct ev_loop* loop) : ev_loop_(loop) {} void QuicLibevEventBase::runInLoop( folly::Function<void()> cb, bool /* thisIteration */) { cb(); } void QuicLibevEventBase::runInLoop( QuicEventBaseLoopCallback* callback, bool /* thisIteration */) { callback->runLoopCallback(); } void QuicLibevEventBase::runInEventBaseThreadAndWait( folly::Function<void()> fn) noexcept { fn(); } bool QuicTimer::Callback::isScheduled() const { return asyncTimeout_ != nullptr; } void QuicTimer::Callback::cancelTimeout() { if (asyncTimeout_) { asyncTimeout_->cancelTimeout(); asyncTimeout_.reset(); } } void QuicTimer::Callback::setAsyncTimeout( std::unique_ptr<QuicAsyncTimeout> asyncTimeout) { CHECK(!asyncTimeout_); asyncTimeout_ = std::move(asyncTimeout); } class EvTimer : public QuicAsyncTimeout { public: EvTimer(QuicLibevEventBase* evb, QuicTimer::Callback* cb) : QuicAsyncTimeout(evb), cb_(cb) {} void timeoutExpired() noexcept override { cb_->timeoutExpired(); } private: QuicTimer::Callback* cb_; }; void QuicLibevEventBase::scheduleTimeout( QuicTimer::Callback* callback, std::chrono::milliseconds timeout) { auto evTimer = std::make_unique<EvTimer>(this, callback); evTimer->scheduleTimeout(timeout.count() / 10000.); callback->setAsyncTimeout(std::move(evTimer)); } } // namespace quic #endif // MVFST_USE_LIBEV
#include <ionir/passes/pass.h> namespace ionir { Module::Module(ionshared::Ptr<Identifier> identifier, ionshared::Ptr<Context> context) : Construct(ConstructKind::Module), Identifiable(std::move(identifier)), context(std::move(context)) { // } void Module::accept(Pass &visitor) { visitor.visitModule(this->dynamicCast<Module>()); } Ast Module::getChildrenNodes() { return Construct::convertChildren( // TODO: What about normal scopes? Merge that with global scope. Or actually, module just uses global context, right? this->context->getGlobalScope() ); } bool Module::insertFunction(const ionshared::Ptr<Function> &function) { Scope globalScope = this->context->getGlobalScope(); std::string functionName = function->prototype->name; if (!globalScope->contains(functionName)) { globalScope->set( functionName, function ); return true; } return false; } ionshared::OptPtr<Function> Module::lookupFunction(std::string name) { ionshared::OptPtr<Construct> functionConstruct = this->context->getGlobalScope()->lookup(std::move(name)); if (ionshared::util::hasValue(functionConstruct) && functionConstruct->get()->constructKind == ConstructKind::Function) { return functionConstruct->get()->dynamicCast<Function>(); } return std::nullopt; } bool Module::mergeInto(const ionshared::Ptr<Module> &module) { auto localGlobalScopeMap = this->context->getGlobalScope()->unwrap(); std::vector<Scope> localScopes = this->context->getScopes(); std::vector<Scope> targetScopes = module->context->getScopes(); Scope targetGlobalScope = module->context->getGlobalScope(); Scope newGlobalScope = ionshared::util::makePtrSymbolTable<Construct>(); ionshared::Ptr<Context> newContext = std::make_shared<Context>(newGlobalScope); // Attempt to merge global scope. for (const auto &[key, construct] : localGlobalScopeMap) { if (!newGlobalScope->set(key, construct)) { return false; } } // Attempt to merge scopes. for (const auto &scope : localScopes) { // TODO: Use ionshared::util::vectorContains<T>(); Does the same thing. if (ionshared::util::locateInVector<Scope>(targetScopes, scope) != std::nullopt) { return false; } newContext->appendScope(scope); } // Update the target module's context. module->context = newContext; return true; } }
// Question => Print all the possible subarray #include<iostream> using namespace std; int main(){ int n; cout<<"Please enter the size of array: "; cin>>n; int arr[n]; for(int i=0; i<n; i++){ cout<<"Please enter elements in the array: "; cin>>arr[i]; } // Printing all the array for(int i=0; i<n; i++){ for(int j=i; j<n; j++){ for(int k=i; k<=j; k++){ cout<<arr[k]<<" "; }cout<<endl; } } }
#include <reactor/net/TcpServer.h> #include <assert.h> #include <iostream> #include <unistd.h> #include <reactor/base/SimpleLogger.h> #include <reactor/net/Channel.h> #include <reactor/net/TcpConnection.h> #include <reactor/net/TcpSocket.h> using namespace std; using namespace reactor::base; namespace reactor { namespace net { TcpServer::TcpServer(EventLoop *loop, const InetAddress &addr): loop_(loop), acceptor_(loop, addr), started_(false) { using namespace std::placeholders; acceptor_.set_new_connection_callback(std::bind(&TcpServer::on_connection, this, _1, _2, _3)); } TcpServer::~TcpServer() { } void TcpServer::start() { if (!started_) { acceptor_.listen(); started_ = true; } } void TcpServer::on_connection(int client, const InetAddress &client_addr, Timestamp time) { if (connection_cb_) { assert(connections_.find(client) == connections_.end()); TcpConnectionPtr conn = std::make_shared<TcpConnection>(loop_, client); using namespace std::placeholders; conn->set_connection_callback(connection_cb_); conn->set_message_callback(message_cb_); conn->set_write_complete_callback(write_complete_cb_); conn->set_close_callback(std::bind(&TcpServer::on_close, this, _1)); connections_[client] = conn; conn->connection_established(); } else { cout << "no connection callback, close it"; ::close(client); } } void TcpServer::on_close(const TcpConnectionPtr &conn) { assert(connections_[conn->fd()] == conn); InetAddress peer = conn->peer_address(); LOG(Info) << peer.host() << ":" << static_cast<long>(peer.port()) << " closed"; connections_.erase(conn->fd()); } } // namespace net } // namespace reactor
#include<iostream> #include<cstdio> #include<vector> #include<map> #include<stack> #include<string> #include<cstring> #include<algorithm> #include<queue> using namespace std; const int act[4][2] = {0,1,1,0,0,-1,-1,0}; const char sav[4] = {'R','D','L','U'}; struct node{ int x,y; string path; }; queue<node> line; int use[610][610],a[610][610],m,n; bool check(int x,int y) { if (use[x][y]) return false; if (x < 0 || x >= m || y < 0 || y >= n) return false; return true; } int main() { cin >> m >> n; int nx,ny; node s; scanf("%d%d%d%d",&s.x,&s.y,&nx,&ny); memset(use,0,sizeof(use)); use[s.x][s.y] = 1;s.path = ""; line.push(s); for (int i = 0;i < m; i++) for (int j = 0;j < n; j++) scanf("%d",&a[i][j]); while (!line.empty()) {node s = line.front();line.pop(); //printf("*%d %d\n",s.x,s.y); if (s.x == nx && s.y == ny) {cout << s.path.size() << endl; cout << s.path << endl; break; } for (int i = 0;i < 4; i++) if (!((1 << i)&a[s.x][s.y])) {//printf("%d %d %d\n",i,act[i][0],act[i][1]); node t; t.x = s.x + act[i][0]; t.y = s.y + act[i][1]; t.path = s.path + sav[i]; if (check(t.x,t.y)) {//printf("%d %d\n",t.x,t.y); line.push(t); use[t.x][t.y] = 1; } } } return 0; }
// Copyright (c) 2016 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <pika/init.hpp> #include <pika/runtime/config_entry.hpp> #include <pika/string_util/from_string.hpp> #include <pika/testing.hpp> #include <atomic> #include <string> void test_get_entry() { std::string val = pika::get_config_entry("pika.pu_step", "42"); PIKA_TEST(!val.empty()); PIKA_TEST_EQ(pika::detail::from_string<int>(val), 1); val = pika::get_config_entry("pika.pu_step", 42); PIKA_TEST(!val.empty()); PIKA_TEST_EQ(pika::detail::from_string<int>(val), 1); } std::atomic<bool> invoked_callback(false); void config_entry_callback(std::string const& key, std::string const& val) { PIKA_TEST_EQ(key, std::string("pika.config.entry.test")); PIKA_TEST_EQ(val, std::string("test1")); PIKA_TEST(!invoked_callback.load()); invoked_callback = true; } void test_set_entry() { std::string val = pika::get_config_entry("pika.config.entry.test", ""); PIKA_TEST(val.empty()); pika::set_config_entry("pika.config.entry.test", "test"); val = pika::get_config_entry("pika.config.entry.test", ""); PIKA_TEST(!val.empty()); PIKA_TEST_EQ(val, std::string("test")); pika::set_config_entry_callback("pika.config.entry.test", &config_entry_callback); pika::set_config_entry("pika.config.entry.test", "test1"); val = pika::get_config_entry("pika.config.entry.test", ""); PIKA_TEST(!val.empty()); PIKA_TEST_EQ(val, std::string("test1")); PIKA_TEST(invoked_callback.load()); } int pika_main() { test_get_entry(); test_set_entry(); return pika::finalize(); } int main(int argc, char** argv) { pika::init(pika_main, argc, argv); return 0; }
#include "CustomGraphicsView.h" #include "View/MainWindow/MainWindow.h" #include <QGraphicsProxyWidget> #include <QDebug> #include <QApplication> #include <QDesktopWidget> QSize CustomGraphicsView::getNormalSize() { return QSize(1920,1080); } CustomGraphicsView::CustomGraphicsView(QWidget *parent) : QGraphicsView(parent) { setFrameShape(QFrame::NoFrame); setLineWidth(0); setRenderHint(QPainter::Antialiasing); setRenderHint(QPainter::SmoothPixmapTransform); } CustomGraphicsView::CustomGraphicsView(QGraphicsScene *scene, QWidget *parent): QGraphicsView(scene, parent) { setFrameShape(QFrame::NoFrame); setLineWidth(0); setRenderHint(QPainter::Antialiasing); setRenderHint(QPainter::SmoothPixmapTransform); } void CustomGraphicsView::setMainWidget(QWidget *pWidget) { this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); if(scene()) { pWidget->installEventFilter(this); m_pMainWindow = pWidget; connect(pWidget,SIGNAL(destroyed(QObject*)),this,SLOT(deleteLater())); // this->setWindowFlags(pWidget->windowFlags()); QGraphicsProxyWidget *pProxyWidget = scene()->addWidget(pWidget,pWidget->windowFlags()); connect(pProxyWidget,&QGraphicsProxyWidget::geometryChanged,this,&CustomGraphicsView::slotGeometryChanged); pProxyWidget->setWindowFlags(pWidget->windowFlags()); connect(pProxyWidget,&QGraphicsProxyWidget::visibleChanged,this,[this,pWidget]{ if(pWidget->windowState().testFlag(Qt::WindowMinimized)) { this->showMinimized(); return; } setVisible(pWidget->isVisible()); }); connect(pProxyWidget, &QGraphicsProxyWidget::childrenChanged,this, [pProxyWidget]{ qDebug()<<__FUNCTION__<<pProxyWidget->childItems().count(); for(auto objItem : pProxyWidget->childItems()) { QGraphicsWidget *pGraphicsWidget = qobject_cast<QGraphicsWidget *>(objItem->toGraphicsObject()); if(pGraphicsWidget) { if(!pGraphicsWidget->windowFlags().testFlag(Qt::FramelessWindowHint)) { qDebug()<<__FUNCTION__<<"pGraphicsWidget->setWindowFlags"; pGraphicsWidget->setWindowFlags(pGraphicsWidget->windowFlags()|Qt::FramelessWindowHint); } } } }); } } bool CustomGraphicsView::event(QEvent *event) { bool isState = QGraphicsView::event(event); if(event->type()==QEvent::WindowStateChange) { if(this->windowState()!=(Qt::WindowMinimized|Qt::WindowFullScreen)&&m_pMainWindow) { m_pMainWindow->setWindowState(this->windowState()); } } return isState; } bool CustomGraphicsView::eventFilter(QObject *obj, QEvent *event) { bool result = QGraphicsView::eventFilter(obj,event); if(m_pMainWindow==obj) { if(event->type()==QEvent::Show) { this->show(); } else if(event->type()==QEvent::Close) { exit(0); } } return result; } void CustomGraphicsView::slotGeometryChanged() { QSize sizeNormal = CustomGraphicsView::getNormalSize(); if(m_pMainWindow->size()!=sizeNormal) { m_pMainWindow->setGeometry(0,0,sizeNormal.width(),sizeNormal.height()); // this->scale(double(this->width())/sizeNormal.width(),double(this->height())/sizeNormal.height()); } }
#include <algorithm> #include <cmath> #include <iostream> #include <limits> #include <utility> #include <vector> using ll = long long; template <typename Node> class SegmentTree { public: SegmentTree() = delete; SegmentTree(const std::vector<ll>& numbers) : m_size(numbers.size()), m_height(std::ceil(std::log2(m_size))), m_nodes((1 << m_height + 1), Node{}) { InitTree(numbers, 0, 0, m_size - 1); } Node GetSub(int idx, int start, int end, int left, int right) const { if (start > right || left > end) { return Node{}; } if (start >= left && right >= end) { return m_nodes[idx]; } Node leftResult = GetSub(2 * idx + 1, start, (start + end) / 2, left, right); Node rightResult = GetSub(2 * idx + 2, (start + end) / 2 + 1, end, left, right); return Node::Calculate(leftResult, rightResult); } private: Node InitTree(const std::vector<ll>& numbers, int idx, int start, int end) { if (start == end) { m_nodes[idx] = { numbers[start], numbers[start] }; } else { Node leftResult = InitTree(numbers, idx * 2 + 1, start, (start + end) / 2); Node rightResult = InitTree(numbers, idx * 2 + 2, (start + end) / 2 + 1, end); m_nodes[idx] = Node::Calculate(leftResult, rightResult); } return m_nodes[idx]; } std::size_t m_size, m_height; std::vector<Node> m_nodes; }; template <typename T> class SegmentNode { public: SegmentNode() : SegmentNode(std::numeric_limits<T>::max(), std::numeric_limits<T>::min()) { // Do nothing. } SegmentNode(T min, T max) : m_min(min), m_max(max) { // Do nothing. } static SegmentNode<T> Calculate(const SegmentNode<T>& left, const SegmentNode<T>& right) { return SegmentNode{ std::min(left.m_min, right.m_min), std::max(left.m_max, right.m_max) }; } T m_min, m_max; }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int N, M; std::cin >> N >> M; std::vector<ll> data; data.reserve(N); for (int i = 0; i < N; ++i) { ll t; std::cin >> t; data.push_back(t); } SegmentTree<SegmentNode<ll>> segtree(data); for (int i = 0; i < M; ++i) { int a, b; std::cin >> a >> b; SegmentNode<ll> n = segtree.GetSub(0, 0, data.size() - 1, a - 1, b - 1); std::cout << n.m_min << ' ' << n.m_max << '\n'; } }
#ifndef _MSG_0X06_SPAWNPOSITION_STC_H_ #define _MSG_0X06_SPAWNPOSITION_STC_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class SpawnPosition : public BaseMessage { public: SpawnPosition(); SpawnPosition(int32_t _x, int32_t _y, int32_t _z); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getX() const; int32_t getY() const; int32_t getZ() const; void setX(int32_t _val); void setY(int32_t _val); void setZ(int32_t _val); private: int32_t _pf_x; int32_t _pf_y; int32_t _pf_z; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X06_SPAWNPOSITION_STC_H_
#include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" #include "../Projectile.h" CLASS_DECLARATION( idPhysics_Base, rvPhysics_Particle ) END_CLASS const float PRT_OVERCLIP = 1.001f; const float PRT_BOUNCESTOP = 10.0f; /* ================ rvPhysics_Particle::DropToFloorAndRest Drops the object straight down to the floor ================ */ void rvPhysics_Particle::DropToFloorAndRest( void ) { idVec3 down; trace_t tr; if ( testSolid ) { testSolid = false; if ( gameLocal.Contents( self, current.origin, clipModel, clipModel->GetAxis(), clipMask, self ) ) { gameLocal.Warning( "entity in solid '%s' type '%s' at (%s)", self->name.c_str(), self->GetType()->classname, current.origin.ToString(0) ); PutToRest(); dropToFloor = false; return; } } // put the body on the floor down = current.origin + gravityNormal * 128.0f; // RAVEN BEGIN // ddynerman: multiple clip worlds gameLocal.Translation( self, tr, current.origin, down, clipModel, clipModel->GetAxis(), clipMask, self ); // RAVEN END current.origin = tr.endpos; // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, clipModel->GetId(), tr.endpos, clipModel->GetAxis() ); // RAVEN END // if on the floor already if ( tr.fraction == 0.0f ) { PutToRest(); EvaluateContacts();//Do a final contact check. Items that drop to floor never do this check otherwise dropToFloor = false; } else if ( IsOutsideWorld() ) { gameLocal.Warning( "entity outside world bounds '%s' type '%s' at (%s)", self->name.c_str(), self->GetType()->classname, current.origin.ToString(0) ); PutToRest(); dropToFloor = false; } } /* ================ rvPhysics_Particle::DebugDraw ================ */ void rvPhysics_Particle::DebugDraw( void ) { if ( rb_showBodies.GetBool() || ( rb_showActive.GetBool() && current.atRest < 0 ) ) { collisionModelManager->DrawModel( clipModel->GetCollisionModel(), clipModel->GetOrigin(), clipModel->GetAxis(), vec3_origin, mat3_identity, 0.0f ); } if ( rb_showContacts.GetBool() ) { int i; for ( i = 0; i < contacts.Num(); i ++ ) { idVec3 x, y; contacts[i].normal.NormalVectors( x, y ); gameRenderWorld->DebugLine( colorWhite, contacts[i].point, contacts[i].point + 6.0f * contacts[i].normal ); gameRenderWorld->DebugLine( colorWhite, contacts[i].point - 2.0f * x, contacts[i].point + 2.0f * x ); gameRenderWorld->DebugLine( colorWhite, contacts[i].point - 2.0f * y, contacts[i].point + 2.0f * y ); } } } /* ================ rvPhysics_Particle::rvPhysics_Particle ================ */ rvPhysics_Particle::rvPhysics_Particle( void ) { SetClipMask( MASK_SOLID ); SetBouncyness( 0.6f, true ); clipModel = NULL; memset( &current, 0, sizeof( current ) ); current.atRest = -1; current.origin.Zero(); saved = current; dropToFloor = false; testSolid = false; hasMaster = false; SetFriction( 0.6f, 0.6f, 0.0f ); SetBouncyness ( 0.5f, true ); gravityNormal.Zero(); } /* ================ rvPhysics_Particle::~rvPhysics_Particle ================ */ rvPhysics_Particle::~rvPhysics_Particle( void ) { if ( clipModel ) { delete clipModel; clipModel = NULL; } } /* ================ rvPhysics_Particle::Save ================ */ void rvPhysics_Particle::Save( idSaveGame *savefile ) const { savefile->WriteInt( current.atRest ); savefile->WriteVec3( current.localOrigin ); savefile->WriteMat3( current.localAxis ); savefile->WriteVec3( current.pushVelocity ); savefile->WriteVec3( current.origin ); savefile->WriteVec3( current.velocity ); savefile->WriteBool( current.onGround ); savefile->WriteBool( current.inWater ); // cnicholson: Added unsaved var savefile->WriteInt( saved.atRest ); // cnicholson: Added unsaved vars savefile->WriteVec3( saved.localOrigin ); savefile->WriteMat3( saved.localAxis ); savefile->WriteVec3( saved.pushVelocity ); savefile->WriteVec3( saved.origin ); savefile->WriteVec3( saved.velocity ); savefile->WriteBool( saved.onGround ); savefile->WriteBool( saved.inWater ); savefile->WriteFloat( linearFriction ); savefile->WriteFloat( angularFriction ); savefile->WriteFloat( contactFriction ); savefile->WriteFloat( bouncyness ); savefile->WriteBool ( allowBounce ); savefile->WriteBounds ( clipModel->GetBounds ( ) ); // cnicholson: Added unsaved var savefile->WriteBool( dropToFloor ); savefile->WriteBool( testSolid ); savefile->WriteBool( hasMaster ); savefile->WriteBool( isOrientated ); // cnicholson: Added unsaved var extraPassEntity.Save( savefile ); savefile->WriteClipModel( clipModel ); } /* ================ rvPhysics_Particle::Restore ================ */ void rvPhysics_Particle::Restore( idRestoreGame *savefile ) { savefile->ReadInt( current.atRest ); savefile->ReadVec3( current.localOrigin ); savefile->ReadMat3( current.localAxis ); savefile->ReadVec3( current.pushVelocity ); savefile->ReadVec3( current.origin ); savefile->ReadVec3( current.velocity ); savefile->ReadBool( current.onGround ); savefile->ReadBool( current.inWater ); // cnicholson: Added unsaved var savefile->ReadInt( saved.atRest ); // cnicholson: Added unsaved vars savefile->ReadVec3( saved.localOrigin ); savefile->ReadMat3( saved.localAxis ); savefile->ReadVec3( saved.pushVelocity ); savefile->ReadVec3( saved.origin ); savefile->ReadVec3( saved.velocity ); savefile->ReadBool( saved.onGround ); savefile->ReadBool( saved.inWater ); savefile->ReadFloat( linearFriction ); savefile->ReadFloat( angularFriction ); savefile->ReadFloat( contactFriction ); savefile->ReadFloat( bouncyness ); savefile->ReadBool ( allowBounce ); idBounds bounds; // cnicholson: Added unrestored var delete clipModel; savefile->ReadBounds ( bounds ); clipModel = new idClipModel ( idTraceModel ( bounds ) ); savefile->ReadBool( dropToFloor ); savefile->ReadBool( testSolid ); savefile->ReadBool( hasMaster ); savefile->ReadBool( isOrientated ); // cnicholson: Added unrestored var extraPassEntity.Restore( savefile ); savefile->ReadClipModel( clipModel ); } /* ================ rvPhysics_Particle::SetClipModel ================ */ void rvPhysics_Particle::SetClipModel( idClipModel *model, const float density, int id, bool freeOld ) { assert( self ); assert( model ); // we need a clip model assert( model->IsTraceModel() ); // and it should be a trace model if ( clipModel && clipModel != model && freeOld ) { delete clipModel; } clipModel = model; // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, 0, current.origin, clipModel->GetAxis() ); // RAVEN END } /* ================ rvPhysics_Particle::GetClipModel ================ */ idClipModel *rvPhysics_Particle::GetClipModel( int id ) const { return clipModel; } /* ================ rvPhysics_Particle::GetNumClipModels ================ */ int rvPhysics_Particle::GetNumClipModels( void ) const { return 1; } /* ================ rvPhysics_Particle::SetBouncyness ================ */ void rvPhysics_Particle::SetBouncyness( const float b, bool _allowBounce ) { allowBounce = _allowBounce; if ( b < 0.0f || b > 1.0f ) { return; } bouncyness = b; } /* ================ rvPhysics_Particle::SetFriction ================ */ void rvPhysics_Particle::SetFriction( const float linear, const float angular, const float contact ) { linearFriction = linear; angularFriction = angular; contactFriction = contact; } /* ================ rvPhysics_Particle::PutToRest ================ */ void rvPhysics_Particle::PutToRest( void ) { current.atRest = gameLocal.time; current.velocity.Zero(); self->BecomeInactive( TH_PHYSICS ); } /* ================ rvPhysics_Particle::DropToFloor ================ */ void rvPhysics_Particle::DropToFloor( void ) { dropToFloor = true; testSolid = true; } /* ================ rvPhysics_Particle::Activate ================ */ void rvPhysics_Particle::Activate( void ) { current.atRest = -1; self->BecomeActive( TH_PHYSICS ); } /* ================ rvPhysics_Particle::EvaluateContacts ================ */ bool rvPhysics_Particle::EvaluateContacts( void ) { ClearContacts(); AddGroundContacts( clipModel ); AddContactEntitiesForContacts(); return ( contacts.Num() != 0 ); } /* ================ rvPhysics_Particle::SetContents ================ */ void rvPhysics_Particle::SetContents( int contents, int id ) { clipModel->SetContents( contents ); } /* ================ rvPhysics_Particle::GetContents ================ */ int rvPhysics_Particle::GetContents( int id ) const { return clipModel->GetContents(); } /* ================ rvPhysics_Particle::GetBounds ================ */ const idBounds &rvPhysics_Particle::GetBounds( int id ) const { return clipModel->GetBounds(); } /* ================ rvPhysics_Particle::GetAbsBounds ================ */ const idBounds &rvPhysics_Particle::GetAbsBounds( int id ) const { return clipModel->GetAbsBounds(); } /* ================ rvPhysics_Particle::Evaluate Evaluate the impulse based rigid body physics. When a collision occurs an impulse is applied at the moment of impact but the remaining time after the collision is ignored. ================ */ bool rvPhysics_Particle::Evaluate( int timeStepMSec, int endTimeMSec ) { particlePState_t next; float timeStep; float upspeed; timeStep = MS2SEC( timeStepMSec ); // if bound to a master if ( hasMaster ) { idVec3 masterOrigin; idMat3 masterAxis; idVec3 oldOrigin; oldOrigin = current.origin; self->GetMasterPosition( masterOrigin, masterAxis ); current.origin = masterOrigin + current.localOrigin * masterAxis; // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, clipModel->GetId(), current.origin, current.localAxis * masterAxis ); // RAVEN END trace_t tr; gameLocal.Translation( self, tr, oldOrigin, current.origin, clipModel, clipModel->GetAxis(), clipMask, self ); if ( tr.fraction < 1.0f ) { self->Collide ( tr, current.origin - oldOrigin ); } DebugDraw(); return true; } // if the body is at rest if ( current.atRest >= 0 || timeStep <= 0.0f ) { DebugDraw(); return false; } // if putting the body to rest if ( dropToFloor ) { DropToFloorAndRest(); return true; } clipModel->Unlink(); // Determine if currently on the ground CheckGround ( ); // Determine the current upward velocity if ( gravityNormal != vec3_zero ) { upspeed = -( current.velocity * gravityNormal ); } else { upspeed = current.velocity.z; } // If not on the ground, or moving upwards, or bouncing and moving toward gravity then do a straight // forward slide move and gravity. if ( !current.onGround || upspeed > 1.0f || (bouncyness > 0.0f && upspeed < -PRT_BOUNCESTOP && !current.inWater) ) { // Force ground off when moving upward if ( upspeed > 0.0f ) { current.onGround = false; } SlideMove( current.origin, current.velocity, current.velocity * timeStep ); if ( current.onGround && upspeed < PRT_BOUNCESTOP ) { current.velocity -= ( current.velocity * gravityNormal ) * gravityNormal; } else { current.velocity += (gravityVector * timeStep); } } else { idVec3 delta; // Slow down due to friction ApplyFriction ( timeStep ); delta = current.velocity * timeStep; current.velocity -= ( current.velocity * gravityNormal ) * gravityNormal; if ( delta == vec3_origin ) { PutToRest( ); } else { SlideMove( current.origin, current.velocity, delta ); } } // update the position of the clip model // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, clipModel->GetId(), current.origin, clipModel->GetAxis() ); // RAVEN END DebugDraw(); // get all the ground contacts EvaluateContacts(); current.pushVelocity.Zero(); if ( IsOutsideWorld() ) { gameLocal.Warning( "clip model outside world bounds for entity '%s' at (%s)", self->name.c_str(), current.origin.ToString(0) ); PutToRest(); } return true; } /* ================ rvPhysics_Particle::UpdateTime ================ */ void rvPhysics_Particle::UpdateTime( int endTimeMSec ) { } /* ================ rvPhysics_Particle::GetTime ================ */ int rvPhysics_Particle::GetTime( void ) const { return gameLocal.time; } /* ================ rvPhysics_Particle::IsAtRest ================ */ bool rvPhysics_Particle::IsAtRest( void ) const { return current.atRest >= 0; } /* ================ rvPhysics_Particle::GetRestStartTime ================ */ int rvPhysics_Particle::GetRestStartTime( void ) const { return current.atRest; } /* ================ rvPhysics_Particle::IsPushable ================ */ bool rvPhysics_Particle::IsPushable( void ) const { return ( !hasMaster ); } /* ================ rvPhysics_Particle::SaveState ================ */ void rvPhysics_Particle::SaveState( void ) { saved = current; } /* ================ rvPhysics_Particle::RestoreState ================ */ void rvPhysics_Particle::RestoreState( void ) { current = saved; // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, clipModel->GetId(), current.origin, clipModel->GetAxis() ); // RAVEN END EvaluateContacts(); } /* ================ idPhysics::SetOrigin ================ */ void rvPhysics_Particle::SetOrigin( const idVec3 &newOrigin, int id ) { idVec3 masterOrigin; idMat3 masterAxis; current.localOrigin = newOrigin; if ( hasMaster ) { self->GetMasterPosition( masterOrigin, masterAxis ); current.origin = masterOrigin + newOrigin * masterAxis; } else { current.origin = newOrigin; } // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, clipModel->GetId(), current.origin, clipModel->GetAxis() ); // RAVEN END Activate(); } /* ================ idPhysics::SetAxis ================ */ void rvPhysics_Particle::SetAxis( const idMat3 &newAxis, int id ) { current.localAxis = newAxis; // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, 0, clipModel->GetOrigin(), newAxis ); // RAVEN END Activate(); } /* ================ rvPhysics_Particle::Translate ================ */ void rvPhysics_Particle::Translate( const idVec3 &translation, int id ) { current.localOrigin += translation; current.origin += translation; // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, clipModel->GetId(), current.origin, clipModel->GetAxis() ); // RAVEN END Activate(); } /* ================ rvPhysics_Particle::Rotate( ================ */ void rvPhysics_Particle::Rotate( const idRotation &rotation, int id ) { idVec3 masterOrigin; idMat3 masterAxis; current.origin *= rotation; if ( hasMaster ) { self->GetMasterPosition( masterOrigin, masterAxis ); current.localOrigin = ( current.origin - masterOrigin ) * masterAxis.Transpose(); } else { current.localOrigin = current.origin; } // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, 0, current.origin, clipModel->GetAxis() * rotation.ToMat3() ); // RAVEN END Activate(); } /* ================ rvPhysics_Particle::GetOrigin ================ */ const idVec3 &rvPhysics_Particle::GetOrigin( int id ) const { return clipModel->GetOrigin(); } /* ================ rvPhysics_Particle::GetAxis ================ */ const idMat3 &rvPhysics_Particle::GetAxis( int id ) const { if ( !clipModel ) { return idPhysics_Base::GetAxis ( id ); } return clipModel->GetAxis(); } /* ================ rvPhysics_Particle::SetLinearVelocity ================ */ void rvPhysics_Particle::SetLinearVelocity( const idVec3 &velocity, int id ) { current.velocity = velocity; Activate(); } /* ================ rvPhysics_Particle::GetLinearVelocity ================ */ const idVec3 &rvPhysics_Particle::GetLinearVelocity( int id ) const { return current.velocity; } /* ================ rvPhysics_Particle::ClipTranslation ================ */ void rvPhysics_Particle::ClipTranslation( trace_t &results, const idVec3 &translation, const idClipModel *model ) const { if ( model ) { gameLocal.TranslationModel( self, results, clipModel->GetOrigin(), clipModel->GetOrigin() + translation, clipModel, clipModel->GetAxis(), clipMask, model->GetCollisionModel(), model->GetOrigin(), model->GetAxis() ); } else { gameLocal.Translation( self, results, clipModel->GetOrigin(), clipModel->GetOrigin() + translation, clipModel, clipModel->GetAxis(), clipMask, self ); } } /* ================ rvPhysics_Particle::ClipRotation ================ */ void rvPhysics_Particle::ClipRotation( trace_t &results, const idRotation &rotation, const idClipModel *model ) const { if ( model ) { gameLocal.RotationModel( self, results, clipModel->GetOrigin(), rotation, clipModel, clipModel->GetAxis(), clipMask, model->GetCollisionModel(), model->GetOrigin(), model->GetAxis() ); } else { gameLocal.Rotation( self, results, clipModel->GetOrigin(), rotation, clipModel, clipModel->GetAxis(), clipMask, self ); } } /* ================ rvPhysics_Particle::ClipContents ================ */ int rvPhysics_Particle::ClipContents( const idClipModel *model ) const { if ( model ) { return gameLocal.ContentsModel( self, clipModel->GetOrigin(), clipModel, clipModel->GetAxis(), -1, model->GetCollisionModel(), model->GetOrigin(), model->GetAxis() ); } else { return gameLocal.Contents( self, clipModel->GetOrigin(), clipModel, clipModel->GetAxis(), -1, NULL ); } } /* ================ rvPhysics_Particle::DisableClip ================ */ void rvPhysics_Particle::DisableClip( void ) { clipModel->Disable(); } /* ================ rvPhysics_Particle::EnableClip ================ */ void rvPhysics_Particle::EnableClip( void ) { clipModel->Enable(); } /* ================ rvPhysics_Particle::UnlinkClip ================ */ void rvPhysics_Particle::UnlinkClip( void ) { clipModel->Unlink(); } /* ================ rvPhysics_Particle::LinkClip ================ */ void rvPhysics_Particle::LinkClip( void ) { // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, clipModel->GetId(), current.origin, clipModel->GetAxis() ); // RAVEN END } /* ================ rvPhysics_Particle::SetPushed ================ */ void rvPhysics_Particle::SetPushed( int deltaTime ) { // velocity with which the particle is pushed current.pushVelocity = ( current.origin - saved.origin ) / ( deltaTime * idMath::M_MS2SEC ); } /* ================ rvPhysics_Particle::GetPushedLinearVelocity ================ */ const idVec3 &rvPhysics_Particle::GetPushedLinearVelocity( const int id ) const { return current.pushVelocity; } /* ================ rvPhysics_Particle::SetMaster ================ */ void rvPhysics_Particle::SetMaster( idEntity *master, const bool orientated ) { idVec3 masterOrigin; idMat3 masterAxis; if ( master ) { if ( !hasMaster ) { // transform from world space to master space self->GetMasterPosition( masterOrigin, masterAxis ); current.localOrigin = ( current.origin - masterOrigin ) * masterAxis.Transpose(); hasMaster = true; } ClearContacts(); } else { if ( hasMaster ) { hasMaster = false; Activate(); } } } /* ===================== rvPhysics_Particle::CheckGround ===================== */ void rvPhysics_Particle::CheckGround( void ) { trace_t groundTrace; idVec3 down; if ( gravityNormal == vec3_zero ) { current.onGround = false; return; } down = current.origin + gravityNormal * CONTACT_EPSILON; gameLocal.Translation( self, groundTrace, current.origin, down, clipModel, clipModel->GetAxis(), clipMask, self ); if ( groundTrace.fraction == 1.0f ) { current.onGround = false; return; } if ( ( groundTrace.c.normal * -gravityNormal ) < 0.7f ) { current.onGround = false; return; } current.onGround = true; } /* ================ rvPhysics_Particle::ApplyFriction ================ */ void rvPhysics_Particle::ApplyFriction( float timeStep ) { idVec3 vel; float speed; float newspeed; // ignore slope movement, remove all velocity in gravity direction vel = current.velocity + (current.velocity * gravityNormal) * gravityNormal; speed = vel.Length(); if ( speed < 1.0f ) { // remove all movement orthogonal to gravity, allows for sinking underwater current.velocity = (current.velocity * gravityNormal) * gravityNormal; return; } // scale the velocity if ( current.onGround ) { newspeed = speed - ((speed * contactFriction) * timeStep); } else { newspeed = speed - ((speed * linearFriction) * timeStep); } if (newspeed < 0) { newspeed = 0; } current.velocity *= ( newspeed / speed ); } /* ================ rvPhysics_Particle::SlideMove ================ */ bool rvPhysics_Particle::SlideMove( idVec3 &start, idVec3 &velocity, const idVec3 &delta ) { int i; trace_t tr; idVec3 move; bool collide, rtnValue = false; move = delta; for( i = 0; i < 3; i++ ) { // be sure if you change this upper value in the for() to update the exit condition below!!!!! gameLocal.Translation( self, tr, start, start + move, clipModel, clipModel->GetAxis(), clipMask, self, extraPassEntity ); start = tr.endpos; if ( tr.fraction == 1.0f ) { if ( i > 0 ) { return false; } return true; } bool hitTeleporter = false; // let the entity know about the collision collide = self->Collide( tr, current.velocity, hitTeleporter ); idEntity* ent; ent = gameLocal.entities[tr.c.entityNum]; assert ( ent ); // If we hit water just clip the move for now and keep on going if ( ent->GetPhysics()->GetContents() & CONTENTS_WATER ) { // Make sure we dont collide with water again clipMask &= ~CONTENTS_WATER; current.inWater = true; // Allow the loop to go one more round to push us through the water i--; velocity *= 0.4f; move.ProjectOntoPlane( tr.c.normal, PRT_OVERCLIP ); continue; // bounce the projectile } else if ( !current.inWater && allowBounce && bouncyness ) { if ( !hitTeleporter ) { float dot; move = tr.endpos; dot = DotProduct( velocity, tr.c.normal ); velocity = ( velocity - ( 2.0f * dot * tr.c.normal ) ) * bouncyness; } return true; //RAVEN BEGIN //jshepard: tr.c.material can (did) crash here if null } else if ( allowBounce && tr.c.material && (tr.c.material->GetSurfaceFlags ( ) & SURF_BOUNCE) ) { //RAVEN END float dot; move = tr.endpos; dot = DotProduct( velocity, tr.c.normal ); velocity = ( velocity - ( 2.0f * dot * tr.c.normal ) ); return true; } // RAVEN BEGIN // dluetscher: removed redundant trace calls else { i = 4; rtnValue = true; } // RAVEN END // clip the movement delta and velocity if( collide ) { move.ProjectOntoPlane( tr.c.normal, PRT_OVERCLIP ); velocity.ProjectOntoPlane( tr.c.normal, PRT_OVERCLIP ); } } return rtnValue; } const float PRT_VELOCITY_MAX = 16000; const int PRT_VELOCITY_TOTAL_BITS = 16; const int PRT_VELOCITY_EXPONENT_BITS = idMath::BitsForInteger( idMath::BitsForFloat( PRT_VELOCITY_MAX ) ) + 1; const int PRT_VELOCITY_MANTISSA_BITS = PRT_VELOCITY_TOTAL_BITS - 1 - PRT_VELOCITY_EXPONENT_BITS; /* ================ rvPhysics_Particle::WriteToSnapshot ================ */ void rvPhysics_Particle::WriteToSnapshot( idBitMsgDelta &msg ) const { msg.WriteLong( current.atRest ); msg.WriteBits ( current.onGround, 1 ); msg.WriteFloat( current.origin[0] ); msg.WriteFloat( current.origin[1] ); msg.WriteFloat( current.origin[2] ); // msg.WriteFloat( current.velocity[0], PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); // msg.WriteFloat( current.velocity[1], PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); // msg.WriteFloat( current.velocity[2], PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); msg.WriteDeltaFloat( 0.0f, current.velocity[0] ); msg.WriteDeltaFloat( 0.0f, current.velocity[1] ); msg.WriteDeltaFloat( 0.0f, current.velocity[2] ); // msg.WriteDeltaFloat( 0.0f, current.pushVelocity[0], PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); // msg.WriteDeltaFloat( 0.0f, current.pushVelocity[1], PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); // msg.WriteDeltaFloat( 0.0f, current.pushVelocity[2], PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); msg.WriteDeltaFloat( 0.0f, current.pushVelocity[0] ); msg.WriteDeltaFloat( 0.0f, current.pushVelocity[1] ); msg.WriteDeltaFloat( 0.0f, current.pushVelocity[2] ); // TODO: Check that this conditional write to delta message is OK if ( hasMaster ) { idCQuat localQuat; localQuat = current.localAxis.ToCQuat(); msg.WriteBits ( 1, 1 ); msg.WriteFloat( localQuat.x ); msg.WriteFloat( localQuat.y ); msg.WriteFloat( localQuat.z ); msg.WriteDeltaFloat( current.origin[0], current.localOrigin[0] ); msg.WriteDeltaFloat( current.origin[1], current.localOrigin[1] ); msg.WriteDeltaFloat( current.origin[2], current.localOrigin[2] ); } else { msg.WriteBits ( 0, 1 ); } } /* ================ rvPhysics_Particle::ReadFromSnapshot ================ */ void rvPhysics_Particle::ReadFromSnapshot( const idBitMsgDelta &msg ) { current.atRest = msg.ReadLong(); current.onGround = ( msg.ReadBits( 1 ) != 0 ); current.origin[0] = msg.ReadFloat(); current.origin[1] = msg.ReadFloat(); current.origin[2] = msg.ReadFloat(); // current.velocity[0] = msg.ReadFloat( PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); // current.velocity[1] = msg.ReadFloat( PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); // current.velocity[2] = msg.ReadFloat( PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); current.velocity[0] = msg.ReadDeltaFloat( 0.0f ); current.velocity[1] = msg.ReadDeltaFloat( 0.0f ); current.velocity[2] = msg.ReadDeltaFloat( 0.0f ); // current.pushVelocity[0] = msg.ReadDeltaFloat( 0.0f, PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); // current.pushVelocity[1] = msg.ReadDeltaFloat( 0.0f, PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); // current.pushVelocity[2] = msg.ReadDeltaFloat( 0.0f, PRT_VELOCITY_EXPONENT_BITS, PRT_VELOCITY_MANTISSA_BITS ); current.pushVelocity[0] = msg.ReadDeltaFloat( 0.0f ); current.pushVelocity[1] = msg.ReadDeltaFloat( 0.0f ); current.pushVelocity[2] = msg.ReadDeltaFloat( 0.0f ); if ( msg.ReadBits ( 1 ) ) { idCQuat localQuat; localQuat.x = msg.ReadFloat( ); localQuat.y = msg.ReadFloat( ); localQuat.z = msg.ReadFloat( ); current.localOrigin[0] = msg.ReadDeltaFloat( current.origin[0] ); current.localOrigin[1] = msg.ReadDeltaFloat( current.origin[1] ); current.localOrigin[2] = msg.ReadDeltaFloat( current.origin[2] ); current.localAxis = localQuat.ToMat3(); } if ( clipModel ) { // RAVEN BEGIN // ddynerman: multiple clip worlds clipModel->Link( self, clipModel->GetId(), current.origin, clipModel->GetAxis() ); // RAVEN END } }
#include "op_info.h" #include "Transaction.h" #include "Ledger.h" #include "Witness.h" #include "util/keys.h" #include "OpContext.h" namespace credb { namespace trusted { Transaction::Transaction(IsolationLevel isolation, Ledger &ledger_, const OpContext &op_context_, LockHandle *lock_handle_) : m_isolation(isolation), ledger(ledger_), op_context(op_context_), lock_handle(ledger_, lock_handle_) { } Transaction::Transaction(bitstream &request, Ledger &ledger_, const OpContext &op_context_) : ledger(ledger_), op_context(op_context_), lock_handle(ledger) { request >> reinterpret_cast<uint8_t&>(m_isolation) >> generate_witness; if(isolation_level() == IsolationLevel::Serializable) { // FIXME: how to avoid phantom read while avoiding locking all shards? for(shard_id_t i = 0; i < NUM_SHARDS; ++i) { m_shard_lock_types[i] = LockType::Read; } } // construct op history and also collect shards_lock_type uint32_t ops_size = 0; request >> ops_size; for(uint32_t i = 0; i < ops_size; ++i) { auto op = new_operation_info_from_req(request); if(!op) { return; } register_operation(op); } } Transaction::~Transaction() { clear(); } void Transaction::clear() { lock_handle.clear(); if(!lock_handle.has_parent()) { for(auto &kv : m_shard_lock_types) { ledger.organize_ledger(kv.first); } } for(auto op: m_ops) { delete op; } m_ops.clear(); } void Transaction::set_read_lock(shard_id_t sid) { if(!m_shard_lock_types.count(sid)) { m_shard_lock_types[sid] = LockType::Read; } } void Transaction::set_write_lock(shard_id_t sid) { m_shard_lock_types[sid] = LockType::Write; } bool Transaction::check_repeatable_read(ObjectEventHandle &obj, const std::string &collection, const std::string &full_path, shard_id_t sid, const event_id_t &eid) { auto [key, path] = parse_path(full_path); (void)path; //if eid hasn't changed value hasn't change either so no need to check path const LockType lock_type = m_shard_lock_types[sid]; event_id_t latest_eid; obj = ledger.get_latest_version(op_context, collection, key, "", latest_eid, lock_handle, lock_type); if(!obj.valid() || latest_eid != eid) { error = "Key [" + key + "] reads outdated value"; return false; } return true; } operation_info_t *Transaction::new_operation_info_from_req(bitstream &req) { OperationType op; req >> reinterpret_cast<uint8_t &>(op); switch(op) { case OperationType::GetObject: return new get_info_t(*this, req); case OperationType::HasObject: return new has_obj_info_t(*this, req); case OperationType::CheckObject: return new check_obj_info_t(*this, req); case OperationType::PutObject: return new put_info_t(*this, req); case OperationType::AddToObject: return new add_info_t(*this, req); case OperationType::FindObjects: return new find_info_t(*this, req); case OperationType::RemoveObject: return new remove_info_t(*this, req); default: this->error = "Unknown OperationType " + std::to_string(static_cast<uint8_t>(op)); log_error(this->error); return nullptr; } } void Transaction::register_operation(operation_info_t *op) { m_ops.push_back(op); op->collect_shard_lock_type(); } bool Transaction::phase_one() { // first acquire locks for all pending shards to ensure atomicity for(auto &kv : m_shard_lock_types) { lock_handle.get_shard(kv.first, kv.second); } // witness root if(generate_witness) { writer.start_map(); // TODO: timestamp switch(isolation_level()) { case IsolationLevel::ReadCommitted: writer.write_string("isolation", "ReadCommitted"); break; case IsolationLevel::RepeatableRead: writer.write_string("isolation", "RepeatableRead"); break; case IsolationLevel::Serializable: writer.write_string("isolation", "Serializable"); break; } writer.start_array(Witness::OP_FIELD_NAME); } // validate reads for(auto op : m_ops) { if(!op->validate()) { return false; } } return true; } Witness Transaction::phase_two() { std::unordered_set<event_id_t> read_set, write_set; std::array<uint16_t, NUM_SHARDS> write_shards; write_shards.fill(0); for(auto op : m_ops) { op->extract_reads(read_set); op->extract_writes(write_shards); } for(shard_id_t shard = 0; shard < write_shards.size(); ++shard) { auto num = write_shards[shard]; if(num > 0) { ledger.get_next_event_ids(write_set, shard, num, &lock_handle); } } for(auto op : m_ops) { if(!op->do_write(read_set, write_set)) { assert(!error.empty()); throw std::runtime_error(error); } } Witness witness; if(generate_witness) { writer.end_array(); // operations writer.end_map(); // witness root } if(error.empty()) { if(generate_witness) { json::Document doc = writer.make_document(); witness.set_data(std::move(doc.data())); if(!sign_witness(ledger.m_enclave, witness)) { error = "cannot sign witness"; } } } bitstream bstream; if(!error.empty()) { throw std::runtime_error(error); } return witness; } Witness Transaction::commit() { if(!phase_one()) { throw std::runtime_error(error); } return phase_two(); } } }
#ifndef SparkComms_h #define SparkComms_h #define HW_BAUD 1000000 #include "BluetoothSerial.h" // Bluetooth vars #define SPARK_NAME "Spark 40 Audio" #define MY_NAME "Heltec" class SparkComms { public: SparkComms(); ~SparkComms(); void start_ser(); void start_bt(); void connect_to_spark(); // bluetooth communications BluetoothSerial *bt; HardwareSerial *ser; }; #endif
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10071" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int speed,time; while( ~scanf("%d %d",&speed,&time) ) printf("%d\n",speed*time*2 ); return 0; }
#include <chuffed/branching/branching.h> #include <chuffed/core/engine.h> #include <chuffed/core/propagator.h> #include <chuffed/vars/modelling.h> #include <cassert> #include <cstdio> class ProblemName : public Problem { public: // Constants int n; // size of problem // Core variables vec<IntVar*> x; // some vars // Intermediate variables //... ProblemName(int _n) : n(_n) { // Create vars createVars(x, n, 1, n); // Post some constraints all_different(x); // Post some branchings branch(x, VAR_INORDER, VAL_MIN); // Declare output variables (optional) output_vars(x); // Declare symmetries (optional) var_sym_break(x); } // Function to print out solution void print(std::ostream& out) override { for (int i = 0; i < n; i++) { out << x[i]->getVal() << ", "; } out << "\n"; }; }; int main(int argc, char** argv) { parseOptions(argc, argv); int n; assert(argc == 2); n = atoi(argv[1]); engine.solve(new ProblemName(n)); return 0; }
#pragma once #include "ARPG.h" #include "Components/ActorComponent.h" #include "Struct/SkillInfo/SkillInfo.h" #include "Struct/SkillProgressInfo/SkillProgressInfo.h" #include "SkillControllerComponent.generated.h" UCLASS() class ARPG_API USkillControllerComponent : public UActorComponent { GENERATED_BODY() private : class UDataTable* DT_SkillInfo; private : class ABaseLevelScriptActor* CurrentLevel; // 플레이어 캐릭터를 나타냅니다. class APlayerCharacter* PlayerCharacter; // 현재 실행중인 스킬 정보를 나타냅니다. FSkillInfo* CurrentSkillInfo; // 바로 이전에 실행시킨 스킬 정보를 나타냅니다. FSkillInfo* PrevSkillInfo; // 실행했었던 스킬 정보를 담아둘 맵 /// - 콤보와 쿨타임을 계산하기 위해 사용됩니다. TMap<FName, FSkillProgressInfo> UsedSkillInfo; // 실행시킬 스킬들을 담아둘 큐 TQueue<FSkillInfo*> SkillQueue; // 입력된 스킬 카운트를 나타냅니다. int32 SkillCount; // 스킬을 요청할 수 있음을 나타냅니다. /// - 이 값이 false 라면 스킬 실행을 요청할 수 없습니다. bool bIsRequestable; public: USkillControllerComponent(); public: virtual void BeginPlay() override; virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; private : // 스킬을 순서대로 처리합니다. void SkillProcedure(); // 사용된 스킬 상태를 갱신합니다. void UpdateUsedSkillInfo(FSkillInfo* newSkillInfo); // 스킬을 시전합니다. void CastSkill(FSkillInfo* skillInfo); void MakeSkillRange( FSkillInfo * skillInfo, FVector tracingStart, FVector tracingEnd, float radius, FName profileName); public : // 스킬 실행을 요청합니다. /// - skillCode : 요청시킬 스킬 코드를 전달합니다. void RequestSkill(FName skillCode); public : // 스킬 요청 가능 상태를 설정합니다. FORCEINLINE void SetSkillRequestable(bool bRequestable) { bIsRequestable = bRequestable; } // 스킬이 끝났음을 알립니다. void SkillFinished(); // 스킬 범위 인덱스를 다음 인덱스로 변경합니다. void NextSkillRangeIndex(); // 스킬 범위를 생성합니다. void MakeSkillRange(); };
#pragma once #ifdef _WINDOWS #include <GL/glew.h> #endif #include <SDL.h> #include <SDL_opengl.h> #include <SDL_image.h> #include "SDL_mixer.h" #include <vector> #include "ShaderProgram.h" #include "Matrix.h" #include "Bullet.h" #ifdef _WINDOWS #define RESOURCE_FOLDER "" #else #define RESOURCE_FOLDER "NYUCodebase.app/Contents/Resources/" #endif class Game{ public: Game(); ~Game(); void createInvaders(); void collision(); bool checkWin(); void RenderMainMenu(); void RenderGame(); void RenderGameOver(); void Setup(); void ProcessInput(); void Update(); void Render(); bool UpdateAndRender(); enum GameState{STATE_MAIN_MENU, STATE_GAME, STATE_GAME_OVER}; void DrawText(int fontTexture, std::string text, float size, float spacing); private: Entity player; std::vector<Bullet*>bullets; std::vector<Entity> row1_Invaders; std::vector<Entity> row2_Invaders; std::vector<Entity> row3_Invaders; SDL_Window* displayWindow; ShaderProgram* program; Mix_Music *music; Mix_Chunk *shoot; Matrix modelMatrix; Matrix viewMatrix; Matrix projectionMatrix; GLuint fontID; GLuint playerID; GLuint bulletTexture; GLuint enemyID; int state; float lastFrameTicks; float elapsed; bool done; };
#include <bits/stdc++.h> using namespace std; // clang-format off #define f first #define s second #define pb push_back #define rep(i, begin, end) \ for (__typeof(end) i = (begin) - ((begin) > (end)); \ i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define db(x) cout << '>' << #x << ':' << x << endl; #define sz(x) ((int)(x).size()) #define newl cout << "\n" #define ll long long int #define vi vector<int> #define vll vector<long long> #define vvll vector<vll> #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; struct hash_pair { template <class T1, class T2> size_t operator()(const pair<T1, T2> &p) const { auto hash1 = hash<T1>{}(p.first); auto hash2 = hash<T2>{}(p.second); return hash1 ^ hash2; } }; // unordered_map<pll, ll, hash_pair> hm; // clang-format on int main() { fast_io(); #ifndef ONLINE_JUDGE freopen("../input.txt", "r", stdin); freopen("../output.txt", "w", stdout); #endif return 0; }
#include <iostream> #include <cstring> using namespace std; string sentence; int num; int count=0; int main(){ ios_base :: sync_with_stdio(false); cin.tie(0); cin>>num; cin.ignore(); while(num--){ getline(cin,sentence); count=0; int len = sentence.size(); for(int i = 0; i < len; i++){ if(sentence[i] == 'i' || sentence[i] == 'a' || sentence[i] == 'u' || sentence[i] == 'e' || sentence[i] == 'o'){ cout<<sentence[i]; count++; } if(sentence[i] == 'I' || sentence[i] == 'A' || sentence[i] == 'U' || sentence[i] == 'E' || sentence[i] == 'O'){ cout<<sentence[i]; count++; } } if(!count) cout<<"???\n"; else cout<<"\n"; fill(sentence.begin(),sentence.end(),NULL); } }
/* * File: Ojos.cpp * Author: raul * * Created on 21 de enero de 2014, 20:47 */ #include "Ojos.h" Ojos::Ojos() { } Ojos::Ojos(GLdouble radio, GLdouble largo) : ObjetoCompuesto(2) { _radio = radio; _largo = largo; _componentes[0] = new Cilindro(_radio, _radio, _largo, 40, 1); _componentes[1] = new Cilindro(_radio, _radio, _largo, 40, 1); } void Ojos::dibuja() { // Light1 GLfloat position[] = {-(_radio * 1.5), 0.0, 0.0, 1.0}; glLightfv(GL_LIGHT1, GL_POSITION, position); // Posición de la luz glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 45.0); GLfloat direction[] = {0.0, 0.0, 1.0}; glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, direction); glPushMatrix(); glRotated(90, 1.0, 0.0, 0.0); glTranslated(-(_radio * 1.5), 0.0, 0.0); _componentes[0]->dibuja(); glPopMatrix(); glPushMatrix(); glRotated(90, 1.0, 0.0, 0.0); glTranslated(_radio * 1.5, 0.0, 0.0); _componentes[1]->dibuja(); glPopMatrix(); }
/* * I2C address change for MLX90640 */ #include <Wire.h> #define DEBUG 1 // ================== // SETUP // ================== void setup() { #if defined(DEBUG) Serial.begin(115200); while (!Serial){ } delay(44); #endif Wire.begin(); Wire.setClock(400000); delay(10); uint16_t readData = 0; // read actual address value from the sensor with 0x33 address // should be 0x33 (0xBE33) int result = MLX90640_I2CRead(0x33, 0x240F, 2, &readData); #ifdef DEBUG Serial.print("result: "); Serial.println(result); Serial.println("----"); Serial.print("I2C address BE33: "); Serial.println(readData, HEX); #endif delay(100); // write 0x00 to erase the address register result = MLX90640_I2CWrite(0x33, 0x240F, 0); #ifdef DEBUG Serial.print("result: "); Serial.println(result); Serial.println("----"); #endif delay(100); // read the address regiseter back to see if it was erased // should be 0x00 result = MLX90640_I2CRead(0x33, 0x240F, 2, &readData); #ifdef DEBUG Serial.print("result: "); Serial.println(result); Serial.println("----"); Serial.print("I2C address 0: "); Serial.println(readData, HEX); #endif // write the new address 0x32 (0xBE32) result = MLX90640_I2CWrite(0x33, 0x240F, 0xBE32); #ifdef DEBUG Serial.print("result: "); Serial.println(result); Serial.println("----"); #endif delay(100); // in this place the power cycle is needed to read data from the device with changed I2C address result = MLX90640_I2CRead(0x32, 0x240F, 2, &readData); #ifdef DEBUG Serial.print("result: "); Serial.println(result); Serial.println("----"); Serial.print("I2C address BE32: "); Serial.println(readData, HEX); Serial.println(); Serial.println("---- done ----"); #endif } // ================== // LOOP // ================== void loop() { // nothing here, everything happens in setup() } //Read a number of words from startAddress. Store into Data array. //Returns 0 if successful, -1 if error int MLX90640_I2CRead(uint8_t _deviceAddress, unsigned int startAddress, unsigned int nWordsRead, uint16_t *data) { //Caller passes number of 'unsigned ints to read', increase this to 'bytes to read' uint16_t bytesRemaining = nWordsRead * 2; //It doesn't look like sequential read works. Do we need to re-issue the address command each time? uint16_t dataSpot = 0; //Start at beginning of array //Setup a series of chunked I2C_BUFFER_LENGTH byte reads while (bytesRemaining > 0) { Wire.beginTransmission(_deviceAddress); Wire.write(startAddress >> 8); //MSB Wire.write(startAddress & 0xFF); //LSB if (Wire.endTransmission(false) != 0) //Do not release bus { //Serial.println("No ack read"); return (0); //Sensor did not ACK } uint16_t numberOfBytesToRead = bytesRemaining; if (numberOfBytesToRead > I2C_BUFFER_LENGTH) numberOfBytesToRead = I2C_BUFFER_LENGTH; Wire.requestFrom((uint8_t)_deviceAddress, numberOfBytesToRead); if (Wire.available()) { for (uint16_t x = 0 ; x < numberOfBytesToRead / 2; x++) { //Store data into array data[dataSpot] = Wire.read() << 8; //MSB data[dataSpot] |= Wire.read(); //LSB dataSpot++; } } bytesRemaining -= numberOfBytesToRead; startAddress += numberOfBytesToRead / 2; } return (0); //Success } //Write two bytes to a two byte address int MLX90640_I2CWrite(uint8_t _deviceAddress, unsigned int writeAddress, uint16_t data) { Wire.beginTransmission((uint8_t)_deviceAddress); Wire.write(writeAddress >> 8); //MSB Wire.write(writeAddress & 0xFF); //LSB Wire.write(data >> 8); //MSB Wire.write(data & 0xFF); //LSB if (Wire.endTransmission() != 0) { //Sensor did not ACK //Serial.println("Error: Sensor did not ack"); return (-1); } uint16_t dataCheck; MLX90640_I2CRead(_deviceAddress, writeAddress, 1, &dataCheck); if (dataCheck != data) { //Serial.println("The write request didn't stick"); return -2; } return (0); //Success }
#ifndef LIBSHARED_AND_STATIC_H #define LIBSHARED_AND_STATIC_H #include "libshared_and_static_export.h" namespace libshared_and_static { class Class { public: int method() const; int MYPREFIX_LIBSHARED_AND_STATIC_EXPORT method_exported() const; int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED method_deprecated() const; int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED_EXPORT method_deprecated_exported() const; int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT method_excluded() const; static int const data; static int const MYPREFIX_LIBSHARED_AND_STATIC_EXPORT data_exported; static int const MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT data_excluded; }; class MYPREFIX_LIBSHARED_AND_STATIC_EXPORT ExportedClass { public: int method() const; int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED method_deprecated() const; int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT method_excluded() const; static int const data; static int const MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT data_excluded; }; class MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT ExcludedClass { public: int method() const; int MYPREFIX_LIBSHARED_AND_STATIC_EXPORT method_exported() const; int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED method_deprecated() const; int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED_EXPORT method_deprecated_exported() const; int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT method_excluded() const; static int const data; static int const MYPREFIX_LIBSHARED_AND_STATIC_EXPORT data_exported; static int const MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT data_excluded; }; int function(); int MYPREFIX_LIBSHARED_AND_STATIC_EXPORT function_exported(); int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED function_deprecated(); int MYPREFIX_LIBSHARED_AND_STATIC_DEPRECATED_EXPORT function_deprecated_exported(); int MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT function_excluded(); extern int const data; extern int const MYPREFIX_LIBSHARED_AND_STATIC_EXPORT data_exported; extern int const MYPREFIX_LIBSHARED_AND_STATIC_NO_EXPORT data_excluded; } // namespace libshared_and_static #endif
#pragma once #include "Help.h" #include "Radar.h" #include "View.h" namespace RLGM { struct ConstantBuffer1 //for vertex shader { DirectX::XMMATRIX mViewWorldProjection; }; __declspec(align(16)) struct ConstantBuffer3 //for pixel shader { int radarId; }; __declspec(align(16)) struct ConstantBuffer4 //for pixel shader { int numRadars; //number of radars int unification8bitRule; //unification rule: 0 - max, 1 - linear combination }; class __declspec(dllexport) Interface { public: std::mutex lock; bool m_bExit = false; //exit flag //tails std::thread tailsCalcThread; int tailsCalcPeriod_ms; int thr2bitForTails = 1; std::map<int, RLGM::View> views; std::map<int, RLGM::Radar> radars; //Direct3d related D3D_FEATURE_LEVEL g_featureLevel; ID3D11Device* g_pd3dDevice = nullptr; ID3D11Device1* g_pd3dDevice1 = nullptr; ID3D11DeviceContext* g_pImmediateContext = nullptr; ID3D11DeviceContext1* g_pImmediateContext1 = nullptr; ID3D11InputLayout* g_pVertexLayout = nullptr; ID3D11RasterizerState* g_rasterizerState = nullptr; std::map<std::wstring, ID3D11VertexShader*> vsShaders; std::map<std::wstring, ID3D11PixelShader*> psShaders; ID3D11BlendState* g_pBlendStateBlend = nullptr; ID3D11BlendState* g_pBlendStateNoBlend = nullptr; ID3D11SamplerState* samplerLinear = nullptr; ID3D11SamplerState* samplerPoint = nullptr; ID3D11Buffer* constantBuffer1 = nullptr; ID3D11Buffer* constantBuffer3 = nullptr; ID3D11Buffer* constantBuffer4 = nullptr; ID3D11Buffer* vbQuadScreen = nullptr; //Картинки /*public Hashtable pictures = new Hashtable(); //Спрайт для рисования Картинок public Sprite sprite; //параметры представления public PresentParameters presentationParams = new PresentParameters(); //Таймер для вычисления Хвостов Timer timerTail; //флаг указывающий что идёт вычисление хвостов в данный момент volatile bool calcTailsWorking = false; //объект для синхронизации: вычисление Хвостов object obSyncCalcTails = new object(); //флаг указывающий что хвосты надо вычислять bool calcTailesMode = true; //объект для синхронизации: вычисление Хвостов, очистка Хвостов, отрисовка Окон object obLock = new object(); //подсчёт фреймрэйта int frameNumber; public float frameRate; DateTime frameRateTime;*/ RLGM::ReturnCode CreateDevice(); RLGM::ReturnCode LoadShaders(); HRESULT CompileShaderFromFile(WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut); Interface(); ~Interface(); //стартовая инициализация/деинициализация RLGM::ReturnCode Init(int tails_calc_period_ms); void DeInit(); //создать, удалить Окно RLGM::ReturnCode CreateView(HWND hWnd, int nViewId, double height, double longitude, double latitude); void DeleteView(int nViewId); //создать, удалить Радар (should be >0) RLGM::ReturnCode CreateRadar(int nRadarId, float height, float longitude, float latitude); //nRadarId should be >0 void DeleteRadar(int nRadarId); //добавить ПРЛИ в Радар RLGM::ReturnCode AddPRLI(int nRadarId, RLGM::PRLIType nType, int nPRLISampleCount, int nPRLILineCount); //вычисление Хвостов void CalcTails(int period_ms); //позиционирование окна void SetViewScale(int nViewId, double value); void AddViewScale(int nViewId, double value); void SetAzimuth(int nViewId, double value); void AddAzimuth(int nViewId, double value); void AddViewOffset(int nViewId, int x, int y); //позиционирование радара void SetRadarSampleSize(int nRadarId, double sampleSize); void SetRadarRotation(int nRadarId, double rotInGrad); //позиционирование Радара: центр void SetRadarPos(int nViewId, int nRadarId, int nX, int nY); std::pair<int, int> GetRadarPos(int nViewId, int nRadarId); void AddRadarPos(int nViewId, int nRadarId, int nDX, int nDY); //позиционирование Радара: масштаб void SetDPP(int nViewId, int nRadarId, float dDPP); float GetDPP(int nViewId, int nRadarId); void MultiplyDPP(int nViewId, int nRadarId, float value); void MultiplyDPPCenter(int nViewId, int nRadarId, float value); //позиционирование Радара: поворот void SetRotation(int nViewId, int nRadarId, float dRotInGrad); void AddRotation(int nViewId, int nRadarId, float delta); //отрисовать окно RLGM::ReturnCode DrawView(int nViewId); //настроить Цветокоррекцию void SetPRLIColorCorrection(int nViewId, int nRadarId, RLGM::PRLIType nPRLIType, int nCount, uint32_t* pPalette); //настроить коэф-ты склейки void SetUnificationCoefs(int nRadarId, const std::vector<uint16_t>& values); //настроить отображение ПРЛИ void SetShowPRLI(int nViewId, int nRadarId, RLGM::PRLIType nPRLIType, bool nShow); bool GetShowPRLI(int nViewId, int nRadarId, RLGM::PRLIType nPRLIType); //Передать Линейку 8 и 2 битки //use float version along with R32_FLOAT texture format //void Set8bitData(int nRadarId, int start_line, int stop_line, const std::vector<float> &data, int offset); void Set8bitData(int nRadarId, int start_line, int stop_line, const std::vector<uint8_t> &data, int offset); void Set2bitData(int nRadarId, int start_line, int stop_line, const std::vector<uint8_t> &data, int offset); //возврат Картографического слоя ID3D11Texture2D* GetMapLayer(int nViewId); void ReleaseMapLayer(int nViewId); //настроить режим текстурирования void SetTextureSamplerType(int nViewId, RLGM::TextureSamplerType value); RLGM::TextureSamplerType GetTextureSamplerType(int nViewId); //настроить отображение слоёв void SetShowMap(int nViewId, bool nShow); void SetShow8bit(int nViewId, bool nShow); void SetShow2bit(int nViewId, bool nShow); void SetShowTails(int nViewId, bool nShow); bool GetShowMap(int nViewId); bool GetShow8bit(int nViewId); bool GetShow2bit(int nViewId); bool GetShowTails(int nViewId); //очистить Хвосты void ClearTailes(int nRadarId); //установить правило склейки 8 биток void Set8bitUnificationRule(int nViewId, RLGM::PRLIUnificationRule value); RLGM::PRLIUnificationRule Get8bitUnificationRule(int nViewId); //позиционирование нерадарных слоёв void SetSurfacesShift(int nViewId, int nx, int ny); void AddSurfacesShift(int nViewId, int dx, int dy); void MultiplySurfacesDPP(int nViewId, float value); void MultiplySurfacesDPPCenter(int nViewId, float value); //порог 2битки для вычисления хвоста void SetThr2BitForTails(int value); }; }; //возврат Верхнего слоя 2 //public IntPtr GetTopSurface2(int nViewId); //public void ReleaseTopSurface2(int nViewId) //возврат Верхнего слоя 1 //public IntPtr GetTopSurface1(int nViewId) //public IntPtr GetTopSurface1HDC(int nViewId) //public void ReleaseTopSurface1(int nViewId) //public void ReleaseTopSurface1HDC(int nViewId, IntPtr hDC); //очистить Верхний слой 1 //public void ClearTop1(int nViewId) //очистить Верхний слой 2 //public void ClearTop2(int nViewId) //установить фоновый цвет //public void SetBackColor(int nViewId, int colorARGBA) //настроить отображение верхнего слоя 1 //public void SetShowTop1(int nViewId, int nShow) //public bool GetShowTop1(int nViewId, int nShow) //настроить отображение верхнего слоя 2 //public void SetShowTop2(int nViewId, int nShow) //public bool GetShowTop2(int nViewId, int nShow) //настроить отображение Картинок //public void SetShowPictures(int nViewId, int nShow) //public bool GetShowPictures(int nViewId) //таймаут для очистки ПРЛИ при отсутствии данных //public void SetTimeoutForClearing(int nRadarId, int nMseconds) //установить правило склейки 2 биток //public void Set2bitIntegrationRule(int nViewId, int nRule) //public void Set2bitIntegrationRule(int nViewId, IntegrationRuleType rule) //настроить режим отображения радара //public void SetRadarDrawMode(int nViewId, int nMode) //загрузить Картинку //public void SetPicture(int nPictureId, string bstrFileName, out uint width, out uint height) //позиционирование Картинки: центр //public void SetPicturePos(int nViewId, int nX, int nY, int nPictureId) //удалить Картинку //public void DeletePicture(int nViewId, int nPictureId) //Рисование Значков //if (drawPictures) //{ // owner.sprite.Begin(SpriteFlags.AlphaBlend); // foreach(var item in((Hashtable)(picturesPosition.Clone())).Keys) // owner.sprite.Draw((Texture)owner.pictures[item], new Vector3(((Texture)(owner.pictures[item])).GetLevelDescription(0).Width / 2, ((Texture)(owner.pictures[item])).GetLevelDescription(0).Height / 2, 0), new Vector3(((Point)(picturesPosition[item])).X + picturesPositionOffset.X, ((Point)(picturesPosition[item])).Y + picturesPositionOffset.Y, 0), new Color4(1, 1, 1, 1)); // owner.sprite.End(); //}
/******************************************************************************** ** Form generated from reading UI file 'error.ui' ** ** Created by: Qt User Interface Compiler version 5.9.4 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_ERROR_H #define UI_ERROR_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_error { public: QLabel *label; void setupUi(QWidget *error) { if (error->objectName().isEmpty()) error->setObjectName(QStringLiteral("error")); error->resize(443, 240); label = new QLabel(error); label->setObjectName(QStringLiteral("label")); label->setEnabled(true); label->setGeometry(QRect(70, 60, 291, 101)); retranslateUi(error); QMetaObject::connectSlotsByName(error); } // setupUi void retranslateUi(QWidget *error) { error->setWindowTitle(QApplication::translate("error", "Form", Q_NULLPTR)); label->setText(QApplication::translate("error", "update failed!", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class error: public Ui_error {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_ERROR_H
// // Created by ssi on 23.05.15. // #include "RSS.h" #include "libxml++/libxml++.h" namespace feed { std::vector< Stack< Post > > &RSS::readFeedFiles(const IDB &db, const std::string &path) { time_t lastDate; using namespace boost::filesystem; std::vector< Stack< Post > > *vector = new std::vector< Stack< Post > >; for (recursive_directory_iterator it(__DIR__ + "../../rss-files"), end; it != end; ++it) { try { std::string fullPath = canonical(*it).string(); xmlpp::DomParser parser; parser.parse_file(fullPath); const xmlpp::Node *pNode = parser.get_document()->get_root_node(); xmlpp::Node::NodeList rssChList; if (pNode->get_name() == "rss") { rssChList = pNode->get_children(); pNode = pNode->get_first_child(); } xmlpp::Node::NodeList itemList; for (xmlpp::Node::NodeList::iterator itln = rssChList.begin(); itln != rssChList.end(); ++itln) { if ((*itln)->get_name() == "channel") { pNode = *itln; break; } } itemList = pNode->get_children(); time_t pubDate = 0; std::string category, globalLink; Stack< Post > stack; for (xmlpp::Node::NodeList::iterator item = itemList.begin(); item != itemList.end(); ++item) { if ((*item)->get_name() == "item") { std::string title, preview, body, link = "", media; xmlpp::Node::NodeList itemNodes = (*item)->get_children(); for (xmlpp::Node::NodeList::iterator itemNode = itemNodes.begin(); itemNode != itemNodes.end(); ++itemNode) { if ((*itemNode)->get_name() == "link") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*itemNode)->get_first_child()); if (nodeText) { link = nodeText->get_content(); } else { const xmlpp::ContentNode *nodeContent = dynamic_cast<const xmlpp::ContentNode *>((*itemNode)->get_first_child()); if (nodeContent) link = nodeContent->get_content(); } if (link == "") link = globalLink; } else if ((*itemNode)->get_name() == "enclosure") { const xmlpp::Element *element = dynamic_cast<const xmlpp::Element *>((*itemNode)); if (element) { xmlpp::Attribute *attr = element->get_attribute("url"); media = attr->get_value(); } } else if ((*itemNode)->get_name() == "title") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*itemNode)->get_first_child()); if (nodeText) { title = nodeText->get_content(); } } else if ((*itemNode)->get_name() == "title") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*itemNode)->get_first_child()); if (nodeText) { title = nodeText->get_content(); } } else if ((*itemNode)->get_name() == "subtitle") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*itemNode)->get_first_child()); if (nodeText) { preview = nodeText->get_content(); } else { const xmlpp::ContentNode *nodeContent = dynamic_cast<const xmlpp::ContentNode *>((*itemNode)->get_first_child()); if (nodeContent) preview = nodeContent->get_content(); } } else if ((*itemNode)->get_name() == "description") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*itemNode)->get_first_child()); if (nodeText) { body = nodeText->get_content(); } else { const xmlpp::ContentNode *nodeContent = dynamic_cast<const xmlpp::ContentNode *>((*itemNode)->get_first_child()); if (nodeContent) body = nodeContent->get_content(); } } else if ((*itemNode)->get_name() == "encoded") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*itemNode)->get_first_child()); if (nodeText) { body = nodeText->get_content(); } else { const xmlpp::ContentNode *nodeContent = dynamic_cast<const xmlpp::ContentNode *>((*itemNode)->get_first_child()); if (nodeContent) body = nodeContent->get_content(); } } else if ((*itemNode)->get_name() == "pubDate") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*itemNode)->get_first_child()); if (nodeText) { pubDate = convertDateToTimestamp(nodeText->get_content()); } } } if (pubDate > lastDate) { Post post = Post(title, preview, pubDate, body, category, media, link); stack.push(post); } else break; } else if ((*item)->get_name() == "title") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*item)->get_first_child()); if (nodeText) { category = nodeText->get_content(); } lastDate = db.getLastByDate(category).getTs_PubDate(); } else if ((*item)->get_name() == "link") { const xmlpp::TextNode *nodeText = dynamic_cast<const xmlpp::TextNode *>((*item)->get_first_child()); if (nodeText) { globalLink = nodeText->get_content(); } } else continue; } if (stack.getCount()) vector->push_back(stack); } catch (xmlpp::parse_error &pe) { continue; } } return *vector; } time_t RSS::convertDateToTimestamp(const std::string &pubDate) { std::vector< std::string > words; std::istringstream ist(pubDate); std::string tmp; while (ist >> tmp) words.push_back(tmp); std::map< std::string, boost::date_time::months_of_year > mounthMap = setMonthMap(); unsigned short month = mounthMap[words[2]]; boost::posix_time::time_duration td(boost::posix_time::duration_from_string(words[4])); boost::local_time::time_zone_ptr tz(new boost::local_time::posix_time_zone("GMT")); boost::local_time::local_date_time ld(boost::gregorian::date(atoi(words[3].c_str()), month, atoi(words[1].c_str())), td, tz, boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR); boost::posix_time::time_duration::sec_type diff = (ld.utc_time() - boost::posix_time::from_time_t(0)).total_seconds(); return (time_t) diff; } std::map< std::string, boost::date_time::months_of_year > &RSS::setMonthMap() { std::map< std::string, boost::date_time::months_of_year > *mouthMap = new std::map< std::string, boost::date_time::months_of_year >; mouthMap->insert(std::make_pair("Jan", boost::date_time::Jan)); mouthMap->insert(std::make_pair("Feb", boost::date_time::Feb)); mouthMap->insert(std::make_pair("Mar", boost::date_time::Mar)); mouthMap->insert(std::make_pair("Apr", boost::date_time::Apr)); mouthMap->insert(std::make_pair("May", boost::date_time::May)); mouthMap->insert(std::make_pair("Jun", boost::date_time::Jun)); mouthMap->insert(std::make_pair("Jul", boost::date_time::Jul)); mouthMap->insert(std::make_pair("Aug", boost::date_time::Aug)); mouthMap->insert(std::make_pair("Sep", boost::date_time::Sep)); mouthMap->insert(std::make_pair("Oct", boost::date_time::Oct)); mouthMap->insert(std::make_pair("Nov", boost::date_time::Nov)); mouthMap->insert(std::make_pair("Dec", boost::date_time::Dec)); return *mouthMap; } RSS::RSS(const IDB &db, bool autoInit) { if (autoInit) { listSort(readFeedFiles(db), posts); } } }
#include<bits/stdc++.h> using namespace std; int main() { int n, l, i, j, found; while(cin>>n>>l) { found = 0; while(n--) { cin>>i>>j; if(i==l && j==0) { found++; } } cout<<found<<"\n"; } return 0; }