text
stringlengths
8
6.88M
#pragma once namespace Hourglass { class WaypointGraph { public: struct Edge { unsigned int m_ToVertex; float m_Distance; }; struct WVertex { Vector3 m_Waypoint; std::vector<Edge> m_Edges; explicit WVertex( const Vector3& waypoint ) { m_Waypoint = waypoint; } void AddEdge( const Edge& edge ) { m_Edges.push_back( edge ); } }; WVertex& WaypointGraph::operator[]( unsigned int _index ) { return m_Vertices[_index]; } const WVertex& WaypointGraph::operator[]( unsigned int _index ) const { return m_Vertices[_index]; } unsigned int AddVertex( const Vector3& w ); unsigned int FindNearestVertex( const Vector3 & v ); void Clear(); unsigned int Size() { return unsigned int(m_Vertices.size()); } void DrawDebugEdges(); private: std::vector<WVertex> m_Vertices; }; }
// // Copyright (C) 2001 David Gould // #include "GroundShadowNode.h" #include <maya/MPlug.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MGlobal.h> #include <maya/MFnUnitAttribute.h> #include <maya/MFnGenericAttribute.h> #include <maya/MFnNurbsSurfaceData.h> #include <maya/MFnNurbsSurface.h> #include <maya/MPointArray.h> #include <maya/MAngle.h> #include <maya/MItGeometry.h> #include <maya/MMatrix.h> #include <assert.h> #include <float.h> const MTypeId GroundShadowNode::id(0x00335); MObject GroundShadowNode::lightPosition; MObject GroundShadowNode::castingSurface; MObject GroundShadowNode::shadowSurface; MObject GroundShadowNode::groundHeight; MStatus GroundShadowNode::compute(const MPlug& plug, MDataBlock& data) { MStatus stat; if (plug == shadowSurface) { MDataHandle groundHeightHnd = data.inputValue(groundHeight); MDataHandle lightPositionHnd = data.inputValue(lightPosition); MDataHandle castingSurfaceHnd = data.inputValue(castingSurface); MDataHandle shadowSurfaceHnd = data.outputValue(shadowSurface); shadowSurfaceHnd.copy(castingSurfaceHnd); double gHeight = groundHeightHnd.asDouble(); MVector lightPoint(lightPositionHnd.asDouble3()); MVector planeNormal(0.0, 1.0, 0.0); MVector planePoint(0.0, gHeight, 0.0); double c = planeNormal * planePoint; MPoint surfPoint; double denom, t; MItGeometry iter(shadowSurfaceHnd, false); for (; !iter.isDone(); iter.next()) { surfPoint = iter.position(MSpace::kWorld); denom = planeNormal * (surfPoint - lightPoint); if (denom != 0.0) { t = (c - (planeNormal * lightPoint)) / denom; surfPoint = lightPoint + t * (surfPoint - lightPoint); } iter.setPosition(surfPoint, MSpace::kWorld); } data.setClean(plug); } else stat = MS::kUnknownParameter; return stat; } void *GroundShadowNode::creator() { return new GroundShadowNode(); } MStatus GroundShadowNode::initialize() { MFnNumericAttribute nAttr; lightPosition = nAttr.create("lightPosition", "lpos", MFnNumericData::k3Double, 0.0); nAttr.setKeyable(true); MFnUnitAttribute uAttr; groundHeight = uAttr.create("groundHeight", "grnd", MFnUnitAttribute::kDistance, 0.0); uAttr.setKeyable(true); MFnGenericAttribute gAttr; castingSurface = gAttr.create("castingSurface", "csrf"); gAttr.addAccept(MFnData::kMesh); gAttr.addAccept(MFnData::kNurbsSurface); gAttr.setHidden(true); shadowSurface = gAttr.create("shadowSurface", "ssrf"); gAttr.addAccept(MFnData::kMesh); gAttr.addAccept(MFnData::kNurbsSurface); gAttr.setHidden(true); gAttr.setStorable(false); addAttribute(groundHeight); addAttribute(lightPosition); addAttribute(castingSurface); addAttribute(shadowSurface); attributeAffects(groundHeight, shadowSurface); attributeAffects(lightPosition, shadowSurface); attributeAffects(castingSurface, shadowSurface); return MS::kSuccess; }
#include <pthread.h> #include <stdio.h> /* compile with g++ main.cpp -lpthread -o example.out */ void* do_work(void* arg) { printf("abc\n"); pthread_exit((void*) 0); } int main() { pthread_t thread; pthread_attr_t attr; int rc; void* status; /* Create Thread attribute object */ rc = pthread_attr_init(&attr); if(rc) { fprintf(stderr, "ERROR: while creating thread attribute object"); return 1; } /* Create a new POSIX Thread */ rc = pthread_create(&thread, &attr, do_work, (void*) NULL); /* Cleanup pthread_attr_t object, we don't need it anymore */ pthread_attr_destroy(&attr); if(rc) { fprintf(stderr, "ERROR: while creating thread"); return 2; } /* Wait for thread to finish work */ rc = pthread_join(thread, &status); if(rc) { fprintf(stderr, "ERROR: while waiting for thread to join"); return 3; } return 0; }
#include<bits/stdc++.h> using namespace std; int random_number() { return rand()%100+1; } void computer_guess(int& lower_limit,int& upper_limit,char& c) { cout<<"My guess is number: "<<(lower_limit+upper_limit)/2<<endl<<"Please enter: "; cin>>c; if(c=='<') { lower_limit=(lower_limit+upper_limit)/2+1; } else if(c=='>') { upper_limit=(lower_limit+upper_limit)/2-1; } else cout<<"Computer win"<<endl; } void play_GuessIt() { char t; do { int times=0,point=10000,number=100; int x,a,lower_limit=1,upper_limit=100; char c; cout<<"Enter your number: "; cin>>x; do { computer_guess(lower_limit,upper_limit,c); times++; } while(c!='='); for(int i=0; i<times-1; i++) { point-=2*number; number--; } cout<<"Number of guesses is: "<<times<<endl; cout<<"The point is: "<<100-times+1<<"/100 and "<<point<<"/10000"<<endl; cout<<"Enter "<<'"'<<"y"<<'"'<<" to continue, enter a character that does not match "<<'"'<<"y"<<'"'<<" to stop: "; cin>>t; } while(t=='y'); } int main() { play_GuessIt(); }
#ifndef REACTOR_NET_HTTP_CONTEXT_H #define REACTOR_NET_HTTP_CONTEXT_H #include "../TcpConnection.h" #include "HttpRequest.h" #include "HttpResponse.h" namespace reactor { namespace net { namespace http { class HttpRequest; class HttpResponse; class HttpContext { public: enum State { kRequestLine = 0, kHeader, kBody, kFinish, kError, }; HttpContext(): state_(kRequestLine), error_code_(200), error_msg_("OK"), close_connection_(true) { } ~HttpContext() = default; HttpContext(const HttpContext &) = default; HttpContext &operator=(const HttpContext &) = default; void reset() { request_ = HttpRequest(); response_ = HttpResponse(); state_ = kRequestLine; error_code_ = 200; error_msg_ = "OK"; close_connection_ = true; } void parse(const TcpConnectionPtr &conn); bool close_connection() const { return close_connection_; } bool finished() const { return state_ == kFinish; } bool error() const { return error_code_ != 200; } int error_code() const { return error_code_; } const std::string &error_message() const { return error_msg_; } HttpRequest &request() { return request_; } const HttpRequest &request() const { return request_; } HttpResponse &response() { return response_; } const HttpResponse &response() const { return response_; } private: void parse_request_line(const std::string &line); void parse_header(const std::string &line); void set_error(int err, const std::string &msg); State state_; int error_code_; std::string error_msg_; bool close_connection_; HttpRequest request_; HttpResponse response_; }; } // namespace http } // namespace net } // namespace reactor #endif
// // SerialPort.hpp // DrumConsole // // Created by Paolo Simonazzi on 21/04/2016. // // #ifndef SerialPort_hpp #define SerialPort_hpp #include <stdio.h> class SerialPort : public Thread { public: SerialPort(); void run() override; private: }; #endif /* SerialPort_hpp */
// // // // // // // // // // // // // // // // // // vCenterViewer // // VisionStudio // // // // // // // // // // // // // // // // // // // QT #include <QApplication> #include <QMutex> #include <QNetworkInterface> // GENERAL #include <vector> #include <iostream> #include <fstream> #include <queue> #include <random> // OPENCV #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/video/video.hpp> // VCENTER #include "mainwindow.h" #include "startwindow.h" #include "independentview.h" #include "./onfivc/devicesearcher.h" #include "analyzer.h" // NAMESPACES using namespace std; using namespace std::chrono; // directorio base donde estan los sources y el ejecutable del programa #ifdef linux string BASE_DIR = "/opt/vCenterViewer/"; #elif _WIN32 || WIN32 || WIN64 string BASE_DIR = "C:/vCenterViewer/"; #endif // TODO /* TELEGRAM - cuando no este mas el vkey, cerrar el py_telegram. MONGO !! no se guardan las imagenes de los emap en mongo !! A veces se cargan mal la velocidad y timeout del ptz !! testear desconexion con mongo !! cargar las alertas y los productos de la base de datos en lugar de preguntarle al vkey DOCUMENTACION ! consejos para operar con una maquina de bajos recursos !! manual y errores comunes NVR !!! No cargan los canales del dvr !!! Agregar las funcionalidades de scheduler/movimiento/stop/play CONFIG CAMARA !! configurar subcamaras: cargar y guardar el recorte !! no se previsualizan las camaras en la ventana de configurar camara, cuando no hay un widget viendola ya !! cuando configuro una camara, tambien enviar el mensaje de los receivers de las alertas EXTRA - recuperar camaras con estado 0 en la base de datos - por que a veces tarda mucho en abrir la ventana de configuracion? PLAYBACK !!! no anda hacer playback de un substream !! no permitir hacer playback cuando este el modo grabacion MODO GRABACION ! botones de manejo de videos: < || > >> ! opcion "ir a" de las tablas de grabaciones de las camaras PTZ - cuando elimino una camara que tiene activado el ptz, eliminar el proceso correspondiente MAS ADELANTE - Permitir cambiar el color del nombre de las camaras en las grillas y en los emaps - permitir independizar y reincorporar emaps - Boton de agregar camara en la ventana de buscar dispositivos - Mostrar el REC: recibir que camaras estan grabandose del vcentermaager */ int vcenterviewer_index = 2; // numero de producto del vCenterViewer string exec_id; // id de ejecucion // ESTILO QString dark_style = "background-color: rgb(50, 50, 50);color: rgb(255, 255, 255);selection-background-color: rgb(48, 138, 255);"; QString white_style = "background-color: rgb(235, 235, 235);color: rgb(45, 45, 45);selection-background-color: rgb(48, 138, 255);"; QString curr_style = dark_style; // estilo de alertas int alert_items_max_font = 15; int alert_items_min_font = 8; int alerts_items_max_count = 50; QString alerts_items_color = "Rojo"; // ICONOS QString icons_folder; vector<QIcon> black_icons; vector<QIcon> blue_icons; Camera* selected_camera = NULL; cv::Mat nosignal_img; vector<Manufacturer> manufacturers; // lista de marcas de camaras para el buscador por IP vector<QString> device_search_ips; QMutex device_search_ips_mutex; // MONGO string mongo_addr = "192.168.0.115:27017"; bool mongo_disconnected = false; //keymanager string key_addr = "localhost:1883"; bool key_connected = true; QMutex update_mutex; //usuario UserInfo userinfo; bool userlogedin = false; // CONFIGURACIONES GLOBALES // general QString language = "English"; QString screenshots_folder = "./"; QString logs_folder = "."; queue<string> log_messages; string last_log = ""; bool startwindowclosed = false; QString broker_ip = "localhost"; cv::Mat ptz_img; cv::Size ptz_size = cv::Size(201, 150); // global configs int video_block_minutes = 10; bool write_timestamp = true; QString timestamp_color = "Red"; QString timestamp_size = "Medium"; QString save_folder = "./"; // control de guardia bool control_on = false; int control_from = 5; int control_to = 25; int control_tolerance = 5; bool control_window_open = false; int time_to_next_control = -1; // informacion global vector<Group*> groups; vector<Camera*> cameras; vector<DhDevice*> dhdevices; vector<CVImageWidget*> cvwidgets; vector<MaskLabel*> prevs; //alertas vector<QString> pendAlerts; QMutex pendAlertsMutex; //licencias bool licences_read = false; vector<Licence> licences_; bool cameras_loaded = false; bool cerrar = false; //telegram bool sigintGot = false; bool stop_tg = false; //record mode bool record_mode_on = false; QString IP; LoadWindow* loadwindow; // ventana de carga // INSTANCIAS VCPtz* ptz; // ptz MqttMessenger* ms; // mqtt VSMongo* vsmongo; // mongo LogManager* log_manager; // logs // analyzer #ifdef __unix__ Analyzer* analyzer; // analyzer: guarda el historial de recursos de la cpu #endif std::string VERSION = "3.0.0"; bool NO_LOGIN = false; // FUNCIONES GLOBALES AUXILIARES bool watching(Camera* camera); void obtenerIP(); void loadManufacturers(); void log(string log_msg); void generateExecID(); void loadStyle(); void loadAlertsStyle(); // funciones de test void testIntervalBinarySearch(); // FUNCION PRINCIPAL int main(int argc, char *argv[]){ mongocxx::instance mongo_inst; QApplication a(argc, argv); srand(48); //semilla loadStyle(); loadAlertsStyle(); loadManufacturers(); removeAllPlaybacks(); generateExecID(); obtenerIP(); cout << "vCenterViewer version " << VERSION << endl; // comenzar analisis de uso de CPU y memoria #ifdef __unix__ analyzer = new Analyzer(BASE_DIR+"analyzer/",2000,false); #endif // configuraciones locales StartWindow* sw = new StartWindow(); sw->show(); if(NO_LOGIN) sw->saveAndClose(); while(!startwindowclosed){ if (cerrar) return 0; QCoreApplication::processEvents(); this_thread::sleep_for(milliseconds(10)); } // iniciar mongo vsmongo = new VSMongo("mongodb://"+mongo_addr,"vCenterWeb"); // ventana de login userinfo.login = false; LoginDialog login; login.show(); // saltarse el login? if(NO_LOGIN) login.autoLogin(); while (!login.login_clicked_) { if (cerrar) return 0; QCoreApplication::processEvents(); this_thread::sleep_for(milliseconds(10)); } // iniciar log manager log_manager = new LogManager(logs_folder.toStdString()); log("Inició sesión el usuario: "+ userinfo.username + "("+userinfo.rol+")"); log("Inició vCenterViewer"); // load window loadwindow = new LoadWindow(); loadwindow->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint); loadwindow->show(); // iniciar ventana principal MainWindow w; w.show(); return a.exec(); } // la camara es visible en alguna ventana? bool watching(Camera* camera){ for(uint i=0;i<cvwidgets.size();i++){ if(cvwidgets[i]->visible_) if( cvwidgets[i]->camera_ == camera || (cvwidgets[i]->camera_->substream_config_.is_substream && cvwidgets[i]->camera_->substream_config_.father_camera == camera)) return true; } return false; } // obtener la ip local void obtenerIP(){ vector<QString> all_addrs; foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) all_addrs.push_back(address.toString()); } IP = all_addrs[0]; } // leer el archivo sources.txt: cargar fabricantes de camaras y sus urls void loadManufacturers(){ std::ifstream urls_file(BASE_DIR+"vCenterViewer/sources.txt"); string s; string manufacturer; while(urls_file >> s){ if(s == "Manufacturer"){ manufacturer = ""; if(urls_file >> s) manufacturer = s; while(urls_file >> s && s.substr(0,7) != "http://" && s.substr(0,7) != "rtsp://") manufacturer += " "+s; manufacturers.push_back(Manufacturer(manufacturer)); }else{ manufacturers[manufacturers.size()-1].addUrl(s); } } } // guardar y mostrar un mensaje de log void log(string log_msg){ log_messages.push(log_msg); } // generar una id de ejecucion, para distinguir esta instancia de otras void generateExecID(){ QDate qd = QDate::currentDate(); QTime qt = QTime::currentTime(); string year = QString::number(qd.year()).toStdString(); string month = QString::number(qd.month()).toStdString(); if(month.size()==1) month = "0"+month; string day = QString::number(qd.day()).toStdString(); if(day.size()==1) day = "0"+day; string hour = QString::number(qt.hour()).toStdString(); if(hour.size()==1) hour = "0"+hour; string min = QString::number(qt.minute()).toStdString(); if(min.size()==1) min="0"+min; string sec = QString::number(qt.second()).toStdString(); if(sec.size()==1) sec = "0"+sec; string msec = QString::number(qt.msec()).toStdString(); exec_id = year+month+day+hour+min+sec+msec; } // leer archivo de configuracion de estilo void loadStyle(){ std::ifstream file(BASE_DIR+"config/style.config"); bool open = file.is_open(); if(open){ string line; getline(file,line); if(line == "black"){ //icons_folder = QString::fromStdString(BASE_DIR)+"images/icon/nobackground/"; icons_folder = QString::fromStdString(BASE_DIR)+"images/icon/black/"; curr_style = dark_style; } if(line == "white"){ curr_style = white_style; icons_folder = QString::fromStdString(BASE_DIR)+"images/icon/white/"; } } } // cargar configuraciones de estilo de alertas void loadAlertsStyle(){ std::ifstream file(BASE_DIR+"config/astyle.config"); bool open = file.is_open(); if(open){ string line; getline(file,line); QStringList alerts_config = QString::fromStdString(line).split("$$"); if(alerts_config.size()>3){ alerts_items_max_count = alerts_config[0].toInt(); alert_items_min_font = alerts_config[1].toInt(); alert_items_max_font = alerts_config[2].toInt(); alerts_items_color = alerts_config[3]; } } } // la palabra empieza con un digito? bool startsWithDigit(QString qs){ if(qs.size()>0){ QChar qc = qs[0]; if( qc == '0' || qc == '1' || qc == '2' || qc == '3' || qc == '4' || qc == '5' || qc == '6' || qc == '7' || qc == '8' || qc == '9' ) return true; } return false; } // chequear que sea un nombre valido y no repetido entre grupos,grillas,emaps,camaras,dispositivos dahua etc bool validName(QString name){ if(startsWithDigit(name)) // empieza con digito? return false; if(name == ("")) // es vacio? return false; for(uint i=0;i<userinfo.grids.size();i++) // es una grilla? if(userinfo.grids[i]->name == name.toStdString()) return false; for(uint i=0;i<userinfo.emaps.size();i++) // es un emap? if(userinfo.emaps[i]->name == name.toStdString()) return false; for(uint i=0;i<groups.size();i++) // es un grupo? if(groups[i]->name_ == name) return false; for(uint i=0;i<cameras.size();i++) // es una camara? if(cameras[i]->name_ == name) return false; for(uint i=0;i<dhdevices.size();i++) // es un dvr/nvr ? if(dhdevices[i]->name_ == name.toStdString()) return false; if(name.contains(" ") || name.contains(';')) // contiene un caracter invalido? return false; if(name == "Grupos" || // es una palabra reservada? name == "Grillas" || name == "Emaps" || name == "Inicio" ) return false; if(name.contains("NuevoGrupo") || // contiene una palabra reservada? name.contains("NuevoEmap") || name.contains("NuevaGrilla") ) return false; if(name.size()>20) // es larga? return false; return true; } void testIntervalBinarySearch(){ vector<pair<int,int> > pairs = {{20,40},{50,100},{120,130},{200,400},{402,405},{1000,1010}}; vector<int> vals = {5,30,41,60,110,125,170,280,401,403,700,1005,2000}; vector<RecordVideo> intervals; for(int i=0;i<pairs.size();i++){ RecordVideo rv; rv.init_time = pairs[i].first; rv.end_time = pairs[i].second; intervals.push_back(rv); } for(int i=0;i<vals.size();i++){ BSearchResult res = intervalBinarySearch(vals[i],intervals,0,intervals.size()-1); if(res.found) std::cout << vals[i] << ": true ("<< intervals[res.index].init_time << "," << intervals[res.index].end_time <<")"<< std::endl; else std::cout << vals[i] << ": false ("<< res.empty_interval_init << "," << res.empty_interval_end <<")"<< std::endl; } }
// energy.cpp #include <memory> #include <vector> #include "BlobCrystallinOligomer/energy.h" namespace energy { using ifile::InputEnergyFile; using monomer::particleArrayT; using potential::ZeroPotential; using potential::HardSpherePotential; using potential::SquareWellPotential; using potential::HarmonicWellPotential; using potential::AngularHarmonicWellPotential; using potential::ShiftedLJPotential; using potential::PatchyPotential; using potential::OrientedPatchyPotential; using potential::DoubleOrientedPatchyPotential; using shared_types::inf; using shared_types::InputError; using shared_types::vecT; using std::cout; Energy::Energy(Config& conf, InputParams& params): m_config {conf}, m_max_cutoff {params.m_max_cutoff} { InputEnergyFile energy_file {params.m_energy_filename}; vector<PotentialData> potentials {energy_file.get_potentials()}; vector<InteractionData> same_conformers_interactions { energy_file.get_same_conformers_interactions()}; vector<InteractionData> different_conformers_interactions { energy_file.get_different_conformers_interactions()}; create_potentials(potentials, same_conformers_interactions, different_conformers_interactions); eneT total_ene {calc_total_energy()}; if (total_ene == inf or total_ene != total_ene) { cout << "Bad starting configuration\n"; throw InputError {}; } } eneT Energy::calc_total_energy() { monomerArrayT monomers {m_config.get_monomers()}; eneT total_ene {0}; for (size_t i {0}; i != monomers.size() - 1; i++) { Monomer& monomer1 {monomers[i].get()}; for (size_t j {i + 1}; j != monomers.size(); j++) { Monomer& monomer2 {monomers[j].get()}; total_ene += calc_monomer_pair_energy(monomer1, CoorSet::current, monomer2, CoorSet::current); } } return total_ene; } eneT Energy::calc_monomer_pair_energy(Monomer& monomer1, CoorSet coorset1, Monomer& monomer2, CoorSet coorset2) { eneT pair_ene {0}; particleArrayT particles1 {monomer1.get_particles()}; particleArrayT particles2 {monomer2.get_particles()}; for (Particle& p1: particles1) { for (Particle& p2: particles2) { eneT part_ene {calc_particle_pair_energy(p1, monomer1.get_conformer(coorset1), coorset1, p2, monomer2.get_conformer(coorset2), coorset2)}; if (part_ene == inf) { return inf; } pair_ene += part_ene; } } return pair_ene; } bool Energy::monomers_interacting(Monomer& monomer1, CoorSet coorset1, Monomer& monomer2, CoorSet coorset2) { bool m_interacting {false}; if (not monomers_in_range(monomer1, coorset1, monomer2, coorset2)) { return m_interacting; } particleArrayT particles1 {monomer1.get_particles()}; particleArrayT particles2 {monomer2.get_particles()}; for (Particle& p1: particles1) { for (Particle& p2: particles2) { bool p_interacting {particles_interacting(p1, monomer1.get_conformer(coorset1), coorset1, p2, monomer2.get_conformer(coorset2), coorset2)}; if (p_interacting) { m_interacting = true; return m_interacting; } } } return m_interacting; } bool Energy::monomers_in_range(Monomer& monomer1, CoorSet coorset1, Monomer& monomer2, CoorSet coorset2) { bool in_range {false}; distT monomer1_r {monomer1.get_radius()}; distT monomer2_r {monomer2.get_radius()}; distT max_interaction_d {monomer1_r + monomer2_r + m_max_cutoff}; distT d {m_config.calc_dist(monomer1, coorset1, monomer2, coorset2)}; if (d <= max_interaction_d) { in_range = true; } return in_range; } monomerArrayT Energy::get_interacting_monomers(Monomer& monomer1, CoorSet coorset1) { monomerArrayT monomers {m_config.get_monomers()}; monomerArrayT interacting_monomers {}; CoorSet coorset2 {CoorSet::current}; for (size_t i {0}; i != monomers.size(); i++) { Monomer& monomer2 {monomers[i].get()}; if (monomer1.get_index() == monomer2.get_index()) { continue; } if (monomers_interacting(monomer1, coorset1, monomer2, coorset2)) { interacting_monomers.push_back(monomer2); } } return interacting_monomers; } eneT Energy::calc_monomer_diff(Monomer& mono1) { monomerArrayT monos {m_config.get_monomers()}; eneT de {0}; for (size_t i {0}; i != monos.size(); i++) { Monomer& mono2 {monos[i].get()}; if (mono1.get_index() == mono2.get_index()) { continue; } eneT ene1 {calc_monomer_pair_energy(mono1, CoorSet::current, mono2, CoorSet::current)}; eneT ene2 {calc_monomer_pair_energy(mono1, CoorSet::trial, mono2, CoorSet::current)}; de += ene2 - ene1; } return de; } bool Energy::particles_interacting(Particle& particle1, int conformer1, CoorSet coorset1, Particle& particle2, int conformer2, CoorSet coorset2) { distT dist {m_config.calc_dist(particle1, coorset1, particle2, coorset2)}; pair<int, int> key {particle1.get_type(), particle2.get_type()}; PairPotential* pot; if (conformer1 == conformer2) { pot = &(m_same_pair_to_pot.at(key).get()); } else { pot = &(m_different_pair_to_pot.at(key).get()); } bool interacting {pot->particles_interacting(dist)}; return interacting; } eneT Energy::calc_particle_pair_energy(Particle& particle1, int conformer1, CoorSet coorset1, Particle& particle2, int conformer2, CoorSet coorset2) { vecT diff {m_config.calc_interparticle_vector(particle2, coorset2, particle1, coorset1)}; distT dist {diff.norm()}; auto p1_ore {particle1.get_ore(coorset1)}; auto p2_ore {particle2.get_ore(coorset2)}; pair<int, int> key {particle1.get_type(), particle2.get_type()}; PairPotential* pot; if (conformer1 == conformer2) { pot = &(m_same_pair_to_pot.at(key).get()); } else { pot = &(m_different_pair_to_pot.at(key).get()); } eneT ene {pot->calc_energy(dist, diff, p1_ore, p2_ore)}; return ene; } void Energy::create_potentials(vector<PotentialData> potentials, vector<InteractionData> same_conformers_interactions, vector<InteractionData> different_conformers_interactions) { for (auto p_data: potentials) { PairPotential* pot; if (p_data.form == "Zero") { pot = new ZeroPotential {}; } if (p_data.form == "HardSphere") { pot = new HardSpherePotential {p_data.sigh}; } if (p_data.form == "SquareWell") { pot = new SquareWellPotential {p_data.eps, p_data.rcut}; } if (p_data.form == "HarmonicWell") { pot = new HarmonicWellPotential {p_data.eps, p_data.rcut}; } if (p_data.form == "AngularHarmonicWell") { pot = new AngularHarmonicWellPotential {p_data.eps, p_data.rcut, p_data.siga1}; } else if (p_data.form == "ShiftedLJ") { pot = new ShiftedLJPotential {p_data.eps, p_data.sigl, p_data.rcut}; } else if (p_data.form == "Patchy") { pot = new PatchyPotential {p_data.eps, p_data.sigl, p_data.rcut, p_data.siga1, p_data.siga2}; } else if (p_data.form == "OrientedPatchy") { pot = new OrientedPatchyPotential {p_data.eps, p_data.sigl, p_data.rcut, p_data.siga1, p_data.siga2, p_data.sigt}; } else if (p_data.form == "DoubleOrientedPatchy") { pot = new DoubleOrientedPatchyPotential {p_data.eps, p_data.sigl, p_data.rcut, p_data.siga1, p_data.siga2, p_data.sigt}; } m_potentials.emplace_back(pot); } for (auto i_data: same_conformers_interactions) { for (auto p_pair: i_data.particle_pairs) { PairPotential& pot {*m_potentials[i_data.potential_index]}; m_same_pair_to_pot.emplace(p_pair, pot); pair<int, int> reversed_p_pair {p_pair.second, p_pair.first}; m_same_pair_to_pot.emplace(reversed_p_pair, pot); } } for (auto i_data: different_conformers_interactions) { for (auto p_pair: i_data.particle_pairs) { PairPotential& pot {*m_potentials[i_data.potential_index]}; m_different_pair_to_pot.emplace(p_pair, pot); pair<int, int> reversed_p_pair {p_pair.second, p_pair.first}; m_different_pair_to_pot.emplace(reversed_p_pair, pot); } } } }
class Solution { public: // vector<int> getIntialColoring(vector<vector<int>>& graph) { // int n = graph.length() // vector<int> coloring(n); // for(int i=0; i<n; i++) { // coloring[i] = 0; // } // } int oppositeColor(int Prevnode, vector<int> coloring) { return coloring[Prevnode] == 1 ? 2 : 1; } bool isBipartite(vector<vector<int>>& graph) { int n = graph.size(); vector<int> coloring(n); queue<int> q; unordered_set<int> seen; /* Graph may not be connected, we will start a BFS from each vertex, but once a vertex is visited it can't be processed again so this still stays to O(|V|+|E|) */ for(int i=0; i<n; i++) { if(seen.find(i) == seen.end()) { int start = i; // 1 => Black && 2 ==> white; coloring[start] = 1; q.push(start); seen.insert(start); while(!q.empty()) { int node = q.front(); q.pop(); for(auto x: graph[node]) { if(coloring[x] == 0) { coloring[x] = oppositeColor(node, coloring); } else if(coloring[x] == coloring[node]) return false; if(seen.find(x) == seen.end()) { q.push(x); seen.insert(x); } } } } } return true; } };
#pragma once #include "Polygon3D.h" #include "Vertex.h" #include "Matrix.h" #include <vector> #include <algorithm> #include "DirectionalLight.h" #include "AmbientLight.h" #include "PointLight.h" #include "Light.h" class Model { public: Model(); ~Model(); // Acessors const std::vector<Polygon3D>& GetPolyons(); const std::vector<Vertex>& GetVerticies(); const std::vector<Vertex>& GetTransformedVerticies(); size_t GetPolygonCount() const; size_t GetVertexCount() const; void AddVertex(float, float, float); void AddPolygon(int, int, int); void ApplyTransformToLocalVerticies(const Matrix&); void ApplyTransformToTransformedVerticies(const Matrix&); // Iterates through all the verticies, calling their void DehomogeniseVerticies(); // Calculates whether the polygon should be renedered and sets _markedForCulling accordingly void CalculateBackfaces(Vertex); // Sorts the polygons in relation to distance from the camera void Sort(); // Calculates Directional Lighting for each point void CalculateLightingDirectional(std::vector<DirectionalLight>); // Calculates Ambient Lighting void CalculateLightingAmbient(AmbientLight); // Calculates Point Lighting void CalculateLightingPoint(std::vector<PointLight>); // Calculates normal vectors of verticies void CalculateVertexNormals(); // Calculates the directional lighting for each vertex void CalculateLightingDirectionalVertex(std::vector<DirectionalLight>); // Calculates the ambient lighting for each vertex void CalculateLightingAmbientVertex(AmbientLight); // Calculates the point lighting for each vertex void CalculateLightingPointVertex(std::vector<PointLight>); private: int Clamp(float); // Reflection Coefficients float _kdRed { 1.0f }; float _kdGreen { 0.2f }; float _kdBlue { 0.2f }; std::vector<Polygon3D> _polygons; std::vector<Vertex> _verticies; std::vector<Vertex> _transformedVerticies; };
// 问题的描述:链表分化 // 给定一个单链表以及一个阈值,对小于阈值的结点放到左边,等于阈值的结点放到中间,大于阈值的结点放到右边 // 保证两种结点内部的位置关系不变 // 分成三个小链表,再组合成一个链表 // 测试用例有4组: // 1、空链表 threshold = 2 // 输入:NULL 2 // 输出:NULL // 2、非空链表 threshold = 3 // 输入:{1,4,2,5} 3 // 输出:1,2,4,5 // 3、非空链表 threshold = 8 // 输入:{1,4,2,5} 8 // 输出:1,4,2,5 // 4、非空链表 threshold = 0 // 输入:{1,4,2,5} 0 // 输出:1,4,2,5 #include <iostream> #include <vector> using namespace std; // 链表结点的定义 struct ListNode { int val; struct ListNode *next; ListNode(int x) :val(x), next(nullptr) {} }; // 创建一个链表 ListNode* CreateList(vector<int> &nums) { if (nums.empty()) return nullptr; ListNode *head = new ListNode(nums[0]); ListNode *temp_node = head, *new_node = nullptr; for (int i = 1; i < nums.size(); ++i) { new_node = new ListNode(nums[i]); temp_node->next = new_node; temp_node = new_node; } return head; } // 回收链表的内存 void FreeList(ListNode *head) { if (head == nullptr) return; ListNode *free_node = nullptr; while (head != nullptr) { free_node = head; head = head->next; delete free_node; } } // 链表的分化 ListNode* DivideList(ListNode *head, int threshold) { if (head == nullptr || head->next == nullptr) return head; ListNode *small_head = new ListNode(0), *small_tail = small_head; ListNode *medium_head = new ListNode(0), *medium_tail = medium_head; ListNode *big_head = new ListNode(0), *big_tail = big_head; // 分成三个小链表 while (head != nullptr) { if (head->val < threshold) { small_tail->next = head; small_tail = head; } else if (head->val == threshold) { medium_tail->next = head; medium_tail = head; } else { big_tail->next = head; big_tail = head; } head = head->next; } // 组合起来 if (medium_head != medium_tail) { small_tail->next = medium_head->next; medium_tail->next = big_head->next; } else { small_tail->next = big_head->next; } big_tail->next = nullptr; head = small_head->next; // 释放掉辅助结点 delete small_head; delete medium_head; delete big_head; return head; } int main() { // 空链表 //vector<int> nums; // 非空链表 vector<int> nums = { 1,4,2,5 }; int threshold = 3; ListNode *root = CreateList(nums); ListNode *head = DivideList(root, threshold); // 遍历链表,输出元素值 ListNode *node = head; while (node != nullptr) { cout << node->val << "\t"; node = node->next; } cout << endl; FreeList(head); system("pause"); return 0; }
// // Model.cpp // cg-projects // // Created by HUJI Computer Graphics course staff, 2013. // #include "ShaderIO.h" #include "Model.h" #include <GL/glew.h> #ifdef __APPLE__ #include <OpenGL/OpenGL.h> #else #include <GL/gl.h> #endif #include <stdlib.h> #include <glm/gtc/type_ptr.hpp> #include "glm/gtc/matrix_transform.hpp" #define SHADERS_DIR "shaders/" Model::Model(float w, float h) : _vao(0), _vbo(0), _vaoCircle(0), _vboCircle(0), _width(w), _height(h), _glPolygonMode(GL_FILL), _viewMode(PERSPECTIVE), _normalMode(NORMAL_FACE), _shadingMode(SHADING_PHONG), _numCircleVertices(50), _specExp(200) { for (int i=0; i < 3; i++) { _mouseFlags[i] = false; } } Model::~Model() { if (_vao != 0) glDeleteVertexArrays(1, &_vao); if (_vbo != 0) glDeleteBuffers(1, &_vbo); if (_vaoCircle != 0) glDeleteVertexArrays(1, &_vaoCircle); if (_vboCircle != 0) glDeleteBuffers(1, &_vboCircle); if (_ebo != 0) glDeleteBuffers(1, &_ebo); } void Model::genModelVerticesFaces() { std::vector<glm::vec4> vertices(_mesh.n_faces() * 3 * 2); _mesh.request_face_normals(); _mesh.request_vertex_normals(); _mesh.update_normals(); size_t i = 0; for (MyMesh::FaceIter h_it=_mesh.faces_begin(); h_it!=_mesh.faces_end(); ++h_it) { // circulate around the current face for (MyMesh::FaceVertexIter fv_it = _mesh.fv_iter(h_it); fv_it; ++fv_it) { MyMesh::Point p = _mesh.point(fv_it.handle()); glm::vec4 position((p[0] - _center[0]) / _maxV, (p[1] - _center[1]) / _maxV, (p[2] - _center[2]) / _maxV, 1.0f); vertices[i++] = position; MyMesh::Normal n = _mesh.normal(h_it); glm::vec4 normal(n[0], n[1], n[2], 0.0); vertices[i++] = normal; } } _mesh.release_face_normals(); _mesh.release_vertex_normals(); i = 0; { // normalize points to arcBall radius float upperRightOffset = glm::length(glm::vec3(CIRCLE_RADIUS - _upperRight[0], CIRCLE_RADIUS - _upperRight[1], CIRCLE_RADIUS - _upperRight[2])); float lowerLeftOffset = glm::length(glm::vec3(CIRCLE_RADIUS + _lowerLeft[0], CIRCLE_RADIUS + _lowerLeft[1], CIRCLE_RADIUS + _lowerLeft[2])); float arcballNormalizeOffset = std::max(upperRightOffset, lowerLeftOffset); for (size_t i = 0; i < vertices.size(); i++) { if(i % 2 == 0) { //do this only for vertices, not normals vertices[i] *= (1 + arcballNormalizeOffset); vertices[i][3] = 1.0; } } } glGenVertexArrays(1, &_vaoFace); glBindVertexArray(_vaoFace); // Create and bind the object's vertex buffer: glGenBuffers(1, &_vboFace); glBindBuffer(GL_ARRAY_BUFFER, _vboFace); // Create and load vertex data into a Vertex Buffer Object: glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * vertices.size(), &(vertices[0]), GL_STATIC_DRAW); setShadingMode(Model::SHADING_PHONG); glBindVertexArray(0); } void Model::genModelVertices() { std::vector<glm::vec4> vertices(_mesh.n_vertices() * 2); _mesh.request_face_normals(); _mesh.request_vertex_normals(); _mesh.update_normals(); size_t i = 0; MyMesh::Point p; for (MyMesh::VertexIter vertexIter = _mesh.vertices_begin(); vertexIter != _mesh.vertices_end(); ++vertexIter) { p = _mesh.point(vertexIter.handle()); glm::vec4 position((p[0] - _center[0]) / _maxV, (p[1] - _center[1]) / _maxV, (p[2] - _center[2]) / _maxV, 1.0f); vertices[i++] = position; MyMesh::Normal n = _mesh.normal(vertexIter); glm::vec4 normal(n[0], n[1], n[2], 0.0); vertices[i++] = normal; } _mesh.release_face_normals(); _mesh.release_vertex_normals(); // Iterate over faces and create a traingle for each face by referencing // to its vertices: std::vector<face_indices_t> faces(_mesh.n_faces()); i = 0; for (MyMesh::FaceIter faceIter = _mesh.faces_begin(); faceIter != _mesh.faces_end(); ++faceIter) { MyMesh::ConstFaceVertexIter cfvlt = _mesh.cfv_iter(faceIter.handle()); face_indices_t face; face.a = cfvlt.handle().idx(); ++cfvlt; face.b = cfvlt.handle().idx(); ++cfvlt; face.c = cfvlt.handle().idx(); faces[i++] = face; } { // normalize points to arcBall radius float upperRightOffset = glm::length(glm::vec3(CIRCLE_RADIUS - _upperRight[0], CIRCLE_RADIUS - _upperRight[1], CIRCLE_RADIUS - _upperRight[2])); float lowerLeftOffset = glm::length(glm::vec3(CIRCLE_RADIUS + _lowerLeft[0], CIRCLE_RADIUS + _lowerLeft[1], CIRCLE_RADIUS + _lowerLeft[2])); float arcballNormalizeOffset = std::max(upperRightOffset, lowerLeftOffset); for (size_t i = 0; i < vertices.size(); i++) { if(i % 2 == 0) { //do this only for vertices, not normals vertices[i] *= (1 + arcballNormalizeOffset); vertices[i][3] = 1.0; } } } // Create and bind the object's Vertex Array Object: glGenVertexArrays(1, &_vao); glBindVertexArray(_vao); // Create and bind the object's vertex buffer: glGenBuffers(1, &_vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo); // Create and bind the object's element buffer: glGenBuffers(1, &_ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo); // Create and load vertex data into a Vertex Buffer Object: glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 4 * vertices.size(), &(vertices[0]), GL_STATIC_DRAW); // Create and load face (elements) data into an Element Buffer Object: glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(face_indices_t)*faces.size(), &(faces[0]), GL_STATIC_DRAW); setShadingMode(Model::SHADING_PHONG); glBindVertexArray(0); } void Model::genCircleVertices() { float* tempVertices = new float[_numCircleVertices * 4]; const float step = (2.0 * PI) / (_numCircleVertices - 1); for(int i = 0; i < _numCircleVertices; i++) { float angle = i * step; tempVertices[i * 4] = cosf(angle) * CIRCLE_RADIUS; tempVertices[i * 4 + 1] = sinf(angle) * CIRCLE_RADIUS; tempVertices[i * 4 + 2] = 0; tempVertices[i * 4 + 3] = 1.f; } // Tells OpenGL that there is vertex data in this buffer object and what form that vertex data takes: glBufferData(GL_ARRAY_BUFFER, _numCircleVertices * 4 * sizeof(float), tempVertices, GL_STATIC_DRAW); delete[] tempVertices; } /** This function computes the geometrical center and the axis aligned bounding box of the object. The bounding box is represented by the lower left and upper right corners. */ void Model::computeCenterAndBoundingBox() { /* Vertex iterator is an iterator which goes over all the vertices of the _mesh */ MyMesh::VertexIter vertexIter; /* This is the specific class used to store the geometrical position of the vertices of the mesh */ MyMesh::Point p(0,0,0); const float fm = std::numeric_limits<float>::max(); _lowerLeft = MyMesh::Point(fm, fm, fm); _upperRight = MyMesh::Point(0,0,0); /* number of vertices in the _mesh */ int vNum = _mesh.n_vertices(); vertexIter = _mesh.vertices_begin(); _lowerLeft = _upperRight = _mesh.point(vertexIter); /* This is how to go over all the vertices in the _mesh */ for (vertexIter = _mesh.vertices_begin(); vertexIter != _mesh.vertices_end(); ++vertexIter){ /* this is how to get the point associated with the vertex */ p = _mesh.point(vertexIter); _center += p; for (int i = 0; i < 3; i++) { _lowerLeft[i] = std::min(_lowerLeft[i], p[i]); _upperRight[i] = std::max(_upperRight[i], p[i]); } } _center /= (double)vNum; std::vector<float> v; v.push_back(fabs(_lowerLeft[0])); v.push_back(fabs(_lowerLeft[1])); v.push_back(fabs(_lowerLeft[2])); v.push_back(fabs(_upperRight[0])); v.push_back(fabs(_upperRight[1])); v.push_back(fabs(_upperRight[2])); _maxV = *std::max_element(v.begin(), v.end()); _lowerLeft /= _maxV; _lowerLeft *= CIRCLE_RADIUS; _upperRight /= _maxV; _upperRight *= CIRCLE_RADIUS; } void Model::loadMesh(const char* fileName) { if (!OpenMesh::IO::read_mesh(_mesh, fileName)) { // if we didn't make it, exit... fprintf(stderr, "Error loading mesh, Aborting.\n"); } } void Model::init(const char* meshFile) { programManager::sharedInstance() .createProgram("RgbShader", SHADERS_DIR "RgbShader.vert", SHADERS_DIR "RgbShader.frag"); programManager::sharedInstance() .createProgram("PhongShader", SHADERS_DIR "PhongShader.vert", SHADERS_DIR "PhongShader.frag"); programManager::sharedInstance() .createProgram("GuShader", SHADERS_DIR "GuShader.vert", SHADERS_DIR "GuShader.frag"); programManager::sharedInstance() .createProgram("circle", SHADERS_DIR "CircleShader.vert", SHADERS_DIR "CircleShader.frag"); _programRgb = programManager::sharedInstance().programWithID("RgbShader"); _programGu = programManager::sharedInstance().programWithID("GuShader"); _programPhong = programManager::sharedInstance().programWithID("PhongShader"); _programCircle = programManager::sharedInstance().programWithID("circle"); // Initialize vertices buffer and transfer it to OpenGL // Initialize Circle { // Create and bind the object's Vertex Array Object: glGenVertexArrays(1, &_vaoCircle); glBindVertexArray(_vaoCircle); // Create and load vertex data into a Vertex Buffer Object: glGenBuffers(1, &_vboCircle); glBindBuffer(GL_ARRAY_BUFFER, _vboCircle); //generate vertices to create the circle genCircleVertices(); // Obtain attribute handles: _posAttribCircle = glGetAttribLocation(_programCircle, "position"); glEnableVertexAttribArray(_posAttribCircle); glVertexAttribPointer(_posAttribCircle, // attribute handle 4, // number of scalars per vertex GL_FLOAT, // scalar type GL_FALSE, 0, 0); glBindVertexArray(0); } // Initialize Model { //generate vertices to create the circle loadMesh(meshFile); computeCenterAndBoundingBox(); genModelVertices(); genModelVerticesFaces(); resetMatrices(); } } void Model::bindAttributes(GLuint program) { // Obtain uniform variable handles: _modelViewUV = glGetUniformLocation(program, "modelView"); _projectionUV = glGetUniformLocation(program, "projection"); _specExpUV = glGetUniformLocation(program, "specExp"); // Obtain attribute handles: _posAttrib = glGetAttribLocation(program, "position"); glEnableVertexAttribArray(_posAttrib); glVertexAttribPointer(_posAttrib, // attribute handle 4, // number of scalars per vertex GL_FLOAT, // scalar type GL_FALSE, sizeof(glm::vec4) * 2, 0); _normalAttrib = glGetAttribLocation(program, "normal"); glEnableVertexAttribArray(_normalAttrib); glVertexAttribPointer(_normalAttrib, // attribute handle 4, // number of scalars per vertex GL_FLOAT, // scalar type GL_FALSE, sizeof(glm::vec4) * 2, (GLvoid*)(sizeof(glm::vec4))); } glm::vec2 Model::getScreenUnitCoordinates(glm::vec2 pos) { pos.x = 2 * (pos.x / _width) - 1.f; pos.y = 2 * (pos.y / _height) - 1.f; pos.y = -pos.y; return pos; } void Model::resetMatrices() { _fov = INITIAL_FOV; _fovBase = _fov; _projectionMat = glm::perspective(_fov, float(_width)/float(_height), OBJECT_DEPTH - OBJECT_B_RAD, OBJECT_DEPTH + OBJECT_B_RAD); _viewMat = glm::lookAt(glm::vec3(0, 0, OBJECT_DEPTH), glm::vec3(),glm::vec3(0,1,0)); _modelMat = glm::mat4(); _translateMat = glm::mat4(); _rotationMat = glm::mat4(); _scaleMat = glm::scale(glm::mat4(), glm::vec3(MODEL_SCALE)); } void Model::toggleProjectionMode() { if(_viewMode == ORTHOGONAL) { _viewMode = PERSPECTIVE; } else { _viewMode = ORTHOGONAL; } updateProjectionMatrix(); } void Model::updateProjectionMatrix() { if(_viewMode == PERSPECTIVE) { _projectionMat = glm::perspective(_fov, float(_width)/float(_height), OBJECT_DEPTH - OBJECT_B_RAD, OBJECT_DEPTH + OBJECT_B_RAD); } else { float ty = tanf(glm::radians(_fov / 2)) * 2; float tx = ty * float(_width)/float(_height); _projectionMat = glm::ortho(-tx, tx, -ty, ty, OBJECT_DEPTH - OBJECT_B_RAD, OBJECT_DEPTH + OBJECT_B_RAD); } } void Model::draw() { // Set the program to be used in subsequent lines: glUseProgram(_program); glPolygonMode(GL_FRONT_AND_BACK, _glPolygonMode); // Draw using the state stored in the Vertex Array object: glm::mat4 modelView = _translateMat * _viewMat * _rotationMat * _modelMat * _scaleMat; glUniformMatrix4fv(_projectionUV, 1, GL_FALSE, glm::value_ptr(_projectionMat)); glUniformMatrix4fv(_modelViewUV, 1, GL_FALSE, glm::value_ptr(modelView)); glUniform1f(_specExpUV, _specExp); if (_normalMode == NORMAL_FACE) { glBindVertexArray(_vao); glDrawElements(GL_TRIANGLES, _mesh.n_faces() * 3, GL_UNSIGNED_INT, NULL); } else { glBindVertexArray(_vaoFace); glDrawArrays(GL_TRIANGLES, 0, _mesh.n_faces() * 3); } // Unbind the Vertex Array object glBindVertexArray(0); // Cleanup, not strictly necessary glUseProgram(0); } void Model::draw2D() { glUseProgram(_programCircle); glBindVertexArray(_vaoCircle); glDrawArrays(GL_LINE_LOOP, 0, _numCircleVertices); // Unbind the Vertex Array object glBindVertexArray(0); glUseProgram(0); } void Model::resize(int width, int height) { _width = width; _height = height; updateProjectionMatrix(); } void Model::changePolygonMode() { if(_glPolygonMode == GL_FILL) { _glPolygonMode = GL_LINE; } else { _glPolygonMode = GL_FILL; } } glm::vec2 Model::normalizeScreenCoordninates(glm::vec2 v) { v.x /= _width; v.y /= _height; return v; } glm::vec3 Model::arcBall(glm::vec2 v) { float z; if (glm::length(v) > 1) { z = 0; } else { z = std::sqrt(1 - glm::dot(v,v)); } return glm::vec3(v.x, v.y, z); } void Model::rotate(int x, int y) { glm::vec2 p1 = getScreenUnitCoordinates(_xyRotateBase); glm::vec2 p2 = getScreenUnitCoordinates(glm::vec2(x,y)); p1 *= (1/CIRCLE_RADIUS); p2 *= (1/CIRCLE_RADIUS); glm::vec3 v1 = arcBall(p1); glm::vec3 v2 = arcBall(p2); glm::vec3 dir = glm::normalize(glm::cross(v1, v2)); float angle = 2 * glm::degrees(glm::acos(glm::dot(glm::normalize(v1), glm::normalize(v2)))); _rotationMat = glm::rotate(glm::mat4(), angle, dir); } void Model::scale(int y) { int dy = _yScaleBase - y; _fov = _fovBase * (1 + dy / _height); if (_fov > MAX_FOV) { _fov = MAX_FOV; } if (_fov < MIN_FOV) { _fov = MIN_FOV; } updateProjectionMatrix(); } void Model::translate(int x, int y) { glm::vec2 dxy = getScreenUnitCoordinates(glm::vec2(x, y)) - getScreenUnitCoordinates(_xyTranslateBase); _translateMat = glm::translate(glm::mat4(1.0f), glm::vec3(dxy, 0)); } void Model::setMouseFlag(int button, int x, int y) { if(button == GLUT_LEFT_BUTTON) { _xyRotateBase = glm::vec2(x, y); if (glm::length(getScreenUnitCoordinates(_xyRotateBase)) < CIRCLE_RADIUS) { _mouseFlags[GLUT_LEFT_BUTTON] = true; } } else if (button == GLUT_MIDDLE_BUTTON) { _yScaleBase = y; _mouseFlags[GLUT_MIDDLE_BUTTON] = true; } else if (button == GLUT_RIGHT_BUTTON) { _xyTranslateBase = glm::vec2(x, y); _mouseFlags[GLUT_RIGHT_BUTTON] = true; } } void Model::resetMouseFlag(int button) { if (button == GLUT_LEFT_BUTTON) { _modelMat = _rotationMat * _modelMat; _rotationMat = glm::mat4(); } else if (button == GLUT_MIDDLE_BUTTON) { _fovBase = _fov; } else if (button == GLUT_RIGHT_BUTTON) { _modelMat = _translateMat * _modelMat; _translateMat = glm::mat4(); } _mouseFlags[button] = false; } void Model::motion(int x, int y) { if (_mouseFlags[GLUT_LEFT_BUTTON]) { rotate(x, y); } else if (_mouseFlags[GLUT_MIDDLE_BUTTON]) { scale(y); } else if (_mouseFlags[GLUT_RIGHT_BUTTON]) { translate(x, y); } } void Model::toggleNormalMode() { if (_normalMode == NORMAL_FACE) { _normalMode = NORMAL_VERTEX; } else { _normalMode = NORMAL_FACE; } } void Model::setShadingMode(Model::shadingMode mode) { _shadingMode = mode; switch(_shadingMode) { case SHADING_RGB: _program = _programRgb; break; case SHADING_GOURAUD: _program = _programGu; break; case SHADING_PHONG: _program = _programPhong; break; default: break; } glUseProgram(0); bindAttributes(_program); glUseProgram(_program); } void Model::decreaseSpec() { if(_specExp > 0) { _specExp -= 5; } } void Model::increaseSpec() { if(_specExp < 2000) { _specExp += 5; } }
#include "ofTimer.h" #define NANOS_PER_SEC 1000000000ll void ofGetMonotonicTime(uint64_t & seconds, uint64_t & nanoseconds); ofTimer::ofTimer() :nanosPerPeriod(0) #ifdef TARGET_WIN32 ,hTimer(CreateWaitableTimer(nullptr, TRUE, nullptr)) #endif { } void ofTimer::reset(){ #if defined(TARGET_WIN32) GetSystemTimeAsFileTime((LPFILETIME)&nextWakeTime); #else nextWakeTime = ofGetCurrentTime(); #endif calculateNextPeriod(); } void ofTimer::setPeriodicEvent(uint64_t nanoseconds){ nanosPerPeriod = std::chrono::nanoseconds(nanoseconds); reset(); } void ofTimer::waitNext(){ #if (defined(TARGET_LINUX) && !defined(TARGET_RASPBERRY_PI)) timespec remainder = {0,0}; timespec wakeTime = nextWakeTime.getAsTimespec(); clock_nanosleep(CLOCK_MONOTONIC,TIMER_ABSTIME,&wakeTime,&remainder); #elif defined(TARGET_WIN32) WaitForSingleObject(hTimer, INFINITE); #else auto now = ofGetCurrentTime(); auto waitNanos = nextWakeTime - now; if(waitNanos > std::chrono::nanoseconds(0)){ timespec waittime = (ofTime() + waitNanos).getAsTimespec(); timespec remainder; nanosleep(&waittime,&remainder); } #endif calculateNextPeriod(); } void ofTimer::calculateNextPeriod(){ #if defined(TARGET_WIN32) nextWakeTime.QuadPart += nanosPerPeriod.count()/100; LARGE_INTEGER now; GetSystemTimeAsFileTime((LPFILETIME)&now); if(nextWakeTime.QuadPart<now.QuadPart){ reset(); }else{ SetWaitableTimer(hTimer, &nextWakeTime, 0, nullptr, nullptr, 0); } #else nextWakeTime += nanosPerPeriod; auto now = ofGetCurrentTime(); if(nextWakeTime<now){ reset(); } #endif }
#include <iostream> using std::cout; using std::cin; using std::endl; #include <cstddef> using std::size_t; int main() { int arr[10] = {}; int arr_copy[10] = {}; int index = 0; for(auto &i : arr) { i = index++; } for(auto j : arr) cout << j << endl; for(int i = 0; i < 10; i++) arr_copy[i] = arr[i]; for(auto j : arr_copy) cout << j << endl; return 0; }
#include <Unixfunc.h> #include <iostream> #include <sys/ipc.h> #include <sys/shm.h> using namespace std; /* 案例二:非亲属进程间通信 写端 写入HelloWorld , 读端进行读取 */ int main() { key_t key = ftok("file", 1); ERROR_CHECK(key, -1, "ftok"); int shmid = shmget(key, 1024, 0600); ERROR_CHECK(shmid, -1, "shmget"); char* buf = (char*)shmat(shmid, NULL, 0); ERROR_CHECK(buf, (char*)-1, "shmat"); cout << "reading from shared memory:" << buf << endl; int ret = shmctl(shmid, IPC_RMID, NULL); ERROR_CHECK(ret, -1, "shmctl"); return 0; }
//===================================== Bibliotecas E Definições ===================================== #include <EEPROM.h> //EEPROM #include <SPI.h> //Biblioteca necessária para comunicação SPI #include <SD.h> //Biblioteca necessária para comunicação SD card #include <Wire.h> //Biblioteca para comunicação I2C com módulo RTC #include <LiquidCrystal.h> //Biblioteca para display 16x2 #include <avr/wdt.h> //Biblioteca referente ao Timer WatchDog //============================================= HARDWARE ============================================= //Constantes #define DS1307_ADDRESS 0x68 #define AtualizacaoDisplay 150 #define AtrasoBotoes 300 #define EnderecoTempoSalvar 0 #define EnderecoCalibracao 1 //Pinos #define rs 2 //D2 #define en 3 //D3 #define d4 4 //D4 #define d5 5 //D5 #define d6 6 //D6 #define d7 7 //D7 #define up 8 //D8 #define select 9 //D9 #define mais 0 //D0 #define menos 1 //D1 #define SelecaoChip 10 //D10 -Chip Select #define MOSI 11 //D11 - MOSI #define MISO 12 //D12 - MISO #define SCK 13 //D13 - SCk #define Bateria_1 14 //A0 #define Bateria_2 15 //A1 #define Bateria_3 16 //A2 #define Bateria_4 17 //A3 //============================================= Variáveis ============================================ LiquidCrystal lcd (rs, en, d4, d5, d6, d7); //Crio o objeto lcd com seus respectivos pinos const byte SelecionadorOpcao[8] = //Lista para o caractere especial (O quadrado) { 0b00000, 0b00000, 0b01110, 0b01110, 0b01110, 0b01110, 0b00000, 0b00000 }; //Caracteres especiais const byte C_Cedilhado[8] { //Lista para o caractere especial ("Ç") 0b00000, 0b01110, 0b10000, 0b10000, 0b10000, 0b01110, 0b00100, 0b00100 }; const byte O_Til[8] { //Lista para o caractere especial ("Õ") 0b01110, 0b00000, 0b01110, 0b10001, 0b10001, 0b10001, 0b01110, 0b00000 }; const byte A_Til[8] { //Lista para o caractere especial ("Ã") 0b01110, 0b00000, 0b01110, 0b00001, 0b01111, 0b10001, 0b01111, 0b00000 }; const byte A_Agudo[8] { //Lista para o caractere especial ("Ã") 0b00010, 0b00100, 0b01110, 0b00001, 0b01111, 0b10001, 0b01111, 0b00000 }; //Seletores para os menus byte SeletorPrincipal = 0; byte SeletorDadosBateria = 1; byte SeletorConfiguracoes = 0; //De tempo byte Timer_salvar = 0; byte MinutoAnterior_salvar = 0; byte TempoParaSalvar = 1; //Número de amostras para o filtro ADC. Quanto maior, melhor, mas terá impacto no desempenho do sistema. float TensaoCalibracao = 5.00; byte Amostras_Filtro = 30; //Das baterias float Bateria1 = 0.00f; float Bateria2 = 0.00f; float Bateria3 = 0.00f; float Bateria4 = 0.00f; float Teste[20] = {0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f, 0.00f}; byte zero = 0x00; //Do relogio RTC byte segundo = 0; //0~59 byte minuto = 0; //0~59 byte hora = 0; //Formato 24 horas byte diasemana = 0; //0-6 -> Domingo - Sábado byte dia = 0; //Dependendo do mês, de 1~31 byte mes = 0; //1~12 byte ano = 0; //0~99 //************ FUNÇÕES DA PARTE DE LEITURA E ESCRITA DOS DADOS NO CARTAO SD ********************* //Função para ler os níveis da baterias float LeituraBateria(int porta) { unsigned int media = 0; float tensao = 0.00f; for(int i = 0; i < Amostras_Filtro; i++){ media += analogRead(porta); delayMicroseconds(1000); } tensao = float(media)/Amostras_Filtro; tensao = tensao*5.05/1023; return tensao; } //Função "link" para os níveis das baterias void NiveisBaterias() { Bateria1 = LeituraBateria(Bateria_1); Bateria2 = LeituraBateria(Bateria_2); Bateria3 = LeituraBateria(Bateria_3); Bateria4 = LeituraBateria(Bateria_4); } //Função para ler os dados e criar um String void leituraEscrita() { /* PADRÃO DA ESCRITA * 0.000V, 0.000V, 0.000V, 0.000V -- 00/00/0000 00:00:00 */ NiveisBaterias(); String LinhaDados = ""; LinhaDados += String(Bateria1, 3); LinhaDados += "V, "; LinhaDados += String(Bateria2, 3); LinhaDados += "V, "; LinhaDados += String(Bateria3, 3); LinhaDados += "V, "; LinhaDados += String(Bateria4, 3); LinhaDados += "V -- "; //Dia if(dia < 10) LinhaDados += '0'; //Se o dia for menor que 10, adiciono um zero à frente. LinhaDados += String(dia); LinhaDados += "/"; //Mês if(mes < 10) LinhaDados += '0'; //Se o mes for menor que 10, adiciono um zero à frente. LinhaDados += String(mes); LinhaDados += "/"; //Ano LinhaDados += "20"; if(ano < 10) LinhaDados += '0'; //Se o ano for menor que 10, adiciono um zero à frente. LinhaDados += String(ano); LinhaDados += " "; //Hora if(hora < 10) LinhaDados += '0'; //Se a hora for menor que 10, adiciono um zero à frente LinhaDados += String(hora); LinhaDados += ":"; //Minuto if(minuto < 10) LinhaDados += '0'; //Se o minuto for menor que 10, adiciono um zero à frente LinhaDados += String(minuto); LinhaDados += ":"; //Segundo if(segundo < 10) LinhaDados += '0'; //Se o segundo for menor que 10, adiciono um zero à frente LinhaDados += String(segundo); //Por fim, escrevo os dados. escreverCartao(LinhaDados); delay(1000); } //Conversões necessárias para leitura e escrita no relógio RTC byte decToBcd(byte valor) { return ( (valor/10*16) + (valor%10) ); } byte bcdToDec(byte val) { return ( (val/16*10) + (val%16) ); } //Leitura da hora e atualização das variáveis void LeituraHora() { Wire.beginTransmission(DS1307_ADDRESS); //Inicio a comunição I2C Wire.write(zero); //Inicio Wire.endTransmission(); Wire.requestFrom(DS1307_ADDRESS, 7); //Pego todos os dados de hora //Atribuo os respectivos dados as suas variáveis segundo = bcdToDec(Wire.read()); minuto = bcdToDec(Wire.read()); hora = bcdToDec(Wire.read() & 0b111111); //Formato 24 horas diasemana = bcdToDec(Wire.read()); //0-6 -> Domingo - Sábado dia = bcdToDec(Wire.read()); mes = bcdToDec(Wire.read()); ano = bcdToDec(Wire.read()); //Meu 'timer' para salvar dados if(Timer_salvar < TempoParaSalvar) { if(MinutoAnterior_salvar != minuto) { MinutoAnterior_salvar = minuto; Timer_salvar += 1; } if(Timer_salvar == TempoParaSalvar){ leituraEscrita(); Timer_salvar = 0; } } } //Atualização dos dados de horário no RTC void AtualizaRTC(byte minuto, byte hora, byte dia, byte mes, byte ano, byte diasemana) { byte segundo = 00; //0~59 Wire.beginTransmission(DS1307_ADDRESS); Wire.write(zero); Wire.write(decToBcd(segundo)); Wire.write(decToBcd(minuto)); Wire.write(decToBcd(hora)); Wire.write(decToBcd(diasemana)); Wire.write(decToBcd(dia)); Wire.write(decToBcd(mes)); Wire.write(decToBcd(ano)); Wire.write(zero); Wire.endTransmission(); } //Função para abrir o arquivo e escrever os dados void escreverCartao(String Dados) { File dataFile = SD.open("dadosbaterias.txt", FILE_WRITE); //Mensagem "Salvar dados" lcd.clear(); lcd.setCursor(1, 0); lcd.print("Salvando Dados"); lcd.setCursor(2, 1); lcd.print("No cartao"); for(byte i = 0; i<3; i++) { lcd.write('.'); delay(1000); } if(dataFile) { //Se tudo estiver configurado com o cartão dataFile.println(Dados); //Escrevo a linha com os dados dataFile.close(); //Fecho o arquivo (para evitar erros) salvoComSucesso(); } else { erroGeral(); } } //**************************************** MENUS DO LCD **************************************** //******************** FUNCOES REFERENTES A MENUS AUXILIARES ************************** //Mensagem de "salvo com sucesso" void salvoComSucesso() { lcd.clear(); lcd.setCursor(3, 0); lcd.print("Salvo com"); lcd.setCursor(4, 1); lcd.print("Sucesso!"); //Mantenho a mensagem por 1 segundo delay(1000); lcd.clear(); return; } //Mensagem de erro geral void erroGeral() { lcd.clear(); lcd.setCursor(4, 0); lcd.print("Erro ao"); lcd.setCursor(4, 1); lcd.print("Salvar!"); //Mantenho a mensagem por 1,5 segundo(s) delay(1500); lcd.clear(); return; } void erroCartao() { lcd.clear(); lcd.setCursor(1, 0); lcd.print("Erro ao salvar"); lcd.setCursor(3, 1); lcd.print("no cartao SD!"); //Mantenho a mensagem por 1 segundo delay(1000); lcd.clear(); return; } void erroAbrirCartao() { lcd.clear(); lcd.setCursor(3, 0); lcd.print("Cartao SD "); lcd.setCursor(1, 1); lcd.print("Nao encontrado."); //Mantenho a mensagem por 1 segundo delay(1500); lcd.clear(); return; } //************************* FUNÇÕES DO MENU PRINCIPAL ********************************* //MenuPrincipal do programa void menuPrincipal() { //Necessario para ficar neste menu while(true) { //Antes de tudo, limpo todo conteúdo do display e verifico a hora e o timer lcd.clear(); //LeituraHora(); //Leitura de botões e atualização de variáveis if(!digitalRead(mais) == HIGH) { SeletorPrincipal += 1; delay(AtrasoBotoes); } else if(!digitalRead(menos) == HIGH) { SeletorPrincipal -= 1; delay(AtrasoBotoes); } //Limites para o menu principal if(SeletorPrincipal > 1){ SeletorPrincipal = 0; } else if(SeletorPrincipal < 0) { SeletorPrincipal = 1; } //Escrever a mensagem do menu principal lcd.setCursor(1, 0); lcd.print("Menu Principal"); //Alterando a posição do cursor (">") para informar ao usuário qual menu ele deseja escolher if(SeletorPrincipal == 0) { lcd.setCursor(9, 1); lcd.print(" Config"); lcd.setCursor(0, 1); lcd.print(">Niveis "); } else { lcd.setCursor(0, 1); lcd.print(" Niveis "); lcd.setCursor(9, 1); lcd.print(">Config"); } //Quando o botao de selecionar menu for pressionado, o programa entrará no menu onde o cursor está if(!digitalRead(select) == HIGH) { delay(AtrasoBotoes); switch(SeletorPrincipal) { case 0: dadosBateria(); //Menu dos dados da bateria break; case 1: configuracoes(); //Menu das configurações de hora, relogio, sistema. break; } } delay(AtualizacaoDisplay); //Atraso para Atualizar o display } } //************************* FUNÇÕES PARA O MENU DE DADOS BATERIA ********************************* void dadosBateria() { while(!digitalRead(up) == LOW) { //Loop necessário para o programa ficar nesse menu //Leitura de botões e atualização de variáveis if(!digitalRead(mais) == HIGH) { SeletorDadosBateria += 1; delay(AtrasoBotoes); } else if(!digitalRead(menos) == HIGH) { SeletorDadosBateria -= 1; delay(AtrasoBotoes); } //Limites no menu da bateria if(SeletorDadosBateria < 1) { SeletorDadosBateria = 4; } else if(SeletorDadosBateria > 4) { SeletorDadosBateria = 1; } //Trocar entre os menus switch(SeletorDadosBateria) { case 1: statusBat(Bateria1, 1); break; case 2: statusBat(Bateria2, 2); break; case 3: statusBat(Bateria3, 3); break; case 4: statusBat(Bateria4, 4); break; } } } //Função para mostrar o dado da bateria selecionada void statusBat(float NivelBateria, int ValorBat) { String TensaoEmString = ""; while(true) { LeituraHora(); //Verifico o timer e consequentemente a hora NiveisBaterias(); //Leio os níveis das 4 baterias lcd.clear(); //Limpar o que tem na tela lcd.setCursor(3, 0); //Posiciono o cursor para printar o número da bateria selecionada //Mostrar o status das bateria selecionada if(ValorBat == 1) { lcd.print("Bateria 1:"); NivelBateria = Bateria1; } else if(ValorBat == 2) { lcd.print("Bateria 2:"); NivelBateria = Bateria2; } else if(ValorBat == 3) { lcd.print("Bateria 3:"); NivelBateria = Bateria3; } else if(ValorBat == 4) { lcd.setCursor(3, 0); lcd.print("Bateria 4:"); NivelBateria = Bateria4; } //Mostrar o valor da bateria em VOLTS lcd.setCursor(5, 1); if(NivelBateria >= 1.00) { lcd.print(NivelBateria, 3); lcd.setCursor(10, 1); lcd.write('V'); } //Mostro o valor da bateria em miliVolts else { lcd.setCursor(5, 1); TensaoEmString = String(NivelBateria, 4); for(byte i = 2; i < 5; i++) { lcd.write(TensaoEmString[i]); } lcd.print(" mV"); } //Verifico os botões if(!digitalRead(up) == HIGH) { delay(AtrasoBotoes); break; } if(!digitalRead(mais) == HIGH) { SeletorDadosBateria += 1; delay(AtrasoBotoes); break; } if(!digitalRead(menos) == HIGH) { SeletorDadosBateria -= 1; delay(AtrasoBotoes); break; } delay(AtualizacaoDisplay); //Atraso para Atualizar o display } } //************************** FUNÇÕES PARA O MENU DE CONFIGURAÇÕES ********************************** void configuracoes() { while(!digitalRead(up) == LOW) { //Loop necessário para o programa ficar nesse menu lcd.clear(); //Printar as palavras lcd.setCursor(2, 0); lcd.print("Configuracoes"); lcd.setCursor(1, 1); lcd.print("Arquivo"); lcd.setCursor(12, 1); lcd.print("Hora"); if(!digitalRead(mais) == HIGH) { SeletorConfiguracoes += 1; delay(AtrasoBotoes); } else if(!digitalRead(menos) == HIGH) { SeletorConfiguracoes -= 1; delay(AtrasoBotoes); } //Limites para o menu de configuracoes if(SeletorConfiguracoes > 1){ SeletorConfiguracoes = 0; } else if(SeletorConfiguracoes < 0) { SeletorConfiguracoes = 1; } if(SeletorConfiguracoes == 0) { lcd.setCursor(0, 1); lcd.print(">"); lcd.setCursor(11, 1); lcd.write(' '); } else { lcd.setCursor(0, 1); lcd.print(' '); lcd.setCursor(11, 1); lcd.write('>'); } if(!digitalRead(select) == HIGH) { delay(AtrasoBotoes); switch(SeletorConfiguracoes) { case 0: configurarArquivo(); break; case 1: mostrarHora(); break; case 2: //calibracao(); break; } } delay(AtualizacaoDisplay); //Atraso para Atualizar o display } } void configurarArquivo() { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Atualiza arquivo"); lcd.setCursor(0, 1); lcd.print("a cada: "); while(true) { delay(AtualizacaoDisplay); //Atraso para Atualizar o display if(!digitalRead(select) == HIGH) { delay(AtrasoBotoes); break; } if(!digitalRead(menos) == HIGH) { delay(AtrasoBotoes); TempoParaSalvar--; } if(!digitalRead(mais) == HIGH) { delay(AtrasoBotoes); TempoParaSalvar++; } if(TempoParaSalvar < 1) { TempoParaSalvar = 60; } else if(TempoParaSalvar > 60) { TempoParaSalvar = 1; } lcd.setCursor(9, 1); if(TempoParaSalvar < 10) { lcd.write('0'); lcd.setCursor(10, 1); } lcd.print(TempoParaSalvar); lcd.print(" Min"); } EEPROM.update(EnderecoTempoSalvar, TempoParaSalvar); //Atualizo o intervalo entre cada vez que o conteúdo é salvo. salvoComSucesso(); return; } void mostrarHora() { bool ManterMenu = false; bool AlterarHora = true; //String DadoDoTempo = ""; lcd.clear(); delay(300); while(!ManterMenu) { LeituraHora(); lcd.setCursor(1 ,0); lcd.print("Hor"); lcd.write((byte)5); lcd.print("rio atual:"); lcd.setCursor(0, 1); String DataHora = ""; if(hora < 10) { //Escrever a hora no display DataHora += '0'; } DataHora += String(hora); DataHora += ':'; if(minuto < 10) { //Escrever o minuto no display DataHora += '0'; } DataHora += String(minuto); DataHora += '-'; if(dia < 10) { //Escrever o dia no display DataHora += '0'; } DataHora += String(dia); DataHora += ':'; if(mes < 10) { //escrever o mês no LCD DataHora += '0'; } DataHora += String(mes); DataHora += ":20"; if(ano < 10) { DataHora += '0'; } DataHora += String(ano); //Por fim, imprimo a data no display lcd.print(DataHora); if(!digitalRead(select) == HIGH) { ManterMenu = true; delay(AtrasoBotoes); } if(!digitalRead(up) == HIGH) { ManterMenu = false; delay(AtrasoBotoes); return; } delay(AtualizacaoDisplay); //Atraso para Atualizar o display } //Após verificar a hora, pergunto ao usuário se ele deseja alterar a hora lcd.clear(); //Reaproveito a variável "ManterMenu" dessa vez no proxímo menu ManterMenu = false; while(!ManterMenu) { lcd.setCursor(0, 0); lcd.print("Configurar Data?"); lcd.setCursor(3, 1); lcd.print("SIM"); lcd.setCursor(10, 1); lcd.print("NAO"); if(AlterarHora) { lcd.setCursor(2, 1); lcd.write('>'); lcd.setCursor(9, 1); lcd.write(' '); } else { lcd.setCursor(2, 1); lcd.write(" "); lcd.setCursor(9, 1); lcd.write(">"); } if((!digitalRead(mais) == HIGH) || (!digitalRead(menos) == HIGH)) { AlterarHora = !AlterarHora; delay(AtrasoBotoes); } if(!digitalRead(select) == HIGH) { ManterMenu = true; delay(AtrasoBotoes); } delay(AtualizacaoDisplay); //Atraso para Atualizar o display } lcd.clear(); if(AlterarHora) { funcaoAlterarHora(); } } /* void calibracao() { byte ValorCalibracao = 127; lcd.clear(); lcd.setCursor(1, 0); lcd.print("Siga os passos"); lcd.setCursor(2, 1); lcd.print("do manual!"); delay(3000); while(true) { //Verificacao dos botões if(!digitalRead(up) == HIGH) { delay(AtrasoBotoes); return; } if(!digitalRead(select) == HIGH) { delay(AtrasoBotoes); break; } if(!digitalRead(mais) == HIGH) { ValorCalibracao += 1; delay(AtrasoBotoes); } if(!digitalRead(menos) == HIGH) { ValorCalibracao -= 1; delay(AtrasoBotoes); } lcd.clear(); lcd.print(2, 0); lcd.print("Calibra"); lcd.write((byte)2); lcd.write((byte)3); lcd.write('o'); lcd.setCursor(6, 1); lcd.print(ValorCalibracao); } } */ void funcaoAlterarHora() { LeituraHora(); //Pego os dados da hora neste instante byte MinutoConfigurado = minuto; byte HoraConfigurado = hora; byte DiaConfigurado = dia; byte MesConfigurado = mes; byte AnoConfigurado = ano; byte DiaSemanaConfigurado = diasemana; byte ValorASerAtualizado = 0; byte OpcaoSelecionada = 0; bool ManterMenu = true; //Antes de tudo, limpo o conteúdo do display lcd.clear(); //Mantenho o menu perguntando ao usuário o que ele deseja alterar while(ManterMenu) { //Leitura dos botoes e limitacao de range if(!digitalRead(up) == HIGH) { ManterMenu = false; delay(AtrasoBotoes); } if(!digitalRead(mais) == HIGH) { OpcaoSelecionada++; delay(AtrasoBotoes); } if(!digitalRead(menos) == HIGH) { OpcaoSelecionada--; delay(AtrasoBotoes); } if (OpcaoSelecionada < 0) { OpcaoSelecionada = 0; } //Menu 1 - Minuto e hora if((OpcaoSelecionada == 0) || (OpcaoSelecionada == 1)) { if(OpcaoSelecionada == 0) { lcd.clear(); lcd.setCursor(0, 0); lcd.write((byte)1); // imprimindo o carcter do seletor para opção "Minutos" lcd.setCursor(2, 1); lcd.write('>'); } else { lcd.clear(); lcd.setCursor(9, 0); lcd.write((byte)1); // imprimindo o carcter do seletor para opção "Horas" lcd.setCursor(10, 1); lcd.write('>'); } lcd.setCursor(3, 1); if(MinutoConfigurado < 10){ lcd.write('0'); lcd.setCursor(4, 1); lcd.print(MinutoConfigurado); } else if(MinutoConfigurado >= 10) { lcd.print(MinutoConfigurado); } lcd.setCursor(11, 1); if(HoraConfigurado < 10){ lcd.write('0'); lcd.print(HoraConfigurado); } else if(HoraConfigurado >= 10) { lcd.print(HoraConfigurado); } lcd.setCursor(1, 0); lcd.print("Minutos"); lcd.setCursor(10, 0); lcd.print("Horas"); } //Menu 2 - Data e mês if((OpcaoSelecionada == 2) || (OpcaoSelecionada == 3) || (OpcaoSelecionada == 4)) { if(OpcaoSelecionada == 2) { lcd.clear(); lcd.setCursor(0, 0); lcd.write((byte)1); // imprimindo o carcter especial 1 lcd.setCursor(1, 1); lcd.write('>'); } else if(OpcaoSelecionada == 3) { lcd.clear(); lcd.setCursor(6, 0); lcd.write((byte)1); lcd.setCursor(7, 1); lcd.write('>'); } else { lcd.clear(); lcd.setCursor(12, 0); lcd.write((byte)1); lcd.setCursor(13, 1); lcd.write('>'); } lcd.setCursor(2, 1); if(DiaConfigurado < 10) { lcd.write('0'); lcd.print(DiaConfigurado); } else if (DiaConfigurado >= 10) { lcd.print(DiaConfigurado); } lcd.setCursor(8, 1); if(MesConfigurado < 10) { lcd.write('0'); lcd.print(MesConfigurado); } else if(MesConfigurado >= 10) { lcd.print(MesConfigurado); } lcd.setCursor(14, 1); if(AnoConfigurado < 10) { lcd.write('0'); lcd.print(AnoConfigurado); } else if(AnoConfigurado >= 10) { lcd.print(AnoConfigurado); } lcd.setCursor(1, 0); lcd.print("Data"); lcd.setCursor(7, 0); lcd.print("Mes"); lcd.setCursor(13, 0); lcd.print("Ano"); } //Por último, o dia da semana if(OpcaoSelecionada == 5) { lcd.clear(); lcd.setCursor(6, 0); lcd.write((byte)1); lcd.print("Dia"); lcd.setCursor(3, 1); lcd.write('>'); switch(DiaSemanaConfigurado) { case 0: lcd.print("DOMINGO"); case 1: lcd.print("SEGUNDA"); case 2: lcd.print("TERCA"); case 3: lcd.print("QUARTA"); case 4: lcd.print("QUINTA"); case 5: lcd.print("SEXTA"); case 6: lcd.print("SABADO"); } } //Verifico se o botao de selecao foi pressionado if(!digitalRead(select) == HIGH) { delay(AtrasoBotoes); //Verificando a opcao selecionada do usuário switch(OpcaoSelecionada) { case 0: //Minuto MinutoConfigurado = atualizaValor(OpcaoSelecionada, MinutoConfigurado); break; case 1: //Hora HoraConfigurado = atualizaValor(OpcaoSelecionada, HoraConfigurado); break; case 2: DiaConfigurado = atualizaValor(OpcaoSelecionada, DiaConfigurado); break; case 3: MesConfigurado = atualizaValor(OpcaoSelecionada, MesConfigurado); break; case 4: AnoConfigurado = atualizaValor(OpcaoSelecionada, AnoConfigurado); break; case 5: DiaSemanaConfigurado = atualizaValor(OpcaoSelecionada, DiaSemanaConfigurado); break; } } if(OpcaoSelecionada > 5) { SalvarData(MinutoConfigurado, HoraConfigurado, DiaConfigurado, MesConfigurado, AnoConfigurado, DiaSemanaConfigurado); return; } delay(AtualizacaoDisplay); } //Fim do loop menu lcd.clear(); } byte atualizaValor(byte OpcaoSelecionada, byte ValorASerAtualizado) { byte Limite = 0; byte ValorAtualizado = 0; bool ManterMenu = true; lcd.clear(); lcd.setCursor(0, 0); lcd.write((byte)1); lcd.setCursor(9, 0); lcd.print("RELOGIO"); lcd.setCursor(1, 0); //Verifico qual opção o usuário está alterando switch(OpcaoSelecionada) { case 0: Limite = 59; //Minuto lcd.print("Minuto"); break; case 1: Limite = 24; //Hora lcd.print("Hora"); break; case 2: Limite = 31; //Data lcd.print("Data"); break; case 3: Limite = 12; //Mês lcd.print("Mes"); break; case 4: Limite = 99; //Ano lcd.print("Ano"); break; case 5: Limite = 6; //Dia lcd.print("Dia"); break; } while(ManterMenu) { //Leitura dos botoes e limitacao de range if((!digitalRead(up) == HIGH) || (!digitalRead(select) == HIGH)) { ManterMenu = false; delay(AtrasoBotoes); } if(!digitalRead(mais) == HIGH) { ValorAtualizado++; delay(AtrasoBotoes); } if(!digitalRead(menos) == HIGH) { ValorAtualizado--; delay(AtrasoBotoes); } if(ValorAtualizado > Limite) { ValorAtualizado = Limite; } else if (ValorAtualizado < 0) { ValorAtualizado = 0; } if(OpcaoSelecionada <= 4) { lcd.setCursor(1, 1); lcd.write('>'); if(ValorAtualizado < 10) { lcd.write('0'); } lcd.print(ValorAtualizado); delay(AtualizacaoDisplay); } else { lcd.setCursor(1, 1); lcd.write('>'); switch(ValorAtualizado) { case 0: lcd.print("DOMINGO"); case 1: lcd.print("SEGUNDA"); case 2: lcd.print("TERCA"); case 3: lcd.print("QUARTA"); case 4: lcd.print("QUINTA"); case 5: lcd.print("SEXTA"); case 6: lcd.print("SABADO"); } } } return ValorAtualizado; } bool SalvarData(byte minuto, byte hora, byte dia, byte mes, byte ano, byte diasemana) { bool DesejaSalvar = true; lcd.clear(); lcd.setCursor(2, 0); lcd.print("Salvar Data?"); //Laço necessário para manter o menu while(true) { if((!digitalRead(mais) == HIGH) || (!digitalRead(menos) == HIGH)){ DesejaSalvar = !DesejaSalvar; delay(AtrasoBotoes); } if(!digitalRead(select) == HIGH) { break; } if(DesejaSalvar) { lcd.setCursor(2, 1); lcd.print(">SIM"); lcd.setCursor(9, 1); lcd.print(" NAO"); } else { lcd.setCursor(2, 1); lcd.print(" SIM"); lcd.setCursor(9, 1); lcd.print(">NAO"); } } if(DesejaSalvar) { //Função para salvar vem aki AtualizaRTC(minuto, hora, dia, mes, ano, diasemana); salvoComSucesso(); } return; } //=================================== Inicio do Programa ========================================== void setup() { Wire.begin(); //Botões de interação pinMode(up, INPUT_PULLUP); pinMode(mais, INPUT_PULLUP); pinMode(menos, INPUT_PULLUP); pinMode(select, INPUT_PULLUP); //Pinos ADC para as baterias pinMode(Bateria_1, INPUT); pinMode(Bateria_2, INPUT); pinMode(Bateria_3, INPUT); pinMode(Bateria_4, INPUT); //Criação de caracteres especiais lcd.createChar(1, SelecionadorOpcao); lcd.createChar(2, C_Cedilhado); lcd.createChar(3, O_Til); lcd.createChar(4, A_Til); lcd.createChar(5 , A_Agudo); //Mensagem inicial display lcd.clear(); lcd.begin(16, 2); //Boas vindas lcd.setCursor(2, 0); lcd.print("Iniciando"); for(byte i = 0; i < 3; i++) { lcd.write('.'); delay(1500); } if(EEPROM.read(EnderecoTempoSalvar) == 0) { TempoParaSalvar = 1; EEPROM.update(EnderecoTempoSalvar, 1); } TempoParaSalvar = EEPROM.read(EnderecoTempoSalvar); /* while(!SD.begin(SelecaoChip)) { erroAbrirCartao(); } lcd.clear(); lcd.setCursor(3, 0); lcd.print("Cartao SD "); lcd.setCursor(3, 1); lcd.print("encontrado."); delay(2000); */ } void loop() { menuPrincipal(); delay(1); }
#include <iostream> using namespace std; int main() { int myArray[21] = { 41, 58, 97, 53, 98, 29, 23, 19, 10, 85, 3, 90, 81, 16, 47, 78, 37, 59, 60, 43 }; bool sorted = false; // Determines if array has been sorted, currently set to false // As long as array is not sorted, sort the array while (!sorted) { sorted = true; // Set sorted to true. If no change is required, will remain at true. Otherwise, it will be set to false // Iterate through array. We subtract by 1 to prevent index out of bounds error for (int i = 0; i < size(myArray) - 1; i++) { // If the current value is greater than next value, swap value. This is for least->greatest implementation. Flip inequality for greatest->least implementation if (myArray[i] > myArray[i + 1]) { int temp = myArray[i]; myArray[i] = myArray[i + 1]; myArray[i + 1] = temp; sorted = false; } } } for (int i = 0; i < size(myArray); i++) { cout << myArray[i] << endl; } return 0; }
// type define // 형을 정의한다 #include <stdio.h> int main(){ typedef int Int32; Int32 n = 20; printf("%d \n", n); }
#include "customQGraphicsView.h" CustomQGraphicsView::CustomQGraphicsView(QWidget *parent) : QGraphicsView(parent) { depressed = false; last_x = -1; last_y = -1; scene = new QGraphicsScene(); this->setScene(scene); }
#include <iostream> #include <unistd.h> #include <GLFW/glfw3.h> #include "Loop.h" #include "Engine.h" #include "Clock.h" #include "../Display/Window.h" Loop::Loop(Engine* engine) : running(false), render(false), sleepTime(0), fps(0.0f), lastTime(0.0), startTime(0.0), frameTime(1.0 / 60.0f), frameCounter(0.0), unprocessedTime(0), frames(0), passedTime(0.0), fpsIndex(0), fpsSum(0.0f) { this->engine = engine; this->clock = new Clock(); this->profiler = new Profiler(this->clock); this->profiler->addTimer("frame"); this->profiler->addTimer("update"); this->profiler->addTimer("render"); this->profiler->addTimer("sleep"); this->updateCallback = nullptr; this->renderCallback = nullptr; } void Loop::start() { if (this->running) return; this->running = true; this->lastTime = this->clock->getTime(); this->frameCounter = 0; this->unprocessedTime = 0; this->frames = 0; while (this->running) { this->render = false; this->startTime = this->clock->getTime(); this->passedTime = this->startTime - this->lastTime; this->lastTime = this->startTime; this->unprocessedTime += this->passedTime; this->frameCounter += this->passedTime; if (this->frameCounter >= 0.1f) { this->fps = computeAverageFps(1.0f / (float)this->passedTime); this->frames = 0; this->frameCounter = 0; } this->profiler->startTimer("frame"); if (this->unprocessedTime > this->frameTime) { this->profiler->startTimer("update"); if (this->updateCallback != nullptr) this->updateCallback(this, this->engine); this->profiler->stopTimer("update"); this->render = true; this->unprocessedTime -= this->passedTime; } this->profiler->startTimer("render"); if (this->renderCallback != nullptr) this->renderCallback(this, this->engine); this->profiler->stopTimer("render"); this->frames++; this->profiler->startTimer("sleep"); usleep(this->sleepTime); this->profiler->stopTimer("sleep"); this->profiler->stopTimer("frame"); } } float Loop::computeAverageFps(float fps) { this->fpsSum -= this->fpsList[this->fpsIndex]; this->fpsSum += fps; this->fpsList[this->fpsIndex] = fps; this->fpsIndex++; if (this->fpsIndex == MAX_SAMPLES) this->fpsIndex = 0; return this->fpsSum / MAX_SAMPLES; } void Loop::stop() { this->running = false; } Loop::~Loop() { delete this->clock; delete this->profiler; }
#include<iostream> #include<string> using namespace std; int main(){ std::ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n,k,pre,len; string cur,str; cin>>n>>cur; cin.ignore(); while (n--) { getline(cin,str); if(str[0]!='/')str=cur+"/"+str; if(str.size()==0)str=cur; while(true){ k = str.find("//"); if(k==string::npos)break; str = str.replace(k,2,"/"); }// 去除多余的"/" while(true){ k = str.find("/../"); if(k==string::npos)break; if(k==0)str.erase(k+1,3);//多余的部分 else { pre = str.rfind("/",k-1); //反向查找上一个目录 str.erase(pre,k-pre+3); // 删除上一个目录及../ } }// 去除../ while(true){ k = str.find("/./"); if(k==string::npos)break; str.erase(k+1,2); }// 去除./ len = str.size(); if(len>1&&str[len-1]=='/')str.erase(len-1,1); cout<<str<<endl; } }
#include "stdafx.h" #include "ShikoChu.h" #include "../../GameData.h" ShikoChu::ShikoChu() { SkinModelRender* sr = NewGO<SkinModelRender>(0, "smr"); sr->Init(L"Assets/modelData/si_bug.cmo"); //sr->SetScale(CVector3::One() * 20); sr->SetPosition(CVector3::Zero()); MonsterInitParam prm; prm.HP = 60; prm.MP = 30; prm.DefencePow = 10; prm.ExDefensePow = 5; prm.AttackPow = 10; prm.ExAttackPow = 300; prm.Speed = 50; prm.Radius = 50; prm.Height = 150; prm.ModelRender = sr; prm.NumAnimation = 0; init(prm); m_ID = enShikoChu; int cnt = 0; ActionID* ua = GameData::GetMonsterActions(m_ID, cnt); SetUseAction(ua, cnt); //tginit(10, 10, 10, 20, 70, sr, 0); }
#if !defined(FUTURE_FTDCMDAPI_H) #define FUTURE_FTDCMDAPI_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "FutureFtdcUserApiStruct.h" #if defined(ISLIB) && defined(WIN32) #ifdef LIB_MD_API_EXPORT #define MD_API_EXPORT __declspec(dllexport) #else #define MD_API_EXPORT __declspec(dllimport) #endif #else #define MD_API_EXPORT #endif class CFutureFtdcMdSpi { public: ///当客户端与交易后台建立起通信连接时(还未登录前),该方法被调用。 virtual void OnFrontConnected(){}; ///当客户端与交易后台通信连接断开时,该方法被调用。当发生这个情况后,API会自动重新连接,客户端可不做处理。 ///@param nReason 错误原因 /// 0x1001 网络读失败 /// 0x1002 网络写失败 /// 0x2001 接收心跳超时 /// 0x2002 发送心跳失败 /// 0x2003 收到错误报文 virtual void OnFrontDisconnected(int nReason){}; ///心跳超时警告。当长时间未收到报文时,该方法被调用。 ///@param nTimeLapse 距离上次接收报文的时间 virtual void OnHeartBeatWarning(int nTimeLapse){}; ///登录请求响应 virtual void OnRspUserLogin(CFutureFtdcRspUserLoginField *pRspUserLogin, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///登出请求响应 virtual void OnRspUserLogout(CFutureFtdcUserLogoutField *pUserLogout, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///错误应答 virtual void OnRspError(CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///订阅行情应答 virtual void OnRspSubMarketData(CFutureFtdcSpecificInstrumentField *pSpecificInstrument, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///取消订阅行情应答 virtual void OnRspUnSubMarketData(CFutureFtdcSpecificInstrumentField *pSpecificInstrument, CFutureFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {}; ///深度行情通知 virtual void OnRtnDepthMarketData(CFutureFtdcDepthMarketDataField *pDepthMarketData) {}; }; #ifndef WINDOWS #if __GNUC__ >= 4 #pragma GCC visibility push(default) #endif #endif class MD_API_EXPORT CFutureFtdcMdApi { public: ///创建MdApi ///@param pszFlowPath 存贮订阅信息文件的目录,默认为当前目录 ///@return 创建出的UserApi ///modify for udp marketdata ///nUdpMode, 0:use tcp only; 1:use udp unicast; 2:use udp broad cast static CFutureFtdcMdApi *CreateFtdcMdApi(const char *pszFlowPath = "", const int nUdpMode=0); ///删除接口对象本身 ///@remark 不再使用本接口对象时,调用该函数删除接口对象 virtual void Release() = 0; ///初始化 ///@remark 初始化运行环境,只有调用后,接口才开始工作 virtual void Init() = 0; ///等待接口线程结束运行 ///@return 线程退出代码 virtual int Join() = 0; ///获取当前交易日 ///@retrun 获取到的交易日 ///@remark 只有登录成功后,才能得到正确的交易日 virtual const char *GetTradingDay() = 0; ///注册前置机网络地址 ///@param pszFrontAddress:前置机网络地址。 ///@remark 网络地址的格式为:“protocol://ipaddress:port”,如:”tcp://127.0.0.1:17001”。 ///@remark “tcp”代表传输协议,“127.0.0.1”代表服务器地址。”17001”代表服务器端口号。 virtual void RegisterFront(char *pszFrontAddress, unsigned int priority = 0) = 0; ///注册回调接口 ///@param pSpi 派生自回调接口类的实例 virtual void RegisterSpi(CFutureFtdcMdSpi *pSpi) = 0; ///订阅行情。 ///@param ppInstrumentID 合约ID ///@param nCount 要订阅/退订行情的合约个数 ///@remark virtual int SubscribeMarketData(char *ppInstrumentID[], int nCount) = 0; ///退订行情。 ///@param ppInstrumentID 合约ID ///@param nCount 要订阅/退订行情的合约个数 ///@remark virtual int UnSubscribeMarketData(char *ppInstrumentID[], int nCount) = 0; ///用户登录请求 virtual int ReqUserLogin(CFutureFtdcReqUserLoginField *pReqUserLoginField, int nRequestID) = 0; ///登出请求 virtual int ReqUserLogout(CFutureFtdcUserLogoutField *pUserLogout, int nRequestID) = 0; protected: ~CFutureFtdcMdApi(){}; }; #ifndef WINDOWS #if __GNUC__ >= 4 #pragma GCC visibility pop #endif #endif #endif
#ifndef RANDOMNUMBERGENERATOR_H #define RANDOMNUMBERGENERATOR_H class RandomNumberGenerator { public: static int randomInt(int from, int tillIncl); static double randomDouble(double from, double tillIncl, int precision); private: RandomNumberGenerator(){}; static bool initiated; static void checkIfInitiated(); }; #endif // RANDOMNUMBERGENERATOR_H
#include "Plate.h" Plate::Plate() { } Plate::~Plate() { } void Plate::loadVals( PL_NUM _E1, PL_NUM _E2, PL_NUM _nu21, PL_NUM _rho, N_PRES _h, PL_NUM _sigma_x, N_PRES _a ) { E1 = _E1; E2 = _E2; nu21 = _nu21; rho = _rho; h = _h; a = _a; sigma_x = _sigma_x; sigma_x_mu = _sigma_x * 0.000001256l; }
#include "mbed.h" #include "adc128.h" #include "term.h" #include "uart.h" const int brakeIOX7Addr = 0x20; DigitalOut myled(LED1); I2C i2cbus(I2C_SDA, I2C_SCL); RawSerial pc(USBTX, USBRX); int initIOX(char *name, const int addr); int blink(int ledVal); int main() { int ledVal = 0; int ticks = 0; wait(0.1); initADC("Rails and Temps", railADC7Addr); initADC("Pressures", presADC7Addr); chanInit(); if (initIOX("Braking Solenoids", brakeIOX7Addr)) pc.printf("IOX Failed: Did you check the reset pin?\n\r"); while(1) { runDebugTerminal(); ledVal = blink(ledVal); wait(0.1); } } int initIOX(char *name, const int iox7BitAddr) { const int iox8BitAddr = iox7BitAddr << 1; char cmd[2]; cmd[0] = 0x05; cmd[1] = 0x00; if (i2cbus.write(iox8BitAddr, cmd, 2)) { return 1; } // Doesn't prove much, just that read/write didn't fail pc.printf("IOX for %s at address %#x Found: manufacturer ID = %#x\n", name, iox7BitAddr, cmd[0]); /* Should be: 0x01 */ return 0; } int blink(int ledVal) { myled = ledVal; return !ledVal; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef M2_SUPPORT #include "AskMaxMessagesDownloadDialog.h" #include "adjunct/quick/Application.h" #include "modules/widgets/OpNumberEdit.h" #include "modules/widgets/OpMultiEdit.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" AskMaxMessagesDownloadDialog::AskMaxMessagesDownloadDialog(int& current_max_messages, BOOL& dont_ask_again, int available_messages, const OpStringC8& group, BOOL& ok) : m_max_messages(current_max_messages) , m_available_messages(available_messages) , m_ask_again(dont_ask_again) , m_ok(ok) { OpStatus::Ignore(m_group.Set(group)); } void AskMaxMessagesDownloadDialog::OnInit() { OpString format, question, max_messages; RETURN_VOID_IF_ERROR(g_languageManager->GetString(Str::D_NEWS_HOW_MANY_NEW_MESSAGES, format)); question.AppendFormat(format.CStr(), m_available_messages, m_group.CStr()); OpMultilineEdit* question_edit = (OpMultilineEdit*)GetWidgetByName("Question"); if (question_edit) { question_edit->SetLabelMode(); question_edit->SetText(question.CStr()); } OpNumberEdit* limited_messages = (OpNumberEdit*)GetWidgetByName("NumberEdit_messages"); if (limited_messages) { if (m_max_messages != 0) { max_messages.AppendFormat(UNI_L("%d"), min(m_max_messages, m_available_messages)); limited_messages->SetText(max_messages.CStr()); } else { limited_messages->SetText(UNI_L("250")); } limited_messages->SetMinValue(0); limited_messages->SetMaxValue(m_available_messages); } SetWidgetValue("Radio_limited_messages", m_max_messages != 0); SetWidgetValue("Radio_all_messages", m_max_messages == 0); } UINT32 AskMaxMessagesDownloadDialog::OnOk() { OpNumberEdit* limited_messages = (OpNumberEdit*)GetWidgetByName("NumberEdit_messages"); if (limited_messages) limited_messages->GetIntValue(m_max_messages); if (m_max_messages < 0) m_max_messages = 0; BOOL fetch_all = GetWidgetValue("Radio_all_messages"); if (fetch_all) m_max_messages = 0; m_ask_again = !GetWidgetValue("Dont_ask_checkbox"); m_ok = TRUE; return 0; } void AskMaxMessagesDownloadDialog::OnCancel() { m_ok = FALSE; } #endif // M2_SUPPORT
// Created on: 1992-08-26 // Created by: Remi GILET // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _gce_MakeParab2d_HeaderFile #define _gce_MakeParab2d_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <gp_Parab2d.hxx> #include <gce_Root.hxx> #include <Standard_Boolean.hxx> class gp_Ax2d; class gp_Ax22d; class gp_Pnt2d; //! This class implements the following algorithms used to //! create Parab2d from gp. //! Defines an infinite parabola. //! An axis placement one axis defines the local cartesian //! coordinate system ("XAxis") of the parabola. //! The vertex of the parabola is the "Location" point of the //! local coordinate system of the parabola. //! The "XAxis" of the parabola is its axis of symmetry. //! The "XAxis" is oriented from the vertex of the parabola to the //! Focus of the parabola. //! The "YAxis" is parallel to the directrix of the parabola and //! its "Location" point is the vertex of the parabola. //! The equation of the parabola in the local coordinate system is //! Y**2 = (2*P) * X //! P is the distance between the focus and the directrix of the //! parabola called Parameter). //! The focal length F = P/2 is the distance between the vertex //! and the focus of the parabola. //! //! * Create a Parab2d from one apex and the center. //! * Create a Parab2d with the directrix and the focus point. //! * Create a Parab2d with its vertex point and its axis //! of symmetry and its focus length. class gce_MakeParab2d : public gce_Root { public: DEFINE_STANDARD_ALLOC //! Creates a parabola with its axis of symmetry ("MirrorAxis") //! and its focal length. //! Warnings : It is possible to have Focal = 0. //! The status is "NullFocalLength" Raised if Focal < 0.0 Standard_EXPORT gce_MakeParab2d(const gp_Ax2d& MirrorAxis, const Standard_Real Focal, const Standard_Boolean Sense = Standard_True); //! Creates a parabola with its local coordinate system <A> //! and its focal length. //! Warnings : It is possible to have Focal = 0. //! The status is "NullFocalLength" Raised if Focal < 0.0 Standard_EXPORT gce_MakeParab2d(const gp_Ax22d& A, const Standard_Real Focal); //! Creates a parabola with the directrix and the focus point. //! The sense of parametrization is given by Sense. Standard_EXPORT gce_MakeParab2d(const gp_Ax2d& D, const gp_Pnt2d& F, const Standard_Boolean Sense = Standard_True); //! Make an Parab2d with S1 as the Focal point and Center //! as the apex of the parabola //! Warning //! The MakeParab2d class does not prevent the //! construction of a parabola with a null focal distance. //! If an error occurs (that is, when IsDone returns //! false), the Status function returns: //! - gce_NullFocusLength if Focal is less than 0.0, or //! - gce_NullAxis if S1 and Center are coincident. Standard_EXPORT gce_MakeParab2d(const gp_Pnt2d& S1, const gp_Pnt2d& Center, const Standard_Boolean Sense = Standard_True); //! Returns the constructed parabola. //! Exceptions StdFail_NotDone if no parabola is constructed. Standard_EXPORT const gp_Parab2d& Value() const; Standard_EXPORT const gp_Parab2d& Operator() const; Standard_EXPORT operator gp_Parab2d() const; protected: private: gp_Parab2d TheParab2d; }; #endif // _gce_MakeParab2d_HeaderFile
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> #include <map> using namespace std; typedef long long ll; #define INF 10e10 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define MAX 100 #define MOD 1000000007 #define pb push_back /* add vars here */ ll n; /* add your algorithm here */ int main() { cin >> n; vector<string> v; string s; bool flag = false; rep(i,n) { cin >> s; v.pb(s); } rep(i,n) { rep(j,n) { if (i == j) continue; if (v[i] == v[j]) { cout << "No" << endl; return 0; } } } for (int i = 1; i < n; ++i) { string a = v[i-1], b = v[i]; if (a.back() != b[0]) { cout << "No" << endl; return 0; } } cout << "Yes" << endl; }
#include "Connector.h" Connector::Connector(Statement* Src, Statement* Dst) //When a connector is created, it must have a source statement and a destination statement //There are no free connectors in the folwchart { SrcStat = Src; DstStat = Dst; ConnType=0; Selected=false; } void Connector::SetSelected(bool s) { Selected = s; } bool Connector::IsSelected() const { return Selected; } void Connector::setSrcStat(Statement *Src) { SrcStat = Src; } Statement* Connector::getSrcStat() { return SrcStat; } void Connector::setDstStat(Statement *Dst) { DstStat = Dst; } Statement* Connector::getDstStat() { return DstStat; } void Connector::setSrcID(int ID) { SrcID=ID; } int Connector::getSrsID() { return SrcID; } void Connector::setDstID(int ID) { DstID=ID; } int Connector::getDstID() { return DstID; } void Connector::setStartPoint(Point P) { Start = P; } Point Connector::getStartPoint() { return Start; } void Connector::setEndPoint(Point P) { End = P; } Point Connector::getEndPoint() { return End; } void Connector::setConnType(int C) { ConnType=C; } int Connector::getConnType() { return ConnType; } void Connector::Draw(Output* pOut) const { ///TODO: Call output to draw a connector here pOut->DrawConnector(Start,End,Selected); } bool Connector::IsOnConnect(Point P) { if(End.y>Start.y) { if(P.x==Start.x&&P.y>=Start.y&&P.y<=Start.y+10) return true; if(P.x>=Start.x&&P.x<=End.x&&P.y==Start.y+10) return true; if(P.x>=End.x&&P.x<=Start.x&&P.y==Start.y+10) return true; if(P.x==End.x&&P.y>=Start.y+10&&P.y<=End.y) return true; if(P.x>=End.x&&P.x<=End.x+10&&P.y<=End.y&&P.y>=End.y-10) return true; if(P.x<=End.x&&P.x>=End.x-10&&P.y<=End.y&&P.y>=End.y-10) return true; return false; } else if(End.y<Start.y) { if(End.x>Start.x) { if(P.x==Start.x&&P.y>=Start.y&&P.y<=Start.y+10) return true; if(P.x<=Start.x&&P.x>=Start.x-150&&P.y==Start.y+10) return true; if(P.x==Start.x-150&&P.y<=Start.y+10&&P.y>=End.y) return true; if(P.x>=Start.x-150&&P.x<=End.x&&P.y==End.y) return true; if(P.x<=End.x&&P.x>=End.x-10&&P.y>=End.y&&P.y<=End.y+10) return true; if(P.x<=End.x&&P.x>=End.x-10&&P.y<=End.y&&P.y>=End.y-10) return true; return false; } else { if(P.x==Start.x&&P.y>=Start.y&&P.y<=Start.y+10) return true; if(P.x>=Start.x&&P.x<=Start.x+150&&P.y==Start.y+10) return true; if(P.x==Start.x+150&&P.y<=Start.y+10&&P.y>=End.y) return true; if(P.x<=Start.x+150&&P.x>=End.x&&P.y==End.y) return true; if(P.x>=End.x&&P.x<=End.x+10&&P.y>=End.y&&P.y<=End.y+10) return true; if(P.x>=End.x&&P.x<=End.x+10&&P.y<=End.y&&P.y>=End.y-10) return true; return false; } } else { if(End.x>Start.x) { if(P.x>=Start.x&&P.x<=End.x&&P.y==Start.y) return true; if(P.x<=End.x&&P.x>=End.x-10&&P.y>=End.y&&P.y<=End.y+10) return true; if(P.x<=End.x&&P.x>=End.x-10&&P.y<=End.y&&P.y>=End.y-10) return true; return false; } else { if(P.x<=Start.x&&P.x>=End.x&&P.y==Start.y) return true; if(P.x>=End.x&&P.x<=End.x+10&&P.y>=End.y&&P.y<=End.y+10) return true; if(P.x>=End.x&&P.x<=End.x+10&&P.y<=End.y&&P.y>=End.y-10) return true; return false; } } } void Connector::Save(ofstream &Outfile) { Outfile<<SrcID<<"\t"<<DstID<<"\t"<<ConnType<<endl; } void Connector::Load(ifstream &Infile) { Infile>>SrcID>>DstID>>ConnType; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef OPPAINTER_H #define OPPAINTER_H #include "modules/pi/OpBitmap.h" class OpFont; /** @short Paint context for a paint device. * * A paint device may be an OpView (for screen), an * OpPrinterController (for printer), or an OpBitmap (graphical * bitmap). * * A painter is a temporary object used for painting on an OpView, * OpPrinterController or OpBitmap. It is provided by calling * OpView::GetPainter(), OpPrinterController::GetPainter() or * OpBitmap::GetPainter() to start a paint job (e.g. handling of a * paint event). To end a paint job, call OpView::ReleasePainter(), * OpBitmap::ReleasePainter(), or delete the OpPrinterController. * Ending a paint job means flushing the double-buffer (if any) to the * screen, printer or graphical bitmap. * * An implementation is free to keep and provide the same OpPainter * object across several subsequent paint jobs, as long as the object * that provides it always returns an OpPainter in its initial * state. No paint context data is to be re-used from a previous paint * job. * * The painter knows the current color to use when drawing text, * lines, rectangles, etc., the current clip rectangle, the current * font, etc. The initial color and font are undefined, and MUST be * set before attempting to perform an operation that depends on them * being set to something reasonable. The initial clip rectangle of a * painter covers the whole paint device area, unless otherwise * explicitly stated for the method that returns it. * * Many methods in OpPainter take coordinate arguments. They are * always relative to the upper left corner of their paint device, * regardless of e.g. the current clip rectangle. If the paint device * is an OpView, the coordinates are thus relative to the upper left * corner of the rendering viewport, in screen coordinates. * * GetDPI is removed, and one should use g_op_screen_info to get * this information */ class OpPainter { public: enum RenderingHint { Quality, Speed }; virtual ~OpPainter(){}; /** Set the current color. * * There is no distinction between foreground and background * color. * * @param red Red component, 0-255, 255 is max intensity * @param green Green component, 0-255, 255 is max intensity * @param blue Blue component, 0-255, 255 is max intensity * @param alpha Alpha component, 0-255, 0 is fully transparent, * 255 is fully opaque */ virtual void SetColor(UINT8 red, UINT8 green, UINT8 blue, UINT8 alpha = 255) = 0; /** * Sets the pre-alpha value for the painter. * * Any subsequent call to GetPreAlpha() shall return the specified * value. All painting operations shall pre-multiply any alpha * value(s) used in all drawing operations with the specified * pre-set alpha value. * @note The default pre-alpha value is 255 (fully opaque). * * @param alpha is the pre-alpha value to set. 255 is fully opaque, * 0 is fully transparent. */ virtual void SetPreAlpha(UINT8 alpha) = 0; /** * Returns the "global" pre-alpha value for the painter. * * @note This method should return the value of the most recent * SetPreAlpha() call. The default value, i.e. if SetPreAlpha() * was not called previously, shall be 255 (fully opaque). */ virtual UINT8 GetPreAlpha() = 0; /** Set the current color. * * There is no distinction between foreground and background * color. * * @param col The new color. The Format is 0xAABBGGRR. */ inline void SetColor(UINT32 col) { SetColor(col & 0xff, (col >> 8) & 0xff, (col >> 16) & 0xff, col >> 24); } /** Set the current font. * * @param font The font */ virtual void SetFont(OpFont *font) = 0; /** Constrain the currently active clip rectangle. * * The parameter-supplied rectangle will be put an a clipping * stack. The currently active clip rectangle will be intersected * with this new rectangle, so that all subsequent draw operations * will be confined to this intersected rectangle. * * To remove the clip rectangle that is at the top of the stack * again, call SetClipRect(). * * @param rect The clipping rectangle to intersect with the * current one, relative to the top left corner of the paint * device. */ virtual OP_STATUS SetClipRect(const OpRect &rect) = 0; /** Remove the topmost clip rectangle off the stack. * * The active clip rectangle after this operation becomes the same * as it was before the previous call to SetClipRect(). */ virtual void RemoveClipRect() = 0; /** Get the clip rectangle at the top of the stack. * * @param rect (output) Set to the clip rectangle on the top of * the stack. Note that the rectangle returned is not intersected * with previous rectangles on the stack (as opposed to what the * "active" clip rectangle used for drawing operations is -- see * SetClipRect() for more information on that). */ virtual void GetClipRect(OpRect* rect) = 0; /** Draw the outline of a rectangle. * * @param rect The rect where the rectangle should be drawn * @param width The width of the border in pixels */ virtual void DrawRect(const OpRect &rect, UINT32 width = 1) = 0; /** Draw a solid rectangle. * * @param rect The rect where the rectangle should be drawn * @see ClearRect() */ virtual void FillRect(const OpRect &rect) = 0; /** Clear the rect with the current color. * * @param rect The rect where the rectangle should be drawn * * @note The difference between FillRect() and ClearRect() is, * that FillRect() should blend the specified rectangle with the * current color (if it has an alpha value), while ClearRect() * should clear the rectangle with current color. * @see FillRect() */ virtual void ClearRect(const OpRect &rect) = 0; /** Draw the outline of an ellipse. * * @param rect The rect where the ellipse should be drawn * @param width The width of the border in pixels */ virtual void DrawEllipse(const OpRect &rect, UINT32 width = 1) = 0; /** Draw a solid ellipse. * * @param rect The rect where the ellipse should be drawn */ virtual void FillEllipse(const OpRect &rect) = 0; /** Draw the outline of a polygon. * * This method closes polygons' path with a final segment from * points[count-1] to points[0]. * * @param points An array of polygon points * @param count Number of points in point_array * @param width Width of the border in pixels */ virtual void DrawPolygon(const OpPoint* points, int count, UINT32 width = 1) = 0; /** Draw a horizontal or vertical line. * * @param from The start position * @param length The length in pixels * @param horizontal Direction - if TRUE, the line will be * horizontal, otherwise it will be vertical * @param width The width in pixels. The width of the line is * spread to the right of a vertical line, and under a horizontal * line. */ virtual void DrawLine(const OpPoint &from, UINT32 length, BOOL horizontal, UINT32 width = 1) = 0; /** Draw a line. * * @param from The start position * @param to The end position * @param width The width in pixels */ virtual void DrawLine(const OpPoint &from, const OpPoint &to, UINT32 width = 1) = 0; /** Draw a text string. * * @param pos The upper left corner, where the text should be drawn * @param text The text - does not have to be NUL terminated * @param len The number of characters to draw * @param extra_char_spacing Extra space to insert between characters (pixels) * @param word_width If set (i.e. if this is a positive number), it * specifies the width of the string, in pixels. This overrides whatever * the system's font engine would calculate the width to be. This parameter * is typically set when Opera has calculated the width of a string in one * zoom level, and then expects the text to scale linearly in other zoom * levels. There are different ways to implement this. One way may be to * adjust the inter-character spacing to make it fit. Another way could be * to also scale the characters. */ virtual void DrawString(const OpPoint &pos, const uni_char* text, UINT32 len, INT32 extra_char_spacing = 0, short word_width = -1) = 0; /** Invert the pixels covered by a solid rectangle. * * What's meant by "invert" is implementation-dependant. * True-color systems may invert the color of each pixel. Indexed * color (palette) based systems may invert the color index on * each pixel instead. Regardless of implementation, inverting the * same rectangle twice must result in the same pixels as before * the first inversion. * * @param rect The rect to be inverted */ virtual void InvertRect(const OpRect &rect) = 0; /** Inverts the pixels covered by a rectangle border. * * What's meant by "invert" is implementation-dependant. * True-color systems may invert the color of each pixel. Indexed * color (palette) based systems may invert the color index on * each pixel instead. Regardless of implementation, inverting the * same rectangle twice must result in the same pixels as before * the first inversion. * * @param rect The rectangle to be inverted * @param border Width of the border, in pixels; will grow towards * the center of the rectangle. */ virtual void InvertBorderRect(const OpRect &rect, int border) = 0; /** Invert the pixels covered by an ellipse border. * * What's meant by "invert" is implementation-dependant. * True-color systems may invert the color of each pixel. Indexed * color (palette) based systems may invert the color index on * each pixel instead. Regardless of implementation, inverting the * same rectangle twice must result in the same pixels as before * the first inversion. * * @param rect The rectangle defining the ellipse whose border is * to be inverted * @param border Width of the border, in pixels; will grow towards * the center of the ellipse. */ virtual void InvertBorderEllipse(const OpRect &rect, int border) = 0; /** Invert the pixels covered by a polygon border. * * What's meant by "invert" is implementation-dependant. * True-color systems may invert the color of each pixel. Indexed * color (palette) based systems may invert the color index on * each pixel instead. Regardless of implementation, inverting the * same rectangle twice must result in the same pixels as before * the first inversion. * * This method closes polygons' path with a final segment from * points[count-1] to points[0]. * * @param points An array of polygon points * @param count Number of points in point_array * @param border Width of the border */ virtual void InvertBorderPolygon(const OpPoint* points, int count, int border) = 0; #if 0 // Possible replacement for all DrawBitmap*() methods: // Spec not complete. /** Flags that specify allowed operations in DrawBitmap(). */ enum BitmapDrawFlags { /** Draw the image with any inherent transparency (1-bit alpha) information. */ BITMAP_DRAW_INTRINSIC_TRANSPARENT = 0x01, /** Draw the image with any inherent alpha translucency information. */ BITMAP_DRAW_INTRINSIC_ALPHA = 0x02 }; /** Draw an image (or image fragment) * * @param bitmap The image to draw * @param source Source rectangle; The x/y coordinates specify from where * in the image to start drawing. It may also specify scaling: if the * width/height of the rectangle differs from the actual image size, the * image is to be scaled when displayed, and the coordinates specified are * the coordinates after scaling. * @param dest Destination rectangle; The x/y coordinates are relative to * the upper left corner of the paint device, and width and height are the * number of pixels to draw in either dimension. The sum of number of * pixels may exceed the actual number of pixels in the (potentially * scaled) image, in which case the image is to be tiled. Tiling must only * be requested if Supports(SUPPORTS_TILING) returns TRUE. * @param flags BitmapDrawFlags values ORed together * @param opacity Overall opacity. May coexist with BITMAP_INTRINSIC_ALPHA * set in the 'flags' parameter. * @return OK, ERR or ERR_NO_MEMORY. */ virtual OP_STATUS DrawBitmap(OpBitmap* bitmap, const OpRect& source, const OpRect& dest, int flags, int opacity = 255) = 0; #endif // 0 /** Draw an image (or image fragment). * * @param bitmap The image to draw * @param source Source rectangle; the fragment to draw, or { 0, * 0, bitmap->Width(), bitmap->Height() } for the whole image. * @param p Destination coordinate for upper left pixel to draw. */ virtual void DrawBitmapClipped(const OpBitmap* bitmap, const OpRect &source, OpPoint p) = 0; // [OPTIONAL DrawBitmap... FUNCTIONS] // Should be used only if they are supported. Otherwise they will be done internal. If you get an OP_ASSERT here, then you need to either change your Supports method or implement the asserted method. /** Draw an image (or image fragment) with inherent transparency. * * This is an optional method. It should be called only if it is * supported. Query for support by calling Supports(SUPPORTS_TRANSPARENT). * * @param bitmap The image to draw * @param source Source rectangle; the fragment to draw, or { 0, * 0, bitmap->Width(), bitmap->Height() } for the whole image. * @param p Destination coordinate for upper left pixel to draw. */ virtual void DrawBitmapClippedTransparent(const OpBitmap* bitmap, const OpRect& source, OpPoint p) { OP_ASSERT(FALSE); }; /** Draw an image (or image fragment) with inherent alpha (translucency). * * This is an optional method. It should be called only if it is * supported. Query for support by calling Supports(SUPPORTS_ALPHA). * * @param bitmap The image to draw * @param source Source rectangle; the fragment to draw, or { 0, * 0, bitmap->Width(), bitmap->Height() } for the whole image. * @param p Destination coordinate for upper left pixel to draw. */ virtual void DrawBitmapClippedAlpha(const OpBitmap* bitmap, const OpRect& source, OpPoint p) { OP_ASSERT(FALSE); }; /** Draw an image (or image fragment) with fixed opacity. * * All pixels in the bitmap should be drawn using the given * opacity. * * An alternative to this function is to implement * BeginOpacity/EndOpacity. Return TRUE if supported and * successful. * * @param bitmap The image to draw * @param source Source rectangle; the fragment to draw, or { 0, * 0, bitmap->Width(), bitmap->Height() } for the whole image. * @param p Destination coordinate for upper left pixel to draw. * @param opacity The opacity to use for all pixels; the value can * be between 0 and 254. 255 (fully opaque) should not happen. */ virtual BOOL DrawBitmapClippedOpacity(const OpBitmap* bitmap, const OpRect &source, OpPoint p, int opacity) { return FALSE; } /** Scaled and draw an image (or image fragment). * * @param bitmap The image to draw * @param source Source rectangle; the fragment to draw, or { 0, * 0, bitmap->Width(), bitmap->Height() } for the whole image. * @param dest Destination rectangle. The X and Y coordinates * specify the upper left pixel to draw. Width and height specify * scaling. They are relative to source.width and source.height, * respectively, in such a way that horizontal scale factor is * dest.width divided by source.width, and vertical scale factor * is dest.height divided by source.height. */ virtual void DrawBitmapScaled(const OpBitmap* bitmap, const OpRect& source, const OpRect& dest) { OP_ASSERT(FALSE); }; /** Scale and draw an image (or image fragment) with inherent transparency. * * This is an optional method. It should be called only if it is * supported. Query for support by calling Supports(SUPPORTS_TRANSPARENT). * * @param bitmap The image to draw * @param source Source rectangle; the fragment to draw, or { 0, * 0, bitmap->Width(), bitmap->Height() } for the whole image. * @param dest Destination rectangle. The X and Y coordinates * specify the upper left pixel to draw. Width and height specify * scaling. They are relative to source.width and source.height, * respectively, in such a way that horizontal scale factor is * dest.width divided by source.width, and vertical scale factor * is dest.height divided by source.height. */ virtual void DrawBitmapScaledTransparent(const OpBitmap* bitmap, const OpRect& source, const OpRect& dest) { OP_ASSERT(FALSE); }; /** Scale and draw an image (or image fragment) with inherent alpha (translucency). * * This is an optional method. It should be called only if it is * supported. Query for support by calling Supports(SUPPORTS_ALPHA). * * @param bitmap The image to draw * @param source Source rectangle; the fragment to draw, or { 0, * 0, bitmap->Width(), bitmap->Height() } for the whole image. * @param dest Destination rectangle. The X and Y coordinates * specify the upper left pixel to draw. Width and height specify * scaling. They are relative to source.width and source.height, * respectively, in such a way that horizontal scale factor is * dest.width divided by source.width, and vertical scale factor * is dest.height divided by source.height. */ virtual void DrawBitmapScaledAlpha(const OpBitmap* bitmap, const OpRect& source, const OpRect& dest) { OP_ASSERT(FALSE); }; /** Draw a tiled image, with inherent alpha and transparency if present. * * This is an optional method. It should be called only if it is * supported. Query for support by calling Supports(SUPPORTS_TILING). * * @param bitmap The image to draw * @param offset Start offset into bitmap for tiling. The pixel at * offset.x,offset.y in bitmap will be drawn at dest.x, dest.y * @param dest Destination rectangle dest.x,dest.y specify the destination * of the upper left pixel to draw. dest.width specifies how many pixels to * use from bitmap horizontally, and dest.height specifies how many pixels * to use from bitmap vertically. * @param scale scale percentage (100 means no scaling). */ virtual OP_STATUS DrawBitmapTiled(const OpBitmap* bitmap, const OpPoint& offset, const OpRect& dest, INT32 scale) { OP_ASSERT(FALSE); return OpStatus::ERR; }; /** Scale and draw a tiled image, with inherent alpha and transparency if present. * * This is an optional method. It should be called only if it is * supported. Query for support by calling Supports(SUPPORTS_TILING). * * @param bitmap Bitmap to be drawn * @param offset Scaled offset inside the scaled bitmap of where to start tiling * @param dest Destination rectangle, where the tiled bitmap should be drawn * @param scale The scale of the image * @param bitmapWidth The width of the bitmap pane (after scaling) * @param bitmapHeight The height of the bitmap pane (after scaling) * bitmapWidth, bitmapHeight are not redundant informations, becasue of rounding issues, use them rather than scale */ virtual OP_STATUS DrawBitmapTiled(const OpBitmap* bitmap, const OpPoint& offset, const OpRect& dest, INT32 scale, UINT32 bitmapWidth, UINT32 bitmapHeight) { OP_ASSERT(FALSE); return OpStatus::ERR; } /** Create and return bitmap of an area on a paint device. * * Read pixels from the paint device (screen, printer, bitmap) and * create a new OpBitmap of them. May be used by core to do * alpha-blending internally, for example. * * @param rect rectangle to create a bitmap from * @return NULL if not implemented, or on error, or the bitmap * otherwise. */ virtual OpBitmap* CreateBitmapFromBackground(const OpRect& rect) = 0; /** Can the painter provide an off-screen OpBitmap that gives * access to the paint area? * * @return TRUE means that GetOffscreenBitmap() can be called. */ virtual BOOL IsUsingOffscreenbitmap() { return FALSE; }; /** Returns an off-screen bitmap that gives access to the paint area. * * This may be a portion of the paint device area, not necessarily * the whole thing. */ virtual OpBitmap* GetOffscreenBitmap() { return NULL; }; /** Get the position of the bitmap returned from GetOffscreenBitmap(). * * @param rect (output) The coordinates set will be relative to * the upper left corner of the paint device. The width and height * will be the same as the width and height of the OpBitmap * returned from GetOffscreenBitmap(). */ virtual void GetOffscreenBitmapRect(OpRect* rect) { (void)rect; } inline void DrawBitmap (OpBitmap* bitmap, OpPoint p) { DrawBitmapClipped(bitmap, OpRect(0, 0, bitmap->Width(), bitmap->Height()), p); } inline void DrawBitmapTransparent (OpBitmap* bitmap, OpPoint p) { DrawBitmapClippedTransparent(bitmap, OpRect(0, 0, bitmap->Width(), bitmap->Height()), p); } inline void DrawBitmapAlpha (OpBitmap* bitmap, OpPoint p) { DrawBitmapClippedAlpha(bitmap, OpRect(0, 0, bitmap->Width(), bitmap->Height()), p); } /** Optional features enum. */ enum SUPPORTS { /** Can get an area from the screen, i.e. is CreateBitmapFromBackground() supported? */ SUPPORTS_GETSCREEN, /** Is display of images with transparent (1-bit alpha) pixels supported? */ SUPPORTS_TRANSPARENT, /** Is alpha-blending of images supported? */ SUPPORTS_ALPHA, /** Do all other paint operations than displaying images (which is * covered by SUPPORTS_ALPHA) support the alpha component specified * with SetColor()? */ SUPPORTS_ALPHA_COLOR, /** Is bitmap tiling supported? */ SUPPORTS_TILING, /** Is this a platform specific painter (supports platform specific features)? */ SUPPORTS_PLATFORM }; /** Query the platform about optional features. * * @param supports The feature to check for * * @return TRUE if the feature is supported, FALSE otherwise */ virtual BOOL Supports(SUPPORTS supports) { (void)supports; return FALSE; }; /** Initiate an opacity layer, start an opacity operation * * All painting between BeginOpacity() and EndOpacity() should be * done using the specified opacity. The opacity value can be * 0-254. 255 (fully opaque) will be handled by core, and this * method will never be used for handling of that. * * An alternative to this is to implement * OpPainter::DrawBitmapClippedOpacity(). If neither is * implemented, opacity will be done in core, but that may not be * in the most optimal solution for a platform. Note that nested * calls to BeginOpacity() is allowed. * * The platform-independent implementation in core creates a * buffer (OpBitmap) to which all painting between BeginOpacity() * and EndOpacity() is done. When an opacity operation is over, * this buffer is blitted to the screen (or backbuffer) with the * given opacity value. * * If the platform can perform this in a more efficient way, it * should implement BeginOpacity() and EndOpacity(). * * @param rect the rectangle to draw with opacity * @param opacity opacity value. 0-254. * @return OpStatus::ERR if the platform wants core to handle * opacity, OpStatus::OK otherwise. OpStatus::ERR_NO_MEMORY on * OOM. */ virtual OP_STATUS BeginOpacity(const OpRect& rect, UINT8 opacity) = 0; /** End the ongoing opacity operation. * * Note that BeginOpacity() / EndOpacity() calls may be nested. * * See also BeginOpacity(). */ virtual void EndOpacity() = 0; /** Get the currently active font. */ virtual OpFont *GetFont() { return current_font; } /** Get the currently active color. * * @return The currently active color. Format: 0xAABBGGRR */ virtual UINT32 GetColor() = 0; /** Set the rendering hint, should take effective immediately for subsequent drawing operation. */ virtual void SetRenderingHint(RenderingHint) {} /** Get the current rendering hint. */ virtual RenderingHint GetRenderingHint() { return Quality; } protected: OpFont* current_font; }; #endif // OPPAINTER_H
#include<SDL.h> #include "Bullet.hpp" #include "Tank.hpp" #include<list> using namespace std; class BattleField{ list<Tank> tanks; SDL_Renderer *gRenderer; SDL_Texture *assets; public: BattleField(SDL_Renderer *, SDL_Texture *); void drawObjects(); void createObject(int, int); void fire(); };
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <Renderer/PlatformTypes.h> #include <GLES3/gl3.h> #include <GLES3/gl2ext.h> // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(5039) // warning C5039: 'TpSetCallbackCleanupGroup': pointer or reference to potentially throwing function passed to extern C function under -EHc. Undefined behavior may occur if this function throws an exception #include <EGL/egl.h> PRAGMA_WARNING_POP // Get rid of some nasty OS macros #undef None // Linux: Undefine "None", this name is used inside enums defined by Unrimp (which gets defined inside "Xlib.h" pulled in by "egl.h") #undef max //[-------------------------------------------------------] //[ Forward declarations ] //[-------------------------------------------------------] namespace OpenGLES3Renderer { class IExtensions; class OpenGLES3Renderer; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace OpenGLES3Renderer { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Abstract OpenGL ES 3 context base interface */ class IOpenGLES3Context { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: /** * @brief * Destructor */ virtual ~IOpenGLES3Context(); /** * @brief * Return whether or not the context is properly initialized */ bool isInitialized() const; /** * @brief * Return the handle of a native OS window which is valid as long as the renderer instance exists * * @return * The handle of a native OS window which is valid as long as the renderer instance exists, "NULL_HANDLE" if there's no such window */ inline handle getNativeWindowHandle() const; /** * @brief * Return the used EGL display * * @return * The used EGL display, "EGL_NO_DISPLAY" on error */ inline EGLDisplay getEGLDisplay() const; /** * @brief * Return the used EGL configuration * * @return * The used EGL configuration, null pointer on error */ inline EGLConfig getEGLConfig() const; /** * @brief * Return the used EGL context * * @return * The used EGL context, "EGL_NO_CONTEXT" on error */ inline EGLContext getEGLContext() const; /** * @brief * Return the used EGL dummy surface * * @return * The used EGL dummy surface, "EGL_NO_SURFACE" on error */ inline EGLSurface getEGLDummySurface() const; /** * @brief * Makes a given EGL surface to the currently used one * * @param[in] eglSurface * EGL surface to make to the current one, can be a null pointer, in this case an internal dummy surface is set * * @return * "EGL_TRUE" if all went fine, else "EGL_FALSE" */ EGLBoolean makeCurrent(EGLSurface eglSurface); //[-------------------------------------------------------] //[ Platform specific ] //[-------------------------------------------------------] #if defined(LINUX) && !defined(ANDROID) inline ::Display* getX11Display() const; #endif //[-------------------------------------------------------] //[ Public virtual OpenGLES3Renderer::IOpenGLES3Context methods ] //[-------------------------------------------------------] public: /** * @brief * Initialize the context * * @param[in] multisampleAntialiasingSamples * Multisample antialiasing samples per pixel, <=1 means no antialiasing * * @return * "true" if all went fine, else "false" */ virtual bool initialize(uint32_t multisampleAntialiasingSamples); /** * @brief * Return the available extensions * * @return * The available extensions */ virtual const IExtensions& getExtensions() const = 0; //[-------------------------------------------------------] //[ Protected methods ] //[-------------------------------------------------------] protected: /** * @brief * Constructor * * @param[in] openGLES3Renderer * Owner OpenGL ES 3 renderer instance * @param[in] nativeWindowHandle * Handle of a native OS window which is valid as long as the renderer instance exists, "NULL_HANDLE" if there's no such window * @param[in] useExternalContext * When true an own OpenGL ES context won't be created */ IOpenGLES3Context(OpenGLES3Renderer& openGLES3Renderer, handle nativeWindowHandle, bool useExternalContext); /** * @brief * Copy constructor * * @param[in] source * Source to copy from */ explicit IOpenGLES3Context(const IOpenGLES3Context& source); /** * @brief * De-initialize the context */ void deinitialize(); /** * @brief * Copy operator * * @param[in] source * Source to copy from * * @return * Reference to this instance */ IOpenGLES3Context& operator =(const IOpenGLES3Context& source); //[-------------------------------------------------------] //[ Protected virtual OpenGLES3Renderer::IOpenGLES3Context methods ] //[-------------------------------------------------------] protected: /** * @brief * Choose a EGL configuration * * @param[in] multisampleAntialiasingSamples * Multisample antialiasing samples per pixel * * @return * The chosen EGL configuration, a null pointer on error * * @note * - Automatically tries to find fallback configurations */ virtual EGLConfig chooseConfig(uint32_t multisampleAntialiasingSamples) const; //[-------------------------------------------------------] //[ Protected data ] //[-------------------------------------------------------] protected: handle mNativeWindowHandle; ///< Handle of a native OS window which is valid as long as the renderer instance exists, "NULL_HANDLE" if there's no such window // X11 #if (defined(LINUX) && !defined(ANDROID)) ::Display *mX11Display; bool mOwnsX11Display; #endif // EGL EGLDisplay mEGLDisplay; // EGL EGLConfig mEGLConfig; EGLContext mEGLContext; EGLNativeWindowType mDummyNativeWindow; ///< Native dummy window handle, can be identical to "mNativeWindowHandle" if it's in fact no dummy at all, can be "NULL_HANDLE" EGLSurface mDummySurface; bool mUseExternalContext; }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // OpenGLES3Renderer //[-------------------------------------------------------] //[ Implementation includes ] //[-------------------------------------------------------] #include "OpenGLES3Renderer/IOpenGLES3Context.inl" #include "OpenGLES3Renderer/OpenGLES3ContextRuntimeLinking.h" // Required in here because we redefine the OpenGL ES 3 functions for dynamic runtime linking
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #include <unordered_map> #include <stack> #include <cstdio> #include <cmath> #include <cstring> #include <list> using namespace std; #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) // #define INF (1e300) #define eps (1e-9) #define MODULO 1000000007 // ifstream fin("796_input.txt"); // #define cin fin typedef pair<int, int> II; typedef vector<II> VII; class Graph { int V; list<int> * adj; void bridgeUtil(int u, vector<bool> & visited, vector<int> & disc, vector<int> & low, vector<int> & parent, int depth); public: Graph(int V); void addEdge(int v, int w); void bridge(); VII bridges; }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; bridges.resize(0); } void Graph::addEdge(int v, int w) { adj[v].push_back(w); adj[w].push_back(v); } void Graph::bridgeUtil(int u, vector<bool> & visited, vector<int> & disc, vector<int> & low, vector<int> & parent, int depth) { static int time = 0; visited[u] = true; disc[u] = low[u] = ++time; for (auto i = adj[u].begin(); i != adj[u].end(); i++) { int v = *i; if (!visited[v]) { parent[v] = u; bridgeUtil(v, visited, disc, low, parent, depth++); low[u] = min(low[u], low[v]); if (low[v] > disc[u]) { bridges.push_back(II(u, v)); } } else if (v != parent[u]) { low[u] = min(low[u], disc[v]); } } } void Graph::bridge() { vector<bool> visited(V, false); vector<int> disc(V, 0); vector<int> low(V, 0); vector<int> parent(V, -1); for (int i = 0; i < V; i++) { if (!visited[i]) { bridgeUtil(i, visited, disc, low, parent, 0); } } } int main() { int n; while (scanf("%d", &n) != -1) { Graph ag(n); for (int i = 0; i < n; i++) { int cur, num, next; scanf("%d (%d)", &cur, &num); for (int j = 0; j < num; j++) { scanf("%d", &next); ag.addEdge(cur, next); ag.addEdge(next, cur); } } ag.bridge(); VII &bridges = ag.bridges; int num_dup = ((int)bridges.size()); printf("%d critical link", num_dup); if (num_dup == 1) { printf("s\n"); } else { printf("s\n"); } for (int i = 0; i < bridges.size(); i++) { if (bridges[i].first > bridges[i].second) { int tmp = bridges[i].first; bridges[i].first = bridges[i].second; bridges[i].second = tmp; } } sort(bridges.begin(), bridges.end()); for (int i = 0; i < bridges.size(); i++) { printf("%d - %d\n", bridges[i].first, bridges[i].second); } printf("\n"); // scanf("%d", &n); } }
// Copyright (c) 2017 Doyub Kim // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include <perf_tests.h> #include <jet/list_query_engine3.h> #include <jet/timer.h> #include <jet/triangle_mesh3.h> #include <gtest/gtest.h> #include <random> using namespace jet; class ListQueryEngine3Tests : public ::testing::Test { protected: TriangleMesh3 triMesh; ListQueryEngine3<Triangle3> listQueryEngine; virtual void SetUp() { std::ifstream file(RESOURCES_DIR "bunny.obj"); ASSERT_TRUE(file); if (file) { triMesh.readObj(&file); file.close(); } for (size_t i = 0; i < triMesh.numberOfTriangles(); ++i) { auto tri = triMesh.triangle(i); listQueryEngine.add(tri); } } }; TEST_F(ListQueryEngine3Tests, Nearest) { std::mt19937 rng(0); std::uniform_real_distribution<> d(0.0, 1.0); const auto makeVec = [&]() { return Vector3D(d(rng), d(rng), d(rng)); }; const auto distanceFunc = [](const Triangle3& tri, const Vector3D& pt) { return tri.closestDistance(pt); }; std::vector<NearestNeighborQueryResult3<Triangle3>> results; Timer timer; size_t n = 1000; for (size_t i = 0; i < n; ++i) { results.push_back(listQueryEngine.nearest(makeVec(), distanceFunc)); } JET_PRINT_INFO("ListQueryEngine3::nearest calls took %f sec.\n", timer.durationInSeconds()); EXPECT_EQ(n, results.size()); } TEST_F(ListQueryEngine3Tests, RayIntersects) { std::mt19937 rng(0); std::uniform_real_distribution<> d(0.0, 1.0); const auto makeVec = [&]() { return Vector3D(d(rng), d(rng), d(rng)); }; const auto testFunc = [](const Triangle3& tri, const Ray3D& ray) { return tri.intersects(ray); }; std::vector<bool> results; Timer timer; size_t n = 1000; for (size_t i = 0; i < n; ++i) { results.push_back(listQueryEngine.intersects( Ray3D(makeVec(), makeVec().normalized()), testFunc)); } JET_PRINT_INFO("ListQueryEngine3::intersects calls took %f sec.\n", timer.durationInSeconds()); EXPECT_EQ(n, results.size()); }
#include <iostream> #include <string> void replace (char text[255], char change) { char str; std::cout << "pleace enter new letter" << std::endl; std::cin >> str; for (int i = 0; i < 255; ++i) { if(text[i] == change) { text[i] = str; } } } int count (char text[255], char str) { int quantity = 0; for (int i = 0; i < 255; ++i) { if (text[i] == str) { ++quantity; } } return quantity; } void remove(char text[255], char rem) { for ( int i = 0; i < 255; ++i) { if (text[i] == rem) { for (int j = i; j < 256; ++j) { text[j] = text[j+1]; } i = i - 1; } } } int main () { static char text[255]; std::cout << "enter your text" << std::endl; std::cin.get(text,255); bool k = 1; int number = 0; char change; char prog; std::cout << "1 count, cin '1' 'count letter' " << std::endl; std::cout << "2 replace, cin '2' 'replace letter'" << std::endl; std::cout << "3 remove, cin '3' 'remove letter' " << std::endl; std::cout << "4. '4' ' ' for exit " << std::endl; while(k) { std::cout << "please enter 'num' 'letter'" << std::endl; std::cin >> number; if (0 >= number && 4 < number) { break; } switch (number) { case 1: std::cin >> prog; std::cout << "leter is - " <<count(text, prog) << " pices" <<std::endl; break; case 2: std::cin >> prog; replace(text, prog); std::cout << text << std::endl; break; case 3: std::cin >> prog; remove(text, prog); std::cout << text << std::endl; break; case 4: k = 0; break; default: std::cout << "enter correct number" << std::endl; } } return 0; }
// Created by: Kirill GAVRILOV // Copyright (c) 2013-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _OpenGl_Buffer_H__ #define _OpenGl_Buffer_H__ #include <OpenGl_Resource.hxx> #include <TCollection_AsciiString.hxx> //! Buffer Object - is a general storage object for arbitrary data (see sub-classes). class OpenGl_Buffer : public OpenGl_Resource { DEFINE_STANDARD_RTTIEXT(OpenGl_Buffer, OpenGl_Resource) public: //! Helpful constants static const unsigned int NO_BUFFER = 0; //! Format VBO target enumeration value. Standard_EXPORT static TCollection_AsciiString FormatTarget (unsigned int theTarget); public: //! Create uninitialized buffer. Standard_EXPORT OpenGl_Buffer(); //! Destroy object. Standard_EXPORT virtual ~OpenGl_Buffer(); //! Return buffer target. virtual unsigned int GetTarget() const = 0; //! Return TRUE if this is a virtual (for backward compatibility) VBO object. virtual bool IsVirtual() const { return false; } //! @return true if current object was initialized bool IsValid() const { return myBufferId != NO_BUFFER; } //! @return the number of components per generic vertex attribute. unsigned int GetComponentsNb() const { return myComponentsNb; } //! @return number of vertex attributes / number of vertices specified within ::Init() Standard_Integer GetElemsNb() const { return myElemsNb; } //! Overrides the number of vertex attributes / number of vertexes. //! It is up to user specifying this number correct (e.g. below initial value)! void SetElemsNb (Standard_Integer theNbElems) { myElemsNb = theNbElems; } //! @return data type of each component in the array. unsigned int GetDataType() const { return myDataType; } //! @return offset to data, NULL by default Standard_Byte* GetDataOffset() const { return myOffset; } //! Creates buffer object name (id) if not yet generated. //! Data should be initialized by another method. Standard_EXPORT virtual bool Create (const Handle(OpenGl_Context)& theGlCtx); //! Destroy object - will release GPU memory if any. Standard_EXPORT virtual void Release (OpenGl_Context* theGlCtx) Standard_OVERRIDE; //! Bind this buffer object. Standard_EXPORT virtual void Bind (const Handle(OpenGl_Context)& theGlCtx) const; //! Unbind this buffer object. Standard_EXPORT virtual void Unbind (const Handle(OpenGl_Context)& theGlCtx) const; //! Notice that buffer object will be unbound after this call. //! @param theComponentsNb [in] specifies the number of components per generic vertex attribute; must be 1, 2, 3, or 4; //! @param theElemsNb [in] elements count; //! @param theData [in] pointer to float data (vertices/normals etc.). Standard_EXPORT bool Init (const Handle(OpenGl_Context)& theGlCtx, const unsigned int theComponentsNb, const Standard_Integer theElemsNb, const float* theData); //! Notice that buffer object will be unbound after this call. //! @param theComponentsNb [in] specifies the number of components per generic vertex attribute; must be 1, 2, 3, or 4; //! @param theElemsNb [in] elements count; //! @param theData [in] pointer to unsigned int data (indices etc.). Standard_EXPORT bool Init (const Handle(OpenGl_Context)& theGlCtx, const unsigned int theComponentsNb, const Standard_Integer theElemsNb, const unsigned int* theData); //! Notice that buffer object will be unbound after this call. //! @param theComponentsNb [in] specifies the number of components per generic vertex attribute; must be 1, 2, 3, or 4; //! @param theElemsNb [in] elements count; //! @param theData [in] pointer to unsigned short data (indices etc.). Standard_EXPORT bool Init (const Handle(OpenGl_Context)& theGlCtx, const unsigned int theComponentsNb, const Standard_Integer theElemsNb, const unsigned short* theData); //! Notice that buffer object will be unbound after this call. //! @param theComponentsNb [in] specifies the number of components per generic vertex attribute; must be 1, 2, 3, or 4; //! @param theElemsNb [in] elements count; //! @param theData [in] pointer to Standard_Byte data (indices/colors etc.). Standard_EXPORT bool Init (const Handle(OpenGl_Context)& theGlCtx, const unsigned int theComponentsNb, const Standard_Integer theElemsNb, const Standard_Byte* theData); //! Notice that buffer object will be unbound after this call. //! Function replaces portion of data within this buffer object using glBufferSubData(). //! The buffer object should be initialized before call. //! @param theElemFrom [in] element id from which replace buffer data (>=0); //! @param theElemsNb [in] elements count (theElemFrom + theElemsNb <= GetElemsNb()); //! @param theData [in] pointer to float data. Standard_EXPORT bool SubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, const float* theData); //! Read back buffer sub-range. //! Notice that buffer object will be unbound after this call. //! Function reads portion of data from this buffer object using glGetBufferSubData(). //! @param theElemFrom [in] element id from which replace buffer data (>=0); //! @param theElemsNb [in] elements count (theElemFrom + theElemsNb <= GetElemsNb()); //! @param theData [out] destination pointer to float data. Standard_EXPORT bool GetSubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, float* theData); //! Notice that buffer object will be unbound after this call. //! Function replaces portion of data within this buffer object using glBufferSubData(). //! The buffer object should be initialized before call. //! @param theElemFrom [in] element id from which replace buffer data (>=0); //! @param theElemsNb [in] elements count (theElemFrom + theElemsNb <= GetElemsNb()); //! @param theData [in] pointer to unsigned int data. Standard_EXPORT bool SubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, const unsigned int* theData); //! Read back buffer sub-range. //! Notice that buffer object will be unbound after this call. //! Function reads portion of data from this buffer object using glGetBufferSubData(). //! @param theElemFrom [in] element id from which replace buffer data (>=0); //! @param theElemsNb [in] elements count (theElemFrom + theElemsNb <= GetElemsNb()); //! @param theData [out] destination pointer to unsigned int data. Standard_EXPORT bool GetSubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, unsigned int* theData); //! Notice that buffer object will be unbound after this call. //! Function replaces portion of data within this buffer object using glBufferSubData(). //! The buffer object should be initialized before call. //! @param theElemFrom [in] element id from which replace buffer data (>=0); //! @param theElemsNb [in] elements count (theElemFrom + theElemsNb <= GetElemsNb()); //! @param theData [in] pointer to unsigned short data. Standard_EXPORT bool SubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, const unsigned short* theData); //! Read back buffer sub-range. //! Notice that buffer object will be unbound after this call. //! Function reads portion of data from this buffer object using glGetBufferSubData(). //! @param theElemFrom [in] element id from which replace buffer data (>=0); //! @param theElemsNb [in] elements count (theElemFrom + theElemsNb <= GetElemsNb()); //! @param theData [out] destination pointer to unsigned short data. Standard_EXPORT bool GetSubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, unsigned short* theData); //! Notice that buffer object will be unbound after this call. //! Function replaces portion of data within this buffer object using glBufferSubData(). //! The buffer object should be initialized before call. //! @param theElemFrom [in] element id from which replace buffer data (>=0); //! @param theElemsNb [in] elements count (theElemFrom + theElemsNb <= GetElemsNb()); //! @param theData [in] pointer to Standard_Byte data. Standard_EXPORT bool SubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, const Standard_Byte* theData); //! Read back buffer sub-range. //! Notice that buffer object will be unbound after this call. //! Function reads portion of data from this buffer object using glGetBufferSubData(). //! @param theElemFrom [in] element id from which replace buffer data (>=0); //! @param theElemsNb [in] elements count (theElemFrom + theElemsNb <= GetElemsNb()); //! @param theData [out] destination pointer to Standard_Byte data. Standard_EXPORT bool GetSubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, Standard_Byte* theData); public: //! @name advanced methods //! Returns estimated GPU memory usage for holding data without considering overheads and allocation alignment rules. virtual Standard_Size EstimatedDataSize() const Standard_OVERRIDE { return IsValid() ? sizeOfGlType (myDataType) * myComponentsNb * myElemsNb : 0; } //! @return size of specified GL type Standard_EXPORT static size_t sizeOfGlType (unsigned int theType); //! Initialize buffer with new data. Standard_EXPORT virtual bool init (const Handle(OpenGl_Context)& theGlCtx, const unsigned int theComponentsNb, const Standard_Integer theElemsNb, const void* theData, const unsigned int theDataType, const Standard_Integer theStride); //! Initialize buffer with new data. bool init (const Handle(OpenGl_Context)& theGlCtx, const unsigned int theComponentsNb, const Standard_Integer theElemsNb, const void* theData, const unsigned int theDataType) { return init (theGlCtx, theComponentsNb, theElemsNb, theData, theDataType, Standard_Integer(theComponentsNb) * Standard_Integer(sizeOfGlType (theDataType))); } //! Update part of the buffer with new data. Standard_EXPORT virtual bool subData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, const void* theData, const unsigned int theDataType); //! Read back buffer sub-range. Standard_EXPORT virtual bool getSubData (const Handle(OpenGl_Context)& theGlCtx, const Standard_Integer theElemFrom, const Standard_Integer theElemsNb, void* theData, const unsigned int theDataType); public: //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; protected: //! Binds a buffer object to an indexed buffer target. //! Wrapper for glBindBufferBase(). //! @param theGlCtx [in] active OpenGL context //! @param theIndex [in] index to bind Standard_EXPORT void BindBufferBase (const Handle(OpenGl_Context)& theGlCtx, unsigned int theIndex); //! Unbinds a buffer object from an indexed buffer target. //! Wrapper for glBindBufferBase(). //! @param theGlCtx [in] active OpenGL context //! @param theIndex [in] index to bind Standard_EXPORT void UnbindBufferBase (const Handle(OpenGl_Context)& theGlCtx, unsigned int theIndex); //! Binds a buffer object to an indexed buffer target with specified offset and size. //! Wrapper for glBindBufferRange(). //! @param theGlCtx [in] active OpenGL context //! @param theIndex [in] index to bind (@sa GL_MAX_UNIFORM_BUFFER_BINDINGS in case of uniform buffer) //! @param theOffset [in] offset within the buffer (@sa GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT in case of uniform buffer) //! @param theSize [in] sub-section length starting from offset Standard_EXPORT void BindBufferRange (const Handle(OpenGl_Context)& theGlCtx, unsigned int theIndex, const intptr_t theOffset, const size_t theSize); protected: Standard_Byte* myOffset; //!< offset to data unsigned int myBufferId; //!< VBO name (index) unsigned int myComponentsNb; //!< Number of components per generic vertex attribute, must be 1, 2, 3, or 4 Standard_Integer myElemsNb; //!< Number of vertex attributes / number of vertices unsigned int myDataType; //!< Data type (GL_FLOAT, GL_UNSIGNED_INT, GL_UNSIGNED_BYTE etc.) }; DEFINE_STANDARD_HANDLE(OpenGl_Buffer, OpenGl_Resource) #endif // _OpenGl_Buffer_H__
#include <bits/stdc++.h> using namespace std; int dp[155555]; int main(){ int n; cin >> n; vector<int> a(n); for(int i=0; i<n; i++) cin >> a[i]; for(int i=1; i<=n; i++) dp[i] = 1e9; for(int i=0; i<n; i++){ dp[i+1] = min(dp[i+1], dp[i]+ abs(a[i+1] - a[i])); dp[i+2] = min(dp[i+2], dp[i] + abs(a[i+2] - a[i])); } cout << dp[n-1] << endl; return 0; }
//Accepted. Time-0.000s #include <bits/stdc++.h> using namespace std; #define ll long long #define vll vector<ll> string find(int x, int y, int a = 0, int b = 1, int c = 1, int d = 0) { int m = a + c, n = b + d; if (x == m && y == n) return ""; if (x*n < y*m) return 'L' + find(x, y, a, b, m, n); else return 'R' + find(x, y, m, n, c, d); } int main() { ll n,m; while(cin>>n>>m) { if(n==1 && m==1) break; cout<<find(n,m)<<"\n"; } }
#include <sstream> #include <algorithm> #include "IpidDetection.hh" #include "Log.hpp" IpidDetection::IpidDetection() : ADetection() { this->setPace(20); this->setName(std::string("IpidDetection")); this->worksWithPair(false); } IpidDetection::~IpidDetection() { } void IpidDetection::findIpidVariations(boost::ptr_vector<State>& states) { std::vector<IpidVariation>::iterator ite = this->_variations.begin(); bool found = false; for (ite; ite != this->_variations.end(); ite++) { if (ite->from == states.front().getFrom() && ite->to == states.front().getTo()) { this->registerIpidVariations((*ite), states); found = true; break; } } if (!found) { this->_variations.push_back(IpidVariation(states.front().getFrom(), states.front().getTo())); this->registerIpidVariations(this->_variations.back(), states); } } void IpidDetection::registerIpidVariations(IpidVariation& var, boost::ptr_vector<State>& states) { boost::ptr_vector<State>::iterator ite = states.begin(); unsigned short expected_value = ite->getId(); var.abnormalInc = 0; for (ite; ite != states.end(); ite++) { if (expected_value != ite->getId()) { expected_value = ite->getId(); var.abnormalInc++; } expected_value++; } std::stringstream ss; ss << "- Ipid Detection - pair: " << var.from.to_string() << "->" << var.to.to_string() << ": anomalies detected: " << var.abnormalInc; Log::get_mutable_instance().write(ss.str()); } void IpidDetection::analyseIpidVariations() { } void IpidDetection::work(boost::ptr_vector<State> states) { this->findIpidVariations(states); }
#include<cmath> #include<stack> #include<iostream> #include<cstring> using namespace std; char s0[1000000001]; char a[17]="0123456789ABCDEF";//便于输出 long long s1=0; int main() { int n,m; stack <int> s; cin>>n>>s0>>m; int l=strlen(s0)-1; int i=0; while(l>=0)//先转十进制 { if(s0[l]>='0' && s0[l]<='9')//若为数字情况 s1+=(s0[l]-'0')*pow(n,i); else s1+=(s0[l]-'A'+10)*pow(n,i);//为字母情况 i++;l--; } while(s1!=0)//转到要求进制 { int k=s1%m; s.push(k);//压入栈 s1/=m; } while(!s.empty())//输出栈内元素 { cout<<a[s.top()]; s.pop(); } }
#include "piece.h" #define PROGRAM_TITLE "Rhythm Tetris" const int PLAY_HEIGHT = 20; const int PLAY_WIDTH = 10; const int HEIGHT_PIXEL = 600; const int WIDTH_PIXEL = 300; class Board { private: int board[PLAY_HEIGHT][PLAY_WIDTH]; Piece * currentPiece = 0; // (0,0) is top left corner int pieceXPosition; int pieceYPosition; public: Board(); ~Board(); int getBoardAt(int x, int y); int getPieceX(); int getPieceY(); void reset(); //no argument makes random piece void makePiece(); void makePiece(Piece_Shapes piece); void dropPiece(); void dropPieceFull(); void rotatePiece(); void movePieceLeft(); void movePieceRight(); void cleanBoard(); void updateBoard(); void solidifyBoard(); bool isValid(); void removeLine(int lineNum); int removeFullLines(); };
#pragma once #include <iostream> #include "UserInterface.h" #include "PassengerCar.h" #include "Motorcycle.h" #include "Bus.h" #include "Truck.h" class Produce { public: PassengerCar* create_passenger_car(UserInterface* ui); Motorcycle* create_motorcycle(UserInterface* ui); Truck* create_truck(UserInterface* ui); Bus* create_bus(UserInterface* ui); };
#pragma once #include "Interface/IRuntimeModule.h" #include "Process/Process.h" #include <list> namespace Rocket { class ProcessManager : implements IRuntimeModule { public: RUNTIME_MODULE_TYPE(ProcessManager); ProcessManager() = default; virtual ~ProcessManager() = default; virtual int Initialize() override; virtual void Finalize() override; virtual void Tick(Timestep ts) override; // interface uint64_t UpdateProcesses(unsigned long deltaMs); // updates all attached processes WeakProcessPtr AttachProcess(StrongProcessPtr pProcess); // attaches a process to the process mgr void AbortAllProcesses(bool immediate); void PauseAllProcesses(); void UnPauseAllProcesses(); // accessors uint32_t GetProcessCount(void) const { return m_ProcessList.size(); } private: typedef std::list<StrongProcessPtr> ProcessList; ProcessList m_ProcessList; uint64_t m_SuccessCount = 0; uint64_t m_FailCount = 0; }; ProcessManager* GetProcessManager(); extern ProcessManager* g_ProcessManager; } // namespace Rocket
#include "header.cpp" struct edge{ int from, to, wght; edge(int u, int v, int w=0): from(u), to(v), wght(w) {} }; bool operator>(edge e1, edge e2){return e1.wght>e2.wght;} bool operator<(edge e1, edge e2){return e1.wght<e2.wght;} bool operator==(edge e1, edge e2){return (e1.from==e2.from&&e1.to==e2.to)||(e1.from==e2.to&&e1.to==e2.from);} typedef vector<edge> ve; typedef vector<ve> me; ostream &operator<<(ostream &os, edge e){ os<<e.from<<"->"<<e.to<<'{'<<e.wght<<'}'; return os; } int V, E; mi AdjMtx; me AdjLst; ve EdgeLst; vi DFS(int s){ //O(V+E) int ord=0; vi num(V,-1); num[s]=ord++; stack<ii> stk; stk.push(ii(s,0)); while(!stk.empty()){ int u=stk.top().fst, k=stk.top().snd; stk.pop(); fr(i,k,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(num[v]<0){ stk.push(ii(u,i+1)); num[v]=ord++; u=v, i=-1; } } } return num; } vi BFS(int s){ //O(V+E) vi num(V,-1); num[s]=0; queue<int> que; que.push(s); while(!que.empty()){ int u=que.front(); que.pop(); fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(num[v]<0){ que.push(v); num[v]=num[u]+1; } } } return num; } vi topSort(){ //O(V+E) vi num(V,0), topsort; fr(j,0,V){ num[j]=1; stack<ii> stk; stk.push(ii(j,0)); while(!stk.empty()){ int u=stk.top().fst, k=stk.top().snd; stk.pop(); fr(i,k,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(!num[v]){ stk.push(ii(u,i)); num[v]=1; u=v, i=-1; } } topsort.push_back(u); } } return topsort; } pair<vb,vector<vb> > APaB(int s){ //O(V+E) int ord=0, root=0; vi num(V,-1), low(V,-1), par(V,-1); vb artPoint(V); vector<vb> bridge(V,vb(V)); num[s]=low[s]=ord++; stack<ii> stk; stk.push(ii(s,0)); while(!stk.empty()){ int u=stk.top().fst, k=stk.top().snd; stk.pop(); fr(i,k,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(num[v]<0){ if(u==s) root++; stk.push(ii(u,i)); par[v]=u; num[v]=low[v]=ord++; u=v, i=-1; } else{ if(v!=par[u]) low[u]=min(low[u],num[v]); if(num[u]<num[v]) low[u]=min(low[u],low[v]); if(num[u]<=low[v]) artPoint[u]=1; if(num[u]<low[v]) bridge[u][v]=bridge[v][u]=1; } } } if(root>1) artPoint[s]=1; return pair<vb,vector<vb> >(artPoint,bridge); } pair<int,vi> SCC_Tarjan(int s){ //O(V+E) int ord=0, nSCC=0; vi num(V,-1), low(V,-1), SCC(V,-1); stack<int> CC; num[s]=low[s]=ord++; CC.push(s); SCC[s]=0; stack<ii> stk; stk.push(ii(s,0)); while(!stk.empty()){ int u=stk.top().fst, k=stk.top().snd; stk.pop(); fr(i,k,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(num[v]<0){ stk.push(ii(u,i)); num[v]=low[v]=ord++; CC.push(v); SCC[v]=0; u=v, i=-1; } else if(!SCC[v]) low[u]=min(low[u],low[v]); } if(num[u]==low[u]){ int v; nSCC++; do{ v=CC.top(); CC.pop(); SCC[v]=nSCC; }while(u!=v); } } return pair<int,vi>(nSCC,SCC); } pair<int,ve> MST_Kruskal(){ //O(E*log(V)) int cost=0; ve mst; djSet ds(V); priority_queue<edge,ve> pq; fr(i,0,EdgeLst.size()) pq.push(EdgeLst[i]); while(ds.qnt>1){ edge e=pq.top(); pq.pop(); int u=e.from, v=e.to, w=e.wght; if(!ds.isSameSet(u,v)){ cost+=w; ds.unionSet(u,v); mst.push_back(e); } } return pair<int,ve>(cost,mst); } pair<int,ve> MST_Prim(){ //O(E*log(V)) int cost=0; ve mst; vi dist(V,INF); dist[0]=0; priority_queue<edge,ve> pq; pq.push(edge(0,0)); while(!pq.empty()){ edge e=pq.top(); int d=e.wght, u=e.to; pq.pop(); if(d==dist[u]){ cost+=d; if(u) mst.push_back(e); dist[u]=0; fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to, w=AdjLst[u][i].wght; if(w<dist[v]){ dist[v]=w; pq.push(edge(u,v,w)); } } } } return pair<int,ve>(cost,mst); } pair<int,ve> SndST(){ //O(E*log(V)+V^2) int cost=0; ve mst, nonmst; djSet ds(V); priority_queue<edge,ve> pq; fr(i,0,EdgeLst.size()) pq.push(EdgeLst[i]); while(ds.qnt>1){ edge e=pq.top(); pq.pop(); int u=e.from, v=e.to, w=e.wght; if(!ds.isSameSet(u,v)){ cost+=w; ds.unionSet(u,v); mst.push_back(e); } else nonmst.push_back(e); } while(!pq.empty()){ nonmst.push_back(pq.top()); pq.pop(); } me mstAL(V); fr(i,0,V-1){ int u=mst[i].from, v=mst[i].to, w=mst[i].wght; mstAL[u].push_back(edge(u,v,i)); mstAL[v].push_back(edge(v,u,i)); } mi maxw(V,vi(V)); me maxe(V,ve(V,edge(0,0))); fr(s,0,V){ queue<int> que; que.push(s); while(!que.empty()){ int u=que.front(); que.pop(); fr(i,0,mstAL[u].size()){ int v=mstAL[u][i].to, w=mstAL[u][i].wght; if(!maxw[s][v]){ que.push(v); if(maxw[s][u]>w) maxw[s][v]=maxw[s][u], maxe[s][v]=maxe[s][u]; else maxw[s][v]=w, maxe[s][v]=mstAL[u][i]; } } } } int m=0; fr(i,0,nonmst.size()){ int u=nonmst[i].from, v=nonmst[i].to, w=nonmst[i].wght; int um=nonmst[m].from, vm=nonmst[m].to, wm=nonmst[m].wght; if(w-maxw[u][v]<wm-maxw[um][vm]) m=i; } int um=nonmst[m].from, vm=nonmst[m].to, wm=nonmst[m].wght; fr(i,0,mst.size()) if(mst[i]==maxe[um][vm]) mst[i]=nonmst[m]; cost+=wm-maxw[um][vm]; return pair<int,ve>(cost,mst); } pair<vi,vi> SSSP_Dijkstra(int s){ //O(E*log(V)) vi dist(V,INF), p(V,s); dist[s]=0; priority_queue<edge,ve> pq; pq.push(edge(s,s)); while(!pq.empty()){ int d=pq.top().wght, u=pq.top().to; pq.pop(); if(d==dist[u]){ fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to, w=AdjLst[u][i].wght; if(dist[v]>dist[u]+w){ dist[v]=dist[u]+w; p[v]=u; pq.push(edge(u,v,dist[v])); } } } } return pair<vi,vi>(dist,p); } pair<vi,vi> SSSP_BellmanFord(int s){ //O(V*E) vi dist(V,INF), p(V,s); dist[s]=0; fr(k,0,V){ fr(u,0,V){ fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to, w=AdjLst[u][i].wght; if(dist[v]>dist[u]+w){ dist[v]=dist[u]+w; p[v]=u; } } } } return pair<vi,vi>(dist,p); } bool negativeCycle(int s){ //O(V*E) vi dist = SSSP_BellmanFord(s).fst; fr(u,0,V){ fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to, w=AdjLst[u][i].wght; if(dist[v]>dist[u]+w) return true; } } return false; } pair<mi,mi> APSP_FloydWarshall(){ //O(V^3) mi dist(AdjMtx), p(V); fr(i,0,V) p[i]=vi(V,i); fr(k,0,V){ fr(i,0,V){ fr(j,0,V){ if(dist[i][j]>dist[i][k]+dist[k][j]){ dist[i][j]=dist[i][k]+dist[k][j]; p[i][j]=p[k][j]; } } } } return pair<mi,mi>(dist,p); } pair<int,ve> MF_EdmondsKarp(int s, int t){ //O(V*E^2) int f, maxFlow=0; ve minCut; vector<vi> res(AdjMtx); while(1){ vi num(V,-1), p(V,-1); num[s]=0; queue<int> que; que.push(s); while(!que.empty()){ int u=que.front(); que.pop(); if(u==t) break; fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(res[u][v]&&num[v]<0){ que.push(v); num[v]=num[u]+1; p[v]=u; } } } if(p[t]==-1) break; f=INF; for(int u=t;u!=s;u=p[u]) f=min(f,res[p[u]][u]); for(int u=t;u!=s;u=p[u]) res[p[u]][u]-=f, res[u][p[u]]+=f; maxFlow+=f; } fr(u,0,V){ fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(!res[u][v]) minCut.push_back(AdjLst[u][i]); } } return pair<int,ve>(maxFlow,minCut); } int MCF(int s, int t, int flow){ //O(V^2*E^2) int f, cost=0; ve minCut; vector<vi> res(AdjMtx); while(1){ vi dist(V,INF), p(V,-1); dist[s]=0; fr(k,0,V){ fr(u,0,V){ fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to, w=AdjLst[u][i].wght; if(res[u][v]&&dist[v]<dist[u]+w){ dist[v]=dist[u]+w; p[v]=u; } } } } if(p[t]==-1) break; f=flow; for(int u=t;u!=s;u=p[u]) f=min(f,res[p[u]][u]); for(int u=t;u!=s;u=p[u]) res[p[u]][u]-=f, res[u][p[u]]+=f; flow-=f; } fr(u,0,V){ fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to, w=AdjLst[u][i].wght, c=AdjMtx[u][v]-res[u][v]; if(c>0) cost+=c*w; } } return cost; } list<int> cyc; vector<vb> mark(V,vb(V)); void eulerRec(list<int>::iterator add, int u){ fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(!mark[u][v]){ mark[u][v]=mark[v][u]=1; eulerRec(cyc.insert(add,u),v); } } } vi eulerTour(int s){ //O(V+E) vi v; eulerRec(cyc.begin(),s); for(list<int>::iterator it=cyc.begin();it!=cyc.end();it++) v.push_back(*it); return v; } vi match(V,-1); int augPath(int u){ if(match[u]) return 0; match[u]=1; fr(i,0,AdjLst[u].size()){ int v=AdjLst[u][i].to; if(match[v]<0||augPath(match[v])){ match[v]=u; return 1; } } return 0; } int MCBM(int l){ //O(V*E) int maxm=0; fr(i,0,l){ fr(j,0,l) match[j]=0; maxm+=augPath(i); } return maxm; } //MIS = V - MCBM //MVC = MCBM //Genius is one percent inspiration, ninety-nine percent perspiration int main(){ cin>>V>>E; AdjMtx=mi(V,vi(V,INF)); AdjLst=me(V); int s,t,f; bool dir; cin>>s>>t>>f; fr(i,0,E){ int u,v,w; cin>>u>>v>>w; AdjMtx[u][v]=w; AdjLst[u].push_back(edge(u,v,w)); EdgeLst.push_back(edge(u,v,w)); if(!dir){ AdjMtx[v][u]=w; AdjLst[v].push_back(edge(v,u,w)); } } cout<<"DFS: "<<DFS(s)<<endl; cout<<"BFS: "<<BFS(s)<<endl; cout<<"Top Sort: "<<topSort()<<endl; cout<<"AP&B: "<<APaB(s)<<endl; cout<<"SCC Tarjan: "<<SCC_Tarjan(s)<<endl; cout<<"MST Kruskal: "<<MST_Kruskal()<<endl; cout<<"MST Prim: "<<MST_Prim()<<endl; cout<<"Second ST: "<<SndST()<<endl; cout<<"SSSP Dijkstra: "<<SSSP_Dijkstra(s)<<endl; cout<<"SSSP Bellman Ford: "<<SSSP_BellmanFord(s)<<endl; cout<<"Has negative cycle? "<<negativeCycle(s)<<endl; cout<<"APSP Floyd Warshall: "<<APSP_FloydWarshall()<<endl; cout<<"MF Edmonds Karp: "<<MF_EdmondsKarp(s,t)<<endl; cout<<"MCF: "<<MCF(s,t,f)<<endl; cout<<"Euler Tour: "<<eulerTour(s)<<endl; cout<<"MCBM: "<<MCBM(s)<<endl; }
#include "Camera.h" Camera::Camera() { Start(720, 1280); } Camera::~Camera() { } Camera::Camera(float windowHeight, float windowWidth) { Start(windowHeight, windowWidth); } void Camera::Start() { Start(720, 1280); } void Camera::Start(float windowHeight, float windowWidth) { SetPos(vec3(10)); SetLookAt(vec3(10), vec3(0), vec3(0, 1, 0)); //viewTransform = glm::lookAt(vec3(10), vec3(0), vec3(0, 1, 0)); projectionTransform = glm::perspective(glm::pi<float>() * 0.25f, windowWidth / windowHeight, 0.1f, 1000.f); UpdateProjectionViewMatrix(); } void Camera::SetPerspective(float fieldOfView, float aspectRatio, float near, float) { } void Camera::SetLookAt(vec3 from, vec3 to, vec3 up) { viewTransform = glm::lookAt(from, to, up); worldTransform = glm::inverse(viewTransform); } void Camera::SetPos(vec3 pos) { worldTransform[3] = vec4(pos, 1); viewTransform = glm::inverse(worldTransform); UpdateProjectionViewMatrix(); worldPos = worldTransform[3]; } vec3 Camera::GetPos() { return vec3(worldTransform[3]); } void Camera::SetWorldTransform(mat4 transform) { worldTransform = transform; viewTransform = glm::inverse(worldTransform); UpdateProjectionViewMatrix(); } mat4 Camera::GetWorldTransform() { return worldTransform; } mat4 Camera::GetView() { return viewTransform; } mat4 Camera::GetProjection() { return projectionTransform; } mat4 Camera::GetProjectionView() { return projectionViewTransform; } vec3 Camera::GetRow(int row) { return worldTransform[row].xyz; } void Camera::getFrustumPlanes(const glm::mat4 & transform, glm::vec4 * planes) { // right side planes[0] = vec4( transform[0][3] - transform[0][0], transform[1][3] - transform[1][0], transform[2][3] - transform[2][0], transform[3][3] - transform[3][0]); // left side planes[1] = vec4( transform[0][3] + transform[0][0], transform[1][3] + transform[1][0], transform[2][3] + transform[2][0], transform[3][3] + transform[3][0]); // top planes[2] = vec4( transform[0][3] - transform[0][1], transform[1][3] - transform[1][1], transform[2][3] - transform[2][1], transform[3][3] - transform[3][1]); // bottom planes[3] = vec4( transform[0][3] + transform[0][1], transform[1][3] + transform[1][1], transform[2][3] + transform[2][1], transform[3][3] + transform[3][1]); // far planes[4] = vec4( transform[0][3] - transform[0][2], transform[1][3] - transform[1][2], transform[2][3] - transform[2][2], transform[3][3] - transform[3][2]); // near planes[5] = vec4( transform[0][3] + transform[0][2], transform[1][3] + transform[1][2], transform[2][3] + transform[2][2], transform[3][3] + transform[3][2]); // plane normalisation, based on length of normal for (int i = 0; i < 6; i++) { float d = glm::length(vec3(planes[i])); planes[i] /= d; } } void Camera::UpdateProjectionViewMatrix() { projectionViewTransform = projectionTransform * viewTransform; }
#include <iostream> #include <iterator> #include <fstream> #include <algorithm> // for std::copy #include <QCommandLineParser> #include <QtDebug> #include <stdio.h> #include "context.h" Context::Context(QCoreApplication& app, int argc, char* argv[]) { /* Set default values */ myHost = "127.0.0.1"; myPort = 8080; myWaitMS = 5000; myInputFilename = "datagrams.txt"; mySleepTime = 0; myMaxMsgs = 0; myRnd = NULL; myCommentChar = '\0'; this->processArgs(app, argc, argv); } Context::~Context() { qWarning() << "Context instance is garbage now."; } uint Context::getPort() { return myPort; } QString Context::getHost() { return myHost; } uint Context::getWaitMS() { return myWaitMS; } ulong Context::getSleep() { return mySleepTime; } bool Context::keepSocketOpen() { return myKeepSocketOpen; } bool Context::handleComments(const std::string& in) { // Smartly detect comments and ignore them in input if(myCommentChar != '\0' && in.at(0) == myCommentChar) { // We have a comment line here, ignore return false; } if(myMsgIndex == 0) { std::string valid_chars("%;+*-:#!?$/\\"); int len = in.size(); if(in.at(0) == in.at(len-1) && std::string::npos != valid_chars.find(in.at(0))) { // We have a valid char that begins and ends the first line myCommentChar = in.at(0); qDebug() << "Input comment char is '" << in.at(0) << "'."; return false; } } // Not the first line any more - no comment indication return true; } bool Context::digestMessages() { myMsgIndex = 0; char buf[30]; // Open the File std::ifstream in(myInputFilename.toStdString()); // Check if object is valid if (!in) { qDebug() << "Cannot open " << myInputFilename << " for input!"; return false; } std::string str; // Read the next line from File until it reaches the end. while (std::getline(in, str)) { if (str.size() > 0 && handleComments(str)) { myMsgs.push_back(str); sprintf(buf, "datagram[%05d:%03lu]:", myMsgIndex, (unsigned long)str.size()); qDebug() << buf << str.c_str(); myMsgIndex++; } } in.close(); myMsgIndex = 0; if (myConfirmTransmission) { std::cout << "Press <RETURN> to start datagram transmission." << std::endl; std::cin.get(); } return true; } bool Context::noMoreMessages() { return myMaxMsgs < 1; } bool Context::getNextMessage(std::string& msg) { if (this->noMoreMessages()) { qDebug() << "Maximum number of messages sent, stopping now."; return false; } myMaxMsgs--; if (!myMsgs.size()) { this->digestMessages(); } if (myRnd) { myMsgIndex = myRnd->generate() % myMsgs.size(); msg = myMsgs.at(myMsgIndex); return true; } else if (myMsgIndex < myMsgs.size()) { msg = myMsgs.at(myMsgIndex); myMsgIndex++; return true; } return false; } uint Context::getMsgIndex() { return myMsgIndex; } void Context::processArgs(QCoreApplication& app, int argc, char* argv[]) { QCommandLineParser parser; parser.setApplicationDescription("Datagrams-over-TCP-socket sender"); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption copt(QStringList() << "C" << "confirm", QCoreApplication::translate("main", "press any key to confirm transmission after input has been read, default: send immediately")); parser.addOption(copt); QCommandLineOption hopt(QStringList() << "H" << "host", QCoreApplication::translate("main", "host to connect to, default: 127.0.0.1"), QCoreApplication::translate("main", "host")); parser.addOption(hopt); QCommandLineOption iopt(QStringList() << "I" << "input-file", QCoreApplication::translate("main", "take messages from <file>, default: datagrams.txt"), QCoreApplication::translate("main", "input-file")); parser.addOption(iopt); QCommandLineOption kopt(QStringList() << "K" << "keep-socket-open", QCoreApplication::translate("main", "keep the socket open between transmissions, default: re-open for every datagram sent across")); parser.addOption(kopt); QCommandLineOption mopt(QStringList() << "M" << "max-messages", QCoreApplication::translate("main", "send at most <max> messages in total, default: 10000 (0: no limit)"), QCoreApplication::translate("main", "max")); parser.addOption(mopt); QCommandLineOption popt(QStringList() << "P" << "port", QCoreApplication::translate("main", "port to connect to, default: 8080"), QCoreApplication::translate("main", "port")); parser.addOption(popt); QCommandLineOption ropt(QStringList() << "R" << "randomize", QCoreApplication::translate("main", "send messages randomly, default: line by line from top to bottom")); parser.addOption(ropt); QCommandLineOption sopt(QStringList() << "S" << "sleep-between-sends", QCoreApplication::translate("main", "sleep for <msec> ms between message sends, default: 0 (no waiting at all)"), QCoreApplication::translate("main", "msec")); parser.addOption(sopt); QCommandLineOption wopt(QStringList() << "W" << "wait", QCoreApplication::translate("main", "wait for response with a maximum of <msec> ms before timing out, default: 5000"), QCoreApplication::translate("main", "msec")); parser.addOption(wopt); parser.process(app); myConfirmTransmission = parser.isSet(copt); if(parser.isSet(hopt)) { myHost = parser.value(hopt); } if(parser.isSet(iopt)) { myInputFilename = parser.value(iopt); } myKeepSocketOpen = parser.isSet(kopt); if(parser.isSet(mopt)) { myMaxMsgs = parser.value(mopt).toInt(); qWarning() << "Sending no more than" << myMaxMsgs << "messages to host."; } if(parser.isSet(popt)) { myPort = parser.value(popt).toInt(); } if(parser.isSet(ropt)) { qWarning() << "Random mode is on."; myRnd = QRandomGenerator::system(); } if(parser.isSet(sopt)) { mySleepTime = parser.value(sopt).toInt(); qWarning() << "Going to sleep for" << mySleepTime << "ms between message sends."; } if(parser.isSet(wopt)) { myWaitMS = parser.value(wopt).toInt(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef CUEHTTP_RESPONSE_HPP_ #define CUEHTTP_RESPONSE_HPP_ #include <memory> #include "cuehttp/cookies.hpp" #include "cuehttp/deps/fmt/fmt.h" #include "cuehttp/detail/body_stream.hpp" #include "cuehttp/detail/common.hpp" #include "cuehttp/detail/noncopyable.hpp" namespace cue { namespace http { using namespace std::literals; class response final : safe_noncopyable { public: response(cookies& cookies, detail::reply_handler handler) noexcept : cookies_{cookies}, last_gmt_date_str_{detail::utils::to_gmt_date_string(std::time(nullptr))}, reply_handler_{std::move(handler)} {} void minor_version(unsigned version) noexcept { minor_version_ = version; } unsigned status() const noexcept { return status_; } void status(unsigned status) { status_ = status; } bool has(std::string_view field) const noexcept { for (auto it = headers_.begin(); it != headers_.end(); ++it) { if (detail::utils::iequals(it->first, field)) { return true; } } return false; } std::string_view get(std::string_view field) const noexcept { for (const auto& header : headers_) { if (detail::utils::iequals(header.first, field)) { return header.second; } } using namespace std::literals; return ""sv; } template <typename _Field, typename _Value> void set(_Field&& field, _Value&& value) { headers_.emplace_back(std::make_pair(std::forward<_Field>(field), std::forward<_Value>(value))); } void set(const std::map<std::string, std::string>& headers) { headers_.insert(headers_.end(), headers.begin(), headers.end()); } void set(std::map<std::string, std::string>&& headers) { headers_.insert(headers_.end(), std::make_move_iterator(headers.begin()), std::make_move_iterator(headers.end())); } void remove(std::string_view field) noexcept { auto erase = headers_.end(); for (auto it = headers_.begin(); it != headers_.end(); ++it) { if (detail::utils::iequals(it->first, field)) { erase = it; break; } } if (erase != headers_.end()) { headers_.erase(erase); } } template <typename _Url> void redirect(_Url&& url) { if (status_ == 404) { status(302); } set("Location", std::forward<_Url>(url)); } bool keepalive() const noexcept { return keepalive_; } void keepalive(bool keepalive) { if (keepalive && minor_version_) { keepalive_ = true; } else { keepalive_ = false; set("Connection", "close"); } } template <typename _ContentType> void type(_ContentType&& content_type) { set("Content-Type", std::forward<_ContentType>(content_type)); } std::uint64_t length() const noexcept { return content_length_; } void length(std::uint64_t content_length) noexcept { content_length_ = content_length; } bool has_body() const noexcept { return !body_.empty(); } std::string_view dump_body() const noexcept { return body_; } void chunked() noexcept { if (!is_chunked_) { is_chunked_ = true; set("Transfer-Encoding", "chunked"); } } template <typename _Body> void body(_Body&& body) { body_ = std::forward<_Body>(body); length(body_.length()); } void body(const char* buffer, std::size_t size) { body_.assign(buffer, size); length(body_.length()); } std::ostream& body() { assert(reply_handler_); if (!stream_) { is_stream_ = true; reply_handler_(header_to_string()); stream_ = std::make_shared<detail::body_ostream>(is_chunked_, reply_handler_); } return *stream_; } void reset() { headers_.clear(); status_ = 404; keepalive_ = true; content_length_ = 0; body_.clear(); is_chunked_ = false; is_stream_ = false; response_str_.clear(); stream_.reset(); } bool is_stream() const noexcept { return is_stream_; } void to_string(std::string& str) { str += detail::utils::get_response_line(minor_version_ * 1000 + status_); // headers const auto now = std::chrono::steady_clock::now(); if (now - last_time_ > std::chrono::seconds{1}) { last_gmt_date_str_ = detail::utils::to_gmt_date_string(std::time(nullptr)); last_time_ = now; } str += last_gmt_date_str_; for (const auto& header : headers_) { str += fmt::format("{}: {}\r\n", header.first, header.second); } // cookies const auto& cookies = cookies_.get(); for (const auto& cookie : cookies) { if (cookie.valid()) { str += fmt::format("Set-Cookie: {}\r\n", cookie.to_string()); } } if (!is_chunked_) { if (content_length_ != 0) { str += fmt::format("Content-Length: {}\r\n\r\n", content_length_); str += body_; } else { str.append("Content-Length: 0\r\n\r\n"); } } else { // chunked str.append("\r\n"); } } private: std::string header_to_string() { std::string str{detail::utils::get_response_line(minor_version_ * 1000 + status_)}; // headers // os << detail::utils::to_gmt_date_string(std::time(nullptr)); for (const auto& header : headers_) { str += fmt::format("{}: {}\r\n", header.first, header.second); } if (get("connection").empty() && keepalive_) { str += "Connection: keep-alive\r\n"sv; } // cookies const auto& cookies = cookies_.get(); for (const auto& cookie : cookies) { if (cookie.valid()) { str += fmt::format("Set-Cookie: {}\r\n", cookie.to_string()); } } if (is_chunked_) { str += "\r\n"sv; } else { str += fmt::format("Content-Length: {}\r\n\r\n", content_length_); } return str; } std::vector<std::pair<std::string, std::string>> headers_; unsigned minor_version_{1}; unsigned status_{404}; bool keepalive_{true}; std::uint64_t content_length_{0}; cookies& cookies_; std::string body_; std::string response_str_; bool is_chunked_{false}; bool is_stream_{false}; std::chrono::steady_clock::time_point last_time_{std::chrono::steady_clock::now()}; std::string last_gmt_date_str_; detail::reply_handler reply_handler_; std::shared_ptr<std::ostream> stream_{nullptr}; }; } // namespace http } // namespace cue #endif // CUEHTTP_RESPONSE_HPP_
#pragma once #include "Primitive.h" class AABB : Primitive { public: AABB(vec3 const& extents, vec3 const& pos) : Primitive(PrimitiveID::AABB) { m_extents = extents; m_pos = pos; } inline vec3 GetExtents() { return m_extents; }; inline vec3 GetPos() { return m_pos; }; private: vec3 m_extents; vec3 m_pos; };
#include <bits/stdc++.h> using namespace std; const int SZ = 1 << 18; struct LazySeg { unsigned long long sum[2 * SZ], lazy[2 * SZ], num_active[2 * SZ]; LazySeg() { for (int i = 0; i < SZ; i++) { num_active[SZ + i] = 1; } for (int i = SZ - 1; i > 0; i--) { num_active[i] = num_active[2 * i] + num_active[2 * i + 1]; } } void push (int ind, int L, int R) { sum[ind] += num_active[ind] * lazy[ind]; if (L != R) { for (int i = 0; i < 2; i++) { lazy[2 * ind + i] += lazy[ind]; } } lazy[ind] = 0; } void pull(int ind) { sum[ind] = sum[2 * ind] + sum[2 * ind + 1]; num_active[ind] = num_active[2 * ind] + num_active[ 2 * ind + 1]; } void increment(int lo, int hi, int val, int ind=1, int L = 0, int R = SZ - 1) { push(ind, L, R); if (hi < L || R < lo) { return; } if (lo <= L && R <= hi) { lazy[ind] = val; push(ind, L, R); return; } int M = (L + R) / 2; increment(lo, hi, val, 2 * ind, L, M); increment(lo, hi, val, 2 * ind + 1, M + 1, R); pull(ind); } unsigned long long query(int lo, int hi, int ind=1, int L=0, int R=SZ - 1) { push(ind, L, R); if (lo > R || L > hi) { return 0; } if (lo <= L && R <= hi) { return sum[ind]; } int M = (L + R) / 2; return query(lo, hi, 2 * ind, L, M) + query(lo, hi, 2 * ind + 1, M + 1, R); } void deactivate(int pos, int ind = 1, int L = 0, int R = SZ - 1) { push(ind, L, R); if (pos > R || L > pos) { return; } if (pos <= L && R <= pos) { assert(num_active[ind] == 1); sum[ind] = num_active[ind] = 0; return; } int M = (L + R) / 2; deactivate(pos, 2 * ind, L, M); deactivate(pos, 2 * ind + 1, M + 1,R); pull(ind); } } Seg; int main() { int N; cin >> N; vector<int> breeds(N), last(N + 1, -1), prev_oc(N); for (int& b : breeds) { cin >> b; } long long ans = 0; for (int r = 0; r < N; r++) { int& last_oc = last[breeds[r]]; ans += Seg.query(last_oc + 1, SZ - 1); if (last_oc != -1) { Seg.deactivate(last_oc); Seg.increment(prev_oc[last_oc], last_oc - 1, -1); } Seg.increment(last_oc, r - 1, 1); prev_oc[r] = last_oc; last_oc = r; } cout << ans << endl; }
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef _GDCMIO_DICOMINSTANCE_HPP_ #define _GDCMIO_DICOMINSTANCE_HPP_ #include <string> #include <vector> #include <gdcmMediaStorage.h> #include "fwData/macros.hpp" #include "gdcmIO/config.hpp" namespace gdcmIO { /** * @brief This class defines a DICOM SOP instance. * * It is useful during all writing process. This class * allows to share data between writers. * * @class DicomInstance. * @author IRCAD (Research and Development Team). * @date 2011. */ class GDCMIO_CLASS_API DicomInstance { public: GDCMIO_API DicomInstance(); GDCMIO_API virtual ~DicomInstance(); GDCMIO_API DicomInstance( const DicomInstance & dicomInstance); GDCMIO_API fwGettersSettersDocMacro(SOPClassUID, SOPClassUID, std::string, The SOP class UID.); GDCMIO_API void setSOPClassUID(const ::gdcm::MediaStorage::MSType a_MSType); GDCMIO_API fwGettersSettersDocMacro(SOPInstanceUID, SOPInstanceUID, std::string, The SOP instance UID.); GDCMIO_API fwGettersSettersDocMacro(StudyInstanceUID, studyInstanceUID, std::string, The study instance UID.); GDCMIO_API fwGettersSettersDocMacro(SeriesInstanceUID, seriesInstanceUID, std::string, The series instance UID.); GDCMIO_API fwGettersSettersDocMacro(FrameOfRefUID, frameOfRefUID, std::string, The frame of reference UID.); GDCMIO_API fwGettersSettersDocMacro(InstanceNumber, instanceNumber, std::string, The instance number.); GDCMIO_API fwGettersSettersDocMacro(Modality, modality, std::string, The modality of image.); GDCMIO_API fwGettersSettersDocMacro(InstitutionName, institutName, std::string, Institution where the equipment that produced the composite instances is located.); GDCMIO_API fwGettersSettersDocMacro(ReferencedSOPInstanceUIDs, referencedSOPInstanceUIDs, std::vector< std::string >, The array of SOP Instance UIDs); GDCMIO_API void addReferencedSOPInstanceUID(const std::string & a_UID); GDCMIO_API fwGettersSettersDocMacro(IsMultiFrame, isMultiFrame, bool, Flag on multi-frame state of an image series); private: // static DicomInstanceWriter * m_unique_instance; //** Members which define SOP UID **// std::string m_SOPClassUID; ///< Defined storage type (eg : CT Image Storage, ...). std::string m_SOPInstanceUID; ///< Defined storage instance. //** Members which define Instance UID **// std::string m_studyInstanceUID; ///< UID of the current study. std::string m_seriesInstanceUID; ///< UID of the current series (= Acquisition). std::string m_instanceNumber; ///< Number of a storage corresponding to a given series. ///< (eg : 0,1, ...., 42, ...) std::string m_modality; ///< Modality of the instance. std::string m_institutName; ///< Hospital name. //** Members which define IMAGE Instance **// std::string m_frameOfRefUID; ///< UID of the image first frame (see : Tag(0020,0052) Frame of Reference UID ) std::vector< std::string > m_referencedSOPInstanceUIDs; ///< SOP Instance UID of each frame of an 3D image bool m_isMultiFrame; ///< Define if the image is multiframe. }; } #endif /* _GDCMIO_DICOMINSTANCE_HPP_ */
#pragma once namespace MyDirectX { struct Vector2 { float x, y, z = 0; Vector2(); Vector2(float x, float y); Vector2(float x, float y, float z); bool operator==(const Vector2& vec); bool operator!=(const Vector2& vec); Vector2 operator+(const Vector2& vec); Vector2 operator-(const Vector2& vec); Vector2 operator*(float f); //½ºÄ®¶ó °ö float Length() const; Vector2 Normalize(); static float Dot(Vector2& v1, Vector2& v2); static Vector2 Cross(Vector2& v1, Vector2& v2); Vector2 TransformCoord(struct Matrix& mat); Vector2 TransformNormal(struct Matrix& mat); D3DXVECTOR3 ToDXVector3(); }; }
#include"Play.h" Play::Play(QObject *parent) : QObject(parent) { scene=new QGraphicsScene; Pview->setScene(scene); QPixmap back(":/play/Floral-Background.jpg"); scene->setBackgroundBrush(back.scaled(500,500,Qt::IgnoreAspectRatio,Qt::SmoothTransformation)); scene->setSceneRect(0,0,500,500); Pview->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); Pview->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); Pview->setFixedSize(500,500); Pview->show(); score=new Score; //score->setZValue(1); scene->addItem(score); ball=new Ball; scene->addItem(ball); // ball->setFlag(QGraphicsItem::ItemIsMovable); int randnum =rand()%9; easywall1 = new Easywall(randnum);// need change scene->addItem(easywall1); easywall1->setPos(0,-700);// in it's constructor //scene->addItem(score); // mediunmwall1 = new Mediumwall(2);// need change // scene->addItem(mediunmwall1); // mediunmwall1->setPos(0,-500); timer2->start(8120); connect(timer2,SIGNAL(timeout()),this,SLOT(makewall())); // mediunmwall1->setPos(0,-1100); // mediunmwall2 = new Mediumwall(2); // scene->addItem(mediunmwall2); // // setTransformOriginPoint(50,50); // mediunmwall2->setPos(0,-500); // // mediunmwall3 = new Mediumwall(3); } void Play::makewall() { score->increase(); int random_number_med = rand() % 9; int random_number_eas = rand() % 9; if(wall_num<4){ if(wall_num%2==1){ mediunmwall1 = new Mediumwall(random_number_med); // need change scene->addItem(mediunmwall1); mediunmwall1->setPos(0,-700); } if(wall_num%2==0){ easywall1 = new Easywall(random_number_eas); // need change scene->addItem(easywall1); easywall1->setPos(0,-700); } } if(wall_num==4){ mediunmwall2 = new Mediumwall(9); scene->addItem(mediunmwall2); mediunmwall2->setPos(0,-700); whiteblock = new Whiteblock2; scene->addItem(whiteblock); whiteblock->setPos(0,-450); } if(wall_num>4){ if(wall_num%2==1){ mediunmwall1 = new Mediumwall(random_number_med); // need change scene->addItem(mediunmwall1); mediunmwall1->setPos(0,-700); } if(wall_num%2==0){ easywall1 = new Easywall(random_number_eas); // need change scene->addItem(easywall1); easywall1->setPos(0,-700); } } wall_num++; }
#include<cstdio> #include<iostream> #include<cstring> using namespace std; #define mn 15000 #define mx 33000 int level[mn],tree[mx]; int lb(int x){ return x&-x; } void add(int x,int value){ for(int i=x;i<=mx;i+=lb(i)) tree[i]+=value; } int get(int x){ int ret=0; for(int i=x;i;i-=lb(i)) ret+=tree[i]; return ret; } int n,_x,_y; int main(){ scanf("%d",&n); memset(level,0,sizeof(level)); memset(tree,0,sizeof(tree)); for(int i=0;i<n;i++){ scanf("%d%d",&_x,&_y); _x++,_y++; level[get(_x)]++; add(_x,1); } for(int i=0;i<n;i++) printf("%d\n",level[i]); return 0; }
// // Created by heyhey on 20/03/2018. // #include "Fonction.h" Fonction::Fonction() { bloc = NULL ; parametre = NULL ; } Fonction::~Fonction() { } Parametre *Fonction::getParametre() const { return parametre; } void Fonction::setParametre(Parametre *parametre) { Fonction::parametre = parametre; } const vector<Declaration *> &Fonction::getDeclarations() const { return declarations; } void Fonction::setDeclarations(const vector<Declaration *> &declaration) { Fonction::declarations = declaration; } Bloc *Fonction::getBloc() const { return bloc; } void Fonction::setBloc(Bloc *bloc) { Fonction::bloc = bloc; } void Fonction::addDeclaration(Declaration *declaration) { declarations.push_back(declaration); } const string &Fonction::getNom() const { return nom; } void Fonction::setNom(const string &nom) { Fonction::nom = nom; } Fonction::Type Fonction::getType() const { return type; } /* void Fonction::setType(Fonction::Type type) { Fonction::type = type; } */ Fonction::Fonction(Parametre *parametre, const string &nom, string type, const vector<Declaration *> &declarations, Bloc *bloc) : parametre(parametre), nom(nom), declarations(declarations), bloc(bloc) { setType(type); } void Fonction::setType(string type) { if(type == "char") Fonction::type = Fonction::CHAR; else if(type == "int32_t") Fonction::type = Fonction::INT_32; else if(type == "int64_t") Fonction::type = Fonction::INT_64; else if(type == "void") Fonction::type = Fonction::VOID; else if(type == "int") Fonction::type = Fonction::INT; } ostream &operator<<(ostream &os, const Fonction &fonction) { os << " nom: " << fonction.nom << " type: " << fonction.type << std::endl; os << "parametre: "; if ( (fonction.parametre) != NULL) {os << *(fonction.getParametre()); } else { os << "NULL " ; } os << std::endl; os << " declarations: "; for (auto i : fonction.declarations ) { os << *i << ' '; } os << std :: endl; if((fonction.getBloc()) != NULL ){ os << " bloc: " << *(fonction.getBloc()); }else {os << " NULL" ;} os << "fin de fonction"<< std::endl; return os; }
// Project 20 Light Harp int soundPin = 11; int pitchInputPin = 0; int volumeInputPin = 1; int ldrDim = 400; int ldrBright = 800; byte sine[] = {0, 22, 44, 64, 82, 98, 111, 120, 126, 127, 126, 120, 111, 98, 82, 64, 44, 22, 0, -22, -44, -64, -82, -98, -111, -120, -126, -128, -126, -120, -111, -98, -82, -64, -44, -22}; long lastCheckTime = millis(); int pitchDelay; int volume; void setup() { // change PWM frequency to 63kHz cli(); //disable interrupts while registers are configured bitSet(TCCR2A, WGM20); bitSet(TCCR2A, WGM21); //set Timer2 to fast PWM mode (doubles PWM frequency) bitSet(TCCR2B, CS20); bitClear(TCCR2B, CS21); bitClear(TCCR2B, CS22); sei(); //enable interrupts now that registers have been set pinMode(soundPin, OUTPUT); } void loop() { long now = millis(); if (now > lastCheckTime + 20L) { pitchDelay = map(analogRead(pitchInputPin), ldrDim, ldrBright, 10, 30); volume = map(analogRead(volumeInputPin), ldrDim, ldrBright, 1, 4); lastCheckTime = now; } playSine(pitchDelay, volume); } void playSine(int period, int volume) { for( int i = 0; i < 36; i++) { analogWrite(soundPin, (sine[i] / volume) + 128); delayMicroseconds(period); } }
#include<iostream> #include<math.h> using namespace std; typedef unsigned long long int ll; bool kt(ll n){ if(n < 2) return false; ll x = sqrt(n); for(ll i = 2; i <= x; i++) if(n % i == 0) return false; return true; } int main(){ ll n; cin >> n; if(kt(n)) cout << "true"; else cout << "false"; return 0; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <stdio.h> #include <string.h> #include <numeric> #define INF (1<<28) using namespace std; class LateProfessor { public: double getProbability(int waitTime, int walkTime, int lateTime, int bestArrival, int worstArrival) { int lateEnd = walkTime - lateTime; int t = waitTime; if (worstArrival == bestArrival) { while (t <= worstArrival) { for (int i=1; i<=lateEnd; ++i) { if (t+i == bestArrival) { return 1.0; } } t = t + waitTime + walkTime; } return 0.0; } else { int s = 0; while (t < worstArrival) { for (int i=0; i<lateEnd; ++i) { if (t+i >= bestArrival && t+i <worstArrival) { s++; } } t = t + waitTime + walkTime; } return (double)s/(worstArrival-bestArrival); } } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 20; int Arg1 = 30; int Arg2 = 10; int Arg3 = 0; int Arg4 = 50; double Arg5 = 0.4; verify_case(0, Arg5, getProbability(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_1() { int Arg0 = 20; int Arg1 = 30; int Arg2 = 10; int Arg3 = 30; int Arg4 = 100; double Arg5 = 0.42857142857142855; verify_case(1, Arg5, getProbability(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_2() { int Arg0 = 20; int Arg1 = 40; int Arg2 = 50; int Arg3 = 0; int Arg4 = 300; double Arg5 = 0.0; verify_case(2, Arg5, getProbability(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_3() { int Arg0 = 101; int Arg1 = 230; int Arg2 = 10; int Arg3 = 654; int Arg4 = 17890; double Arg5 = 0.6637270828498492; verify_case(3, Arg5, getProbability(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_4() { int Arg0 = 20; int Arg1 = 30; int Arg2 = 10; int Arg3 = 90; int Arg4 = 90; double Arg5 = 1.0; verify_case(4, Arg5, getProbability(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_5() { int Arg0 = 20; int Arg1 = 30; int Arg2 = 10; int Arg3 = 91; int Arg4 = 91; double Arg5 = 0.0; verify_case(5, Arg5, getProbability(Arg0, Arg1, Arg2, Arg3, Arg4)); } // END CUT HERE }; // BEGIN CUT HERE int main() { LateProfessor ___test; ___test.run_test(-1); } // END CUT HERE
#include "../../include/time_leak/netAnalyzer.hpp" using namespace std; void time_leak::NetAnalyzer::RunAnalysis(time_leak::Net &net, bool runConditional) { while(this->wasChanged()) { this->resetChanged(); this->analyzeNet(net, net.GetPlaces().at("end"), true); this->transitionsQueue.Clear(); this->placesQueue.Clear(); if (!this->wasChanged()) break; this->resetAnalyzedFlag(net.GetPlaces()); this->resetAnalyzedFlag(net.GetHighTransitions()); this->resetAnalyzedFlag(net.GetLowTransitions()); this->analyzeNet(net, this->findStartPlace(net.GetPlaces()), false); } this->checkForSpecialCases(net.GetHighTransitions(), runConditional); printResults(net.GetHighTransitions()); } void time_leak::NetAnalyzer::analyzeNet(time_leak::Net &net, time_leak::Place *startPlace, bool upwards) { startPlace->Analyze(); Traverse(startPlace->GetElementsBasedOnDirection(upwards), this->transitionsQueue); while (this->placesQueue.Size() > 0 || this->transitionsQueue.Size() > 0) { if (time_leak::ForwardQueue(this->transitionsQueue, this->placesQueue, upwards)) changesMade(); if (time_leak::ForwardQueue(this->placesQueue, this->transitionsQueue, upwards)) changesMade(); } } template <class T> void time_leak::NetAnalyzer::resetAnalyzedFlag(T &Elements) { for (auto iterator = Elements.begin(); iterator != Elements.end(); ++iterator) { iterator->second->SetAnalyzed(false); } } time_leak::Place *time_leak::NetAnalyzer::findStartPlace(map<string, time_leak::Place*> places) { time_leak::Place *p; for (auto iterator = places.begin(); iterator != places.end(); ++iterator) { if (iterator->second->GetInElements().size() == 0) { p = iterator->second; break; } } return p; } void time_leak::NetAnalyzer::checkForSpecialCases(map<string, time_leak::Transition*> &highTransitions, bool runConditional) { for (auto iterator = highTransitions.begin(); iterator != highTransitions.end(); ++iterator) { this->checkIntervalOnlyCase(iterator->second); if (runConditional) this->checkConditionalCase(iterator->second); this->checkIntervalOnlyCase(iterator->second); } } void time_leak::NetAnalyzer::checkIntervalOnlyCase(time_leak::Transition *transition) { if (transition->GetTransitionType() != Transition::TransitionType::low && transition->GetTransitionType() != Transition::TransitionType::lowEnd) return; Transition::TransitionType initialTransitionType = transition->GetTransitionType(); map<string, time_leak::Place *> places = transition->GetOutElements(); for (auto it1 = places.begin(); it1 != places.end(); ++it1) { map<string, time_leak::Transition *> transitions = it1->second->GetOutElements(); for (auto it2 = transitions.begin(); it2 != transitions.end(); ++it2) { if (it2->second->CheckIfLow()) { if (it2->second->GetInElements().size() > 1) { map<string, time_leak::Place *> places2 = it2->second->GetInElements(); for (auto it3 = places2.begin(); it3 != places2.end(); ++it3) { if (places.find(it3->second->GetId()) == places.end()) { if (transition->GetTransitionType() == Transition::TransitionType::low) { transition->SetTransitionType(Transition::TransitionType::maxDuration); } if (transition->GetTransitionType() == Transition::TransitionType::lowEnd) { map<string, time_leak::Transition *> transitions2 = it3->second->GetInElements(); for (auto it4 = transitions2.begin(); it4 != transitions2.end(); ++it4) { if (!it4->second->CheckIfLow()) { transition->SetTransitionType(Transition::TransitionType::high); if (transition->GetConditional()) { transition->SetConditional(false); } } } } } } } else { transition->SetTransitionType(initialTransitionType); return; } } } } } void time_leak::NetAnalyzer::checkConditionalCase(time_leak::Transition *transition) { if (transition->GetTransitionType() == Transition::TransitionType::low || transition->GetTransitionType() == Transition::TransitionType::maxDuration) return; if (transition->GetTransitionType() != Transition::TransitionType::lowStart) this->checkConditionallyLowStart(transition); if (transition->GetTransitionType() != Transition::TransitionType::lowEnd && transition->GetTransitionType() != Transition::TransitionType::low) this->checkConditionallyLowEnd(transition); return; } void time_leak::NetAnalyzer::checkConditionallyLowStart(time_leak::Transition *transition) { map<string, time_leak::Place*> inputPlaces = transition->GetInElements(); bool conditionallyLowStart = true; bool conditionally = false; for (auto inputPlace = inputPlaces.begin(); inputPlace != inputPlaces.end(); ++inputPlace) { map<string, time_leak::Transition *> inputTransitions = inputPlace->second->GetInElements(); for (auto inputTransition = inputTransitions.begin(); inputTransition != inputTransitions.end(); ++inputTransition) { if (transition->GetTransitionType() == Transition::TransitionType::high && (inputTransition->second->CheckIfLow() || inputTransition->second->GetTransitionType() == Transition::TransitionType::lowEnd) && !inputTransition->second->GetConditional()) { transition->SetTransitionType(Transition::TransitionType::lowStart); transition->SetConditional(); return; } else if (inputTransition->second->CheckIfLow() && inputPlace->second->GetHighOut() < 2 && !inputTransition->second->GetConditional()) { conditionally = true; } else { conditionally = false; } map<string, time_leak::Place*> outputPlaces = inputTransition->second->GetOutElements(); for (auto outputPlace = outputPlaces.begin(); outputPlace != outputPlaces.end(); ++outputPlace) { if (outputPlace->second->GetId() != inputPlace->second->GetId()) { map<string, time_leak::Transition*> outputTransitions = outputPlace->second->GetOutElements(); for (auto outputTransition = outputTransitions.begin(); outputTransition != outputTransitions.end(); ++outputTransition) { if ((outputTransition->second->CheckIfLow() || outputTransition->second->GetTransitionType() == Transition::TransitionType::lowStart) && !outputTransition->second->GetConditional() && inputPlace->second->GetHighOut() < 2) { conditionally = true; break; } } } if (conditionally) break; } if (conditionally) break; } if (!conditionally) { conditionallyLowStart = false; } } if (conditionallyLowStart) { if (transition->GetTransitionType() == Transition::TransitionType::lowEnd) transition->SetTransitionType(Transition::TransitionType::low); else transition->SetTransitionType(Transition::TransitionType::lowStart); transition->SetConditional(); } return; } void time_leak::NetAnalyzer::checkConditionallyLowEnd(time_leak::Transition *transition) { map<string, Place*> outputPlaces = transition->GetOutElements(); bool conditionallyLowEnd = false; for (auto outputPlace = outputPlaces.begin(); outputPlace != outputPlaces.end(); ++outputPlace) { map<string, Transition*> outputTransitions = outputPlace->second->GetOutElements(); for (auto outputTransition = outputTransitions.begin(); outputTransition != outputTransitions.end(); ++outputTransition) { if ((outputTransition->second->CheckIfLow() || outputTransition->second->GetTransitionType() == Transition::TransitionType::lowStart) && !outputTransition->second->GetConditional()) { conditionallyLowEnd = true; break; } } if (conditionallyLowEnd) break; } if (conditionallyLowEnd) { if (transition->GetTransitionType() == Transition::TransitionType::lowStart) { transition->SetTransitionType(Transition::TransitionType::low); checkIntervalOnlyCase(transition); } else transition->SetTransitionType(Transition::TransitionType::lowEnd); transition->SetConditional(); } } bool time_leak::NetAnalyzer::wasChanged() { return this->changed; } void time_leak::NetAnalyzer::changesMade() { this->changed = true; } void time_leak::NetAnalyzer::resetChanged() { this->changed = false; } void time_leak::NetAnalyzer::printResults(map<string, time_leak::Transition*> &highTransitions) { map<string, time_leak::Transition *>::iterator iterator; for (iterator = highTransitions.begin(); iterator != highTransitions.end(); ++iterator) { cout << iterator->second->GetId() << "-" << iterator->second->GetTransitionTypeString() << endl; } /*map<string, time_leak::Place *>::iterator iterator2; for (iterator2 = globals::Places.begin(); iterator2 != globals::Places.end(); ++iterator2) { if (iterator2->second->IsTimeDeducible()) cout << iterator2->second->GetId() << " is timeDeducible." << endl; }*/ }
#include "server/HTTPServer.h" #include "RuntimeArguments.h" eeskorka::serverConfig eeskorka::config; int main(int argc, char** argv) { RuntimeArguments arguments(argc, argv); eeskorka::config.readConfigFile(arguments.configPath); if (arguments.port != -1) { eeskorka::config.port = arguments.port; } eeskorka::httpServer server; if (server.startStaticServer() == -1) { spdlog::critical("cannot start server"); return 1; } return 0; }
//Declaration header #include"resources.h" //C++ headers #include<sstream> #include<fstream> //Engine headers #include"logger.h" namespace shady_engine { resources::resources() { } std::shared_ptr<shader> resources::load_shader( const std::string& pName, const std::string& pVSPath, const std::string& pFSPath ) { std::ifstream vsFile; std::ifstream fsFile; vsFile.exceptions(std::ifstream::badbit); fsFile.exceptions(std::ifstream::badbit); try { vsFile.open(pVSPath.c_str()); fsFile.open(pFSPath.c_str()); } catch (std::ios::failure& f) { throw std::runtime_error("failed to open shader file!"); } std::stringstream vsSStream; std::stringstream fsSStream; vsSStream << vsFile.rdbuf(); fsSStream << fsFile.rdbuf(); std::string vsString = vsSStream.str(); std::string fsString = fsSStream.str(); const char* vertexShader = vsString.c_str(); const char* fragmentShader = fsString.c_str(); try { shaders[pName] = std::make_shared<shader>(vertexShader, fragmentShader); } catch (std::bad_alloc& e) { throw std::bad_alloc(e); } return shaders[pName]; } std::shared_ptr<texture2D> resources::load_texture( const std::string& pName, const std::string& pPath, GLenum pFormat ) { unsigned char *image = nullptr; GLint width = 0; GLint height = 0; if (pFormat == GL_RGB) image = SOIL_load_image(pPath.c_str(), &width, &height, 0, SOIL_LOAD_RGB); else if (pFormat == GL_RGBA) image = SOIL_load_image(pPath.c_str(), &width, &height, 0, SOIL_LOAD_RGBA); if (image == nullptr){ throw std::runtime_error("failed to load image file!"); } try { textures[pName] = std::make_shared<texture2D>(image,width,height,pFormat); } catch (std::bad_alloc& e) { throw std::bad_alloc(e); } return textures[pName]; } std::shared_ptr<shader> resources::use_shader(const std::string& pName) { shaders[pName]->use(); return shaders[pName]; } }
#pragma once class Base { public: virtual int PublicMethodBase(); virtual int CallProtectedMethod(); virtual int CallPrivateMethod(); int x; protected: virtual int ProtectedMethodBase(); int y; private: virtual int PrivateMethodBase(); int z; }; class A : public Base { public: virtual int PublicMethodBase() override; protected: virtual int ProtectedMethodBase() override; private: virtual int PrivateMethodBase() override; //Non virtual interface Idiom if the method that call this one is not virtual //x is public //y is protected //z is not accesible from this class }; class B : protected Base { //x is protected //y is protected //z is not accesible from this class }; class C : private Base { public: int ImplementedInTermsOfBase(); //x is private //y is private //z is not accesible from this class };
#include <cmath> #include <Poco/Ascii.h> #include <Poco/Exception.h> #include <Poco/NumberParser.h> #include <Poco/String.h> #include "math/SimpleCalc.h" using namespace std; using namespace Poco; using namespace BeeeOn; double SimpleCalc::evaluate(const string &input) const { enum State { S_INIT, S_TERM_OP_TERM, }; State state = S_INIT; const string &trimmed = trim(input); auto at = trimmed.begin(); const auto end = trimmed.end(); if (at == end) throw SyntaxException("expected <term> but got nothing"); double result = NAN; double tmp = NAN; char op = '\0'; while (at != end) { switch (state) { case S_INIT: result = parseTerm(at, end); break; case S_TERM_OP_TERM: tmp = parseTerm(at, end); apply(result, op, tmp); break; } op = parseOpOrEOF(at, end); if (op == '\0') return result; state = S_TERM_OP_TERM; } if (op != '\0') throw SyntaxException("missing <term> after <op>: " + to_string(op)); return result; } double SimpleCalc::parseTerm( string::const_iterator &at, string::const_iterator end) const { skipWhitespace(at, end); enum State { S_BEGIN, S_ZERO, S_DIGIT, S_FLOAT }; const string::const_iterator begin = at; State state = S_BEGIN; for (; at != end; ++at) { const char c = *at; switch (state) { case S_BEGIN: if (c == '0') state = S_ZERO; else if (Ascii::isDigit(c)) state = S_DIGIT; else if (c == '.') state = S_FLOAT; else if (c == '-') continue; else throw SyntaxException("unexpected character " + string(1, c) + " for <term>"); break; case S_ZERO: if (c == '0') continue; else if (c == '.') state = S_FLOAT; else if (isWhitespace(c) || isOperator(c)) return 0.0; else throw SyntaxException("unexpected content after <term>: " + to_string(c)); break; case S_DIGIT: if (Ascii::isDigit(c)) continue; else if (c == '.') state = S_FLOAT; else if (isWhitespace(c) || isOperator(c)) return NumberParser::parse({begin, at}); else throw SyntaxException("unexpected content after <term>: " + to_string(c)); break; case S_FLOAT: if (Ascii::isDigit(c)) continue; else if (isWhitespace(c) || isOperator(c)) return NumberParser::parseFloat({begin, at}); else throw SyntaxException("unexpected content after <term>: " + to_string(c)); break; default: throw IllegalStateException("no such <term> state, this is a serious bug"); } } // parse whole begin..end switch (state) { case S_BEGIN: throw SyntaxException("expected <term> but found nothing"); case S_ZERO: return 0.0; case S_DIGIT: return NumberParser::parse({begin, at}); case S_FLOAT: return NumberParser::parseFloat({begin, at}); } throw IllegalStateException("no such <term> state, this is a serious bug"); } char SimpleCalc::parseOpOrEOF( string::const_iterator &at, string::const_iterator end) const { skipWhitespace(at, end); if (at == end) return '\0'; const char op = *at; if (isOperator(op)) { ++at; return op; } throw SyntaxException("unexpected character: " + string(1, op) + " for <op>"); } void SimpleCalc::apply(double &result, char op, double tmp) const { switch (op) { case '+': result += tmp; break; case '-': result -= tmp; break; case '*': result *= tmp; break; case '/': if (tmp == 0.0) throw IllegalStateException("division by zero detected"); result /= tmp; break; default: throw IllegalStateException("invalid operation: " + to_string(op) + ", this is a bug"); } } void SimpleCalc::skipWhitespace( string::const_iterator &at, string::const_iterator end) const { while (at != end && isWhitespace(*at)) ++at; } bool SimpleCalc::isWhitespace(const char c) const { return Ascii::isSpace(c); } bool SimpleCalc::isOperator(const char c) const { static string operators = "+-*/"; return operators.find(c) != string::npos; } bool SimpleCalc::isTerm(const char c) const { return Ascii::isDigit(c) || c == '.'; }
#include <list> #include <vector> #include <algorithm> #include <iterator> #include <numeric> #include <limits> #include <iostream> #include "graph.hpp" template<typename T> class TD; float PartitionGraph::compute_weight(int i, int j) { float weight = -1. * std::pow(std::accumulate(a_.begin()+i, a_.begin()+j, 0.), 2) / std::accumulate(b_.begin()+i, b_.begin()+j, 0.); return weight; } float PartitionGraph::compute_weight(int i, int j, std::vector<float>& diffs) { return diffs[i*n_+j]; } void PartitionGraph::add_edge_and_weight(int j, int k, std::vector<float> &&diffs) { int curr_node = node_to_int(j, k); float weight; if (k==1) { // level 1, just connect source to node weight = compute_weight(0, j, diffs); __attribute__((unused)) auto r = boost::add_edge(0, curr_node, EdgeWeightProperty(weight), G_); } else if (k==T_) { // level T_, connect all nodes in previous layer to node for (int i=j; i<j+per_level_-1; ++i) { weight = compute_weight(i, k, diffs); __attribute__((unused)) auto r = boost::add_edge(node_to_int(i, k-1), curr_node, EdgeWeightProperty(weight), G_); } } else { // level >= 2 for (int i=k-1; i<j; ++i) { weight = compute_weight(i, j, diffs); __attribute__((unused)) auto r = boost::add_edge(node_to_int(i, k-1), curr_node, EdgeWeightProperty(weight), G_); } } } void PartitionGraph::sort_by_priority(std::vector<float>& a, std::vector<float>& b) { std::vector<int> ind(a.size()); std::iota(ind.begin(), ind.end(), 0); std::stable_sort(ind.begin(), ind.end(), [&a, &b](int i, int j) { return (a[i]/b[i]) < (a[j]/b[j]); }); priority_sortind_ = ind; // Inefficient reordering std::vector<float> a_s, b_s; for (auto i : ind) { a_s.push_back(a[i]); b_s.push_back(b[i]); } std::copy(a_s.begin(), a_s.end(), a.begin()); std::copy(b_s.begin(), b_s.end(), b.begin()); } void PartitionGraph::create() { // sort vectors by priority function G(x,y) = x/y sort_by_priority(a_, b_); // partial sums for ease of weight calculation std::vector<float> asum(n_), bsum(n_); std::partial_sum(a_.begin(), a_.end(), asum.begin(), std::plus<float>()); std::partial_sum(b_.begin(), b_.end(), bsum.begin(), std::plus<float>()); // create sparse matrix of differences int numDiff = (n_+1)*(n_); float wt; std::vector<float> diffs = std::vector<float>(numDiff); for (int j=1; j<=n_; ++j) { diffs[j] = -1. * std::pow(asum[j-1], 2)/bsum[j-1]; } for (int i=1; i<=n_; ++i) { for (int j=i+1; j<=n_; ++j) { wt = -1. * std::pow(asum[j-1]-asum[i-1], 2)/(bsum[j-1]-bsum[i-1]); diffs[i*n_+j] = wt; } } // std::cerr << "PRECOMPUTES COMPLETE\n"; // source added implicitly via add_edge() // add layers for $T \in \{1, \dots T__{-1}\}$ // std::cerr << "CONSTRUCTING GRAPH\n"; for(int k=1; k<T_; ++k) { for(int j=k; j<(k+per_level_); ++j) { add_edge_and_weight(j, k, std::move(diffs)); } // std::cerr << " LAYER " << k << " OF " << T_-1 << " COMPLETE\n"; } // add sink, must add explicitly float weight; int curr_node = (T_-1) * per_level_ + 1; for (int j=T_-1; j<n_; ++j) { weight = compute_weight(j, n_, diffs); __attribute__((unused)) auto r = boost::add_edge(node_to_int(j, T_-1), curr_node, EdgeWeightProperty(weight), G_); } // std::cerr << "GRAPH CONSTRUCTION COMPLETE\n"; } void PartitionGraph::optimize() { // Glorified bellman-ford call // std::cerr << "COMPUTING SHORTEST PATH\n"; int nb_vertices = boost::num_vertices(G_); boost::property_map<graph_t, float EdgeWeightProperty::*>::type weight_pmap_; weight_pmap_ = boost::get(&EdgeWeightProperty::weight, G_); // init the distance std::vector<float> distance(nb_vertices, (std::numeric_limits<float>::max)()); distance[0] = 0.; // init the predecessors (identity function) std::vector<std::size_t> parent(nb_vertices); for (int i = 0; i < nb_vertices; ++i) parent[i] = i; // bellman-ford __attribute__((unused)) bool r = bellman_ford_shortest_paths(G_, nb_vertices, boost::weight_map(weight_pmap_). distance_map(&distance[0]). predecessor_map(&parent[0]) ); // optimal paths std::list<int> pathlist; int first=0, index = parent.back(); // int pathlist, in reverse order while (index > 0) { pathlist.push_back(index); index = parent[index]; } // node optimalpath std::for_each(pathlist.rbegin(), pathlist.rend(), [this, &first](int a){ std::pair<int, int> node = int_to_node(a); int last = node.first; this->optimalpath_.push_back(std::make_pair(first, last)); first = last; }); optimalpath_.push_back(std::make_pair(first, n_)); int subset_ind = 0; for (auto& node : optimalpath_) { subsets_[subset_ind]= std::vector<int>(); for(int i=node.first; i<node.second; ++i) { subsets_[subset_ind].push_back(priority_sortind_[i]); } subset_ind++; } std::for_each(optimalpath_.begin(), optimalpath_.end(), [this](std::pair<int, int> i) { this->optimalweight_ += this->compute_weight(i.first, i.second); }); // Details /* std::for_each(optimalpath_.begin(), optimalpath_.end(), [](std::pair<int, int> i){ std::cout << "[" << i.first << ", " << i.second << ") --> "; }); std::cout << " >>SINK<< \n"; std::cout << "SORTIND\n"; std::copy(priority_sortind_.begin(), priority_sortind_.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; std::cout << "WEIGHTS\n"; std::for_each(optimalpath_.begin(), optimalpath_.end(), [this](std::pair<int, int> i) { std::cout << "[" << i.first << ", " << i.second << ") : " << this->compute_weight(i.first, i.second) << "\n"; }); std::cout << "SUBSETS\n"; std::cout << "[\n"; std::for_each(subsets_.begin(), subsets_.end(), [](std::vector<int>& subset){ std::cout << "["; std::copy(subset.begin(), subset.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "]\n"; }); std::cout << "]"; */ } std::list<std::pair<int,int>> PartitionGraph::get_optimal_path() const { return optimalpath_; } std::vector<std::vector<int>> PartitionGraph::get_optimal_subsets_extern() const { return subsets_; } float PartitionGraph::get_optimal_weight_extern() const { return optimalweight_; } template <class NameProp> class name_label_writer { public: name_label_writer(NameProp nameprop) : nameprop_(nameprop) {} template <class VertexOrEdge> void operator()(std::ostream& out, const VertexOrEdge& v) const { out << "[label=\"" << nameprop_[v] << "\"]"; } private: NameProp nameprop_; }; template<typename WeightProp> class weight_label_writer { public: weight_label_writer(WeightProp weightprop) : weightprop_(weightprop) {} template<typename VertexOrEdge> void operator()(std::ostream& out, const VertexOrEdge& v) const { out << "[label=\"" << get(weightprop_, v) << "\", color=\"grey\"]"; } private: WeightProp weightprop_; }; void PartitionGraph::write_dot() { int nb_vertices = boost::num_vertices(G_); std::vector<std::string> nameProp(nb_vertices); for(int i=0; i<nb_vertices; ++i) { auto p = int_to_node(i); nameProp[i] = "(" + std::to_string(p.first) + ", " + std::to_string(p.second) + ")"; } auto weightProp = boost::get(&EdgeWeightProperty::weight, G_); using weightPropType = boost::adj_list_edge_property_map<boost::directed_tag, float, float&, unsigned long, EdgeWeightProperty, float EdgeWeightProperty::*>; // Full labeling write_graphviz(std::cout, G_, name_label_writer<std::vector<std::string>>(nameProp), weight_label_writer<weightPropType>(weightProp)); // Only node name labeling // write_graphviz(std::cout, G_, name_label_writer(nameProp)); // No labeling // write_graphviz(std::cout, G_); } std::vector<int> PartitionGraph::get_optimal_path_extern() const { // just flatten everything out std::vector<int> optimalpath; for (auto& node : optimalpath_) { optimalpath.push_back(node.first); optimalpath.push_back(node.second); } return optimalpath; } int PartitionGraph::node_to_int(int i, int j) { // valid for levels 1 through (T-1) return (j-1)*per_level_ + (i-j+1); } std::pair<int,int> PartitionGraph::int_to_node(int m) { // valid for levels 1 through (T-1) int a = 1 + int((m-1)/per_level_); int b = m - (a-1)*per_level_ + a - 1; return std::make_pair(b, a); }
// chunk_manager.cpp #include "chunk_manager.h" #include "math/perlin.h" #include "system/logger.h" #include <algorithm> namespace leap { namespace world { ChunkManager::ChunkManager() = default; ChunkManager::~ChunkManager() = default; Rval ChunkManager::init() { constexpr int32_t WORLD_REAL_WIDTH = WORLD_WIDTH_CHUNKS * CHUNK_EDGE * BLOCK_EDGE; octree_ = std::make_unique<octree::Node<std::size_t>>(octree::v3i32{0, 0, 0}, WORLD_REAL_WIDTH, 2); return Rval::OK; } void ChunkManager::new_terrain() { constexpr float CHUNK_REAL_EDGE = CHUNK_EDGE * BLOCK_EDGE; constexpr float WORLD_REAL_HALF_WIDTH = WORLD_WIDTH_CHUNKS * CHUNK_REAL_EDGE / 2; constexpr float WORLD_REAL_HALF_HEIGHT = WORLD_HEIGHT_CHUNKS * CHUNK_REAL_EDGE / 2; for (int y_chunk = 0; y_chunk < WORLD_HEIGHT_CHUNKS; ++y_chunk) { for (int z_chunk = 0; z_chunk < WORLD_WIDTH_CHUNKS; ++z_chunk) { for (int x_chunk = 0; x_chunk < WORLD_WIDTH_CHUNKS; ++x_chunk) { const math::vec3 loc{ static_cast<float>(x_chunk * CHUNK_REAL_EDGE - WORLD_REAL_HALF_WIDTH + CHUNK_REAL_EDGE / 2), static_cast<float>(y_chunk * CHUNK_REAL_EDGE - WORLD_REAL_HALF_HEIGHT + CHUNK_REAL_EDGE / 2), static_cast<float>(z_chunk * CHUNK_REAL_EDGE - WORLD_REAL_HALF_WIDTH + CHUNK_REAL_EDGE / 2) }; loaded_chunks_.emplace_back().set_location(loc); octree_->put(octree::v3i32{ int32_t(math::floor(loc.x())), int32_t(math::floor(loc.y())), int32_t(math::floor(loc.z())), })->data() = loaded_chunks_.size() - 1; } } } perlin noise{}; for (auto& chunk : loaded_chunks_) { const auto& chunk_loc = chunk.get_location(); for (int x_block = 0; x_block < CHUNK_EDGE; ++x_block) { for (int z_block = 0; z_block < CHUNK_EDGE; ++z_block) { auto x = chunk_loc.x() + x_block; auto z = chunk_loc.x() + z_block; for (int y_block = 0; y_block < CHUNK_EDGE; ++y_block) { auto y = chunk_loc.y() + y_block; auto e = noise({x * 0.08f, y * 0.15f, z * 0.08f}) * 12.0f; const float elevation = 8 + e; if (float(y_block) > elevation) { continue; } chunk.set_active_block(x_block, y_block, z_block, true); chunk.set_block_type(x_block, y_block, z_block, BlockType::Grass); } } } } } Chunk* ChunkManager::get_chunk(const math::vec3& loc) { const auto node = octree_->find(octree::v3i32{ int32_t(math::floor(loc.x())), int32_t(math::floor(loc.y())), int32_t(math::floor(loc.z())), }); if (node == nullptr) { return nullptr; } const auto index = node->data(); LEAP_ASSERT(index >= 0 && index < loaded_chunks_.size()); if (index >= 0 && index < loaded_chunks_.size()) { return &loaded_chunks_[index]; } return nullptr; } }//namespace }//namespace
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 10000 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 int H[MAXN+5]; int W[MAXN+5]; int LIS[MAXN+5]; int LDS[MAXN+5]; int main(int argc, char const *argv[]) { int kase; scanf("%d",&kase); int num,tmp; int A,B; for(int K = 1 ; K <= kase ; K++ ){ scanf("%d",&num); for(int i = 0 ; i < num ; i++ ) scanf("%d",&H[i]); for(int i = 0 ; i < num ; i++ ) scanf("%d",&W[i]); A = B = 0; for(int i = 0 ; i < num ; i++ ){ LIS[i] = LDS[i] = W[i]; for(int j = 0 ; j < i ; j++ ){ if( H[j] < H[i] ) LIS[i] = max(LIS[i],LIS[j]+W[i]); if( H[j] > H[i] ) LDS[i] = max(LDS[i],LDS[j]+W[i]); } A = max(A,LIS[i]); B = max(B,LDS[i]); } if( B > A ) printf("Case %d. Decreasing (%d). Increasing (%d).\n",K,B,A); else printf("Case %d. Increasing (%d). Decreasing (%d).\n",K,A,B); } return 0; }
// Labastida Vázquez Fernando // Práctica 05 #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <stdbool.h> #define MAXSIZE 5 int stack[MAXSIZE]; int top = -1; int myQueue[MAXSIZE]; int front = 0; int rear = -1; int itemCount = 0; int peekSt(); void pop(); void push(int data); int isemptySt(); int isfullSt(); int peekC0(); void insert(int data); int removeElem(); bool isEmptyCo(); bool isFullCo(); int main() { setlocale(LC_ALL, ""); int data; int i; int a = 1, b = 0, k; for(int w = 0; i < 10; i++){ push(b); insert(b); push(a); insert(a); b = b + a; a = a + b; } printf("\nEl contenido del stack es: ["); while (top > 0) { peekSt(); printf("%d, ", stack[top]); pop(); } peekSt(); printf("%d]\n", stack[top]); pop(); // printf("(El stack quedó vacío.)\n"); printf("\nEl contenido de la cola es: ["); while (front < rear) { peekC0(); printf("%d, ", myQueue[front]); removeElem(); } peekC0(); printf("%d]\n", myQueue[front]); removeElem(); // printf("(La cola quedó vacía.)\n"); front = 0; rear = -1; itemCount = 0; } int peekSt() { if (!isemptySt()) { return stack[top]; } else { printf("El stack está vacío, no se puede hacer peek\n"); return -1; } } void push(int data) { if (!isfullSt()) { stack[++top] = data; } else { printf("ERROR stack está lleno, no se puede hacer push\n"); } } int isfullSt() { if (top == MAXSIZE - 1) { return true; } else { return false; } } int isemptySt() { if (top == -1) { return true; } else { return false; } } void pop() { if (!isemptySt()) { top--; } else { printf("El stack está vacío, no se puede hacer pop\n"); } } int peekC0() { if (isEmptyCo()) { printf("La cola está vacía, no se puede hacer peek\n"); return -1; } return myQueue[front]; } int removeElem() { if (isEmptyCo()) { printf("No se puede remover, cola vacía\n"); rear = -1; return -1; } else { int data = myQueue[front++]; itemCount--; return data; } } void insert(int data) { if (rear == MAXSIZE - 1) { rear = -1; } if (isFullCo()) { printf("No se puede insertar, cola llena\n"); rear = -1; } else { myQueue[++rear] = data; itemCount++; } } bool isFullCo() { return itemCount == MAXSIZE; } bool isEmptyCo() { return itemCount == 0; }
#include<iostream> using namespace std; long r[100000],n; bool simulate(long a) { long b; for(int i=0;i<n;i++) { if(i==0)b=r[i]; else b=r[i]-r[i-1]; if(a==b)a--; else if(a<b)return false; } return true; } int main() { int t; cin>>t; for(int j=0;j<t;j++) { long max,ans; cin>>n; for(int i=0;i<n;i++) { cin>>r[i]; if(i==0) max=r[i]; else if((r[i]-r[i-1])>max)max=r[i]-r[i-1]; } if(simulate(max))ans=max; else ans=max+1; printf("Case %d: %d\n",j+1,ans); } return 0; }
#ifndef __SECOMPONENT_H__ #define __SECOMPONENT_H__ #include "SEObject.h" class SEComponent : public SEObject { public: typedef enum { RENDER_COMPONENT, TIMER_COMPONENT, PHYSICS_COMPONENT, ANIMATION_COMPONENT, UI_COMPONENT, AUDIO_COMPONENT, CONTROL_COMPONENT, STATEMACHINE_COMPONENT, NUM_COMPONENTS } tComponent; virtual void update(double dt) = 0; virtual tComponent type() = 0; ~SEComponent() {} protected: SEComponent(tComponent t) : t_(t) {} tComponent t_; }; #endif // __SECOMPONENT_H__
#ifndef __CLIENTINFO_INCLUDED__ #define __CLIENTINFO_INCLUDED__ #include <cstdio> #include <iostream> #include <string> #include <sstream> #include <unistd.h> #include <vector> #include "../Utils/network_utils.h" #include "../Ports/ports.h" #include "../Packet/packet.h" class ClientInfo { private: char *hostName; char *ipAddress; std::vector<std::string> fileNames; static std::vector<ClientInfo> clients; public: ClientInfo(char *hostName,char *ipAddress); ~ClientInfo(); void formatFilesList(const char *message); char* getIpAddress(); char* getHostName(); static std::vector<ClientInfo> getClients(); static void addClient(ClientInfo *info); bool fileFoundInClient(std::string File); static std::string getClientsByFileName(std::string fileName); static bool removeClient(char* HostName, char *IpAddress); }; #endif
#include "book.h" Book::Book() { buyTree = NULL; sellTree = NULL; lowSell = NULL; highBuy = NULL; } void Book::AddOrder(int timestamp,char id, bool isBid, int price, int size) { Order * order = new Order(timestamp, id, isBid, price, size); if (isBid){// buy order if (buyTree != NULL){ buyTree->Insert(order); if (highBuy!=NULL){ if (price > highBuy->price){ highBuy = order->parentLimit; } } else{ highBuy = order->parentLimit; } } else{ buyTree = new Limit(order,this); highBuy = order->parentLimit; } } else{// sell order if (sellTree != NULL){ sellTree->Insert(order); if (lowSell!=NULL){ if (price < lowSell->price){ lowSell = order->parentLimit; } } else{ lowSell = order->parentLimit; } } else{ sellTree = new Limit(order,this); lowSell = order->parentLimit; } } // update maps orderMap[id] = order; priceMap[price] = order->parentLimit; } void Book::ReduceOrder(int timestamp,char id, int size) { Order * order = orderMap[id]; Limit * limit = order->parentLimit; assert(order!=NULL); assert(limit!=NULL); order->Reduce(size); if (order->size <= 0){ //order depleted int price = order->price; delete order; orderMap.erase(id); if (limit->volume<=0){ // limit has been depleted assert(limit->volume == 0);// just checking // correct running min/maxes if (limit==lowSell){ lowSell = limit->parent; } if (limit==highBuy){ highBuy = limit->parent; } Limit * y = limit->Remove(); // returns node that was spliced out delete y; priceMap.erase(price); } } } int Book::Quote(int required, bool buy){ Limit * x = GetBestOffer(); int cost = 0; while (required>0 && x != NULL) { std::cout<<required<<','; if (required > x->volume){ required -= x->volume; cost += x->volume*x->price; x = x->Succesor(); } else{ cost += required*x->price; required = 0; } } std::cout<<std::endl; if (required <= 0){ return cost; } else{ return -1; } } int Book::GetVolumeAtLimit(int x){ return priceMap[x]->volume; } Limit * Book::GetBestBid(){ return highBuy; } Limit * Book::GetBestOffer(){ return lowSell; }
#ifndef PICTURESHRINKER_H #define PICTURESHRINKER_H #include <QThread> #include <QString> class PictureShrinker : public QThread { Q_OBJECT public: explicit PictureShrinker(QObject *parent = 0); void setPath(QString path); void setSavePath(QString path); void setScale(int widthPercent, int heightPercent); signals: void error(QString errorText); void pictureScaled(void); public slots: protected: virtual void run(); protected: QString _path; QString _savePath; int _widthPercent; int _heightPercent; }; #endif // PICTURESHRINKER_H
//Accepted Solution. Time- 0.090s #include <bits/stdc++.h> using namespace std; #define ll long long #define vll vector<ll> class SegmentTree { // the segment tree is stored like a heap array private: vll st, A; ll n; ll left (ll p) { return p << 1; } // same as binary heap operations ll right(ll p) { return (p << 1) + 1; } void build(ll p, ll L, ll R) { // O(n) if (L == R) // as L == R, either one is fine st[p] = A[L]; else { // recursively compute the values build(left(p) , L , (L + R) / 2); build(right(p), ((L + R) / 2) + 1, R ); ll p1 = st[left(p)], p2 = st[right(p)]; st[p] = p1*p2; } } ll rsq(ll p, ll L, ll R, ll i, ll j) { // O(log n) if (i > j) return 1; if(i==L && j==R) return st[p]; ll m=(L+R)/2; return rsq(left(p),L,m,i,min(j,m))*rsq(right(p),m+1,R,max(i,m+1),j); } void update(ll p, ll L, ll R, ll pos, ll val){ if (L == R) st[p] = val; else{ ll m=(L+R)/2; if(pos<=m) update(left(p),L,m,pos,val); else update(right(p),m+1,R,pos,val); ll p1 = st[left(p)], p2 = st[right(p)]; st[p] = p1*p2; } } public: SegmentTree(const vll &_A) { A = _A; n = (int)A.size(); // copy content for local usage st.assign(4 * n, 0); // create large enough vector of zeroes build(1, 0, n - 1); // recursive build } ll rsq(ll i, ll j) { return rsq(1, 0, n - 1, i, j); } // overloading void update(ll pos, ll val) {return update(1,0,n-1,pos,val); } }; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n,k,a,b; char ch; while(cin>>n>>k) { vll v; for(int i=0;i<n;i++) { cin>>a; if(a==0) v.push_back(0); else if(a>0) v.push_back(1); else v.push_back(-1); } SegmentTree st(v); for(int i=0;i<k;i++) { cin>>ch>>a>>b; if(ch=='C') { if(b==0) st.update(a-1,0); else if(b>0) st.update(a-1,1); else st.update(a-1,-1); } else { ll p=st.rsq(a-1,b-1); if(p==0) cout<<"0"; else if(p==1) cout<<"+"; else cout<<"-"; } } cout<<"\n"; } }
//Accepted. Time-0.010s #include <bits/stdc++.h> using namespace std; #define ll long long #define vll vector<ll> int main() { ll n,k,a; while(cin>>n) { if(n==0) break; vll v; for(int i=0;i<n;i++) { cin>>a; if(a) v.push_back(a); } int k=v.size(); if(!k) cout<<"0\n"; else { for(int i=0;i<k;i++) { if(i) cout<<" "; cout<<v[i]; } cout<<"\n"; } } }
#pragma once #include "afxdialogex.h" #include "Talk2Me.h" #include "afxcmn.h" // CSignup 对话框 class CSignup : public CDialogEx { DECLARE_DYNAMIC(CSignup) public: CSignup(CWnd* pParent = NULL); // 标准构造函数 virtual ~CSignup(); // 对话框数据 enum { IDD = IDD_SIGNUP_DLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); bool IsValidInput(CString); bool m_test; CString m_username; CString m_pwd1; CString m_pwd; };
/*********************************************************************** Desc: Noise Mesh Renderer (D3D) ************************************************************************/ #include "Noise3D.h" using namespace Noise3D; IRenderModuleForMesh::IRenderModuleForMesh() { } IRenderModuleForMesh::~IRenderModuleForMesh() { ReleaseCOM(m_pFX_Tech_DrawMesh); } void IRenderModuleForMesh::RenderMeshes() { ICamera* const tmp_pCamera = GetScene()->GetCamera(); mFunction_RenderMeshInList_UpdateRarely(); mFunction_RenderMeshInList_UpdatePerFrame(); m_pRefRI->UpdateCameraMatrix(tmp_pCamera); //for every mesh for (UINT i = 0; i<mRenderList_Mesh.size(); i++) { IMesh* const pMesh = mRenderList_Mesh.at(i); mFunction_RenderMeshInList_UpdatePerObject(pMesh); //IA/OM settings m_pRefRI->SetInputAssembler(IRenderInfrastructure::NOISE_VERTEX_TYPE::DEFAULT, pMesh->m_pVB_Gpu, pMesh->m_pIB_Gpu, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_pRefRI->SetRasterState(pMesh->GetFillMode(), pMesh->GetCullMode()); m_pRefRI->SetBlendState(pMesh->GetBlendMode()); m_pRefRI->SetSampler(IShaderVariableManager::NOISE_SHADER_VAR_SAMPLER::DEFAULT_SAMPLER, NOISE_SAMPLERMODE::LINEAR); m_pRefRI->SetDepthStencilState(true); m_pRefRI->SetRtvAndDsv(IRenderInfrastructure::NOISE_RENDER_STAGE::NORMAL_DRAWING); //every mesh subset(one for each material) UINT meshSubsetCount = pMesh->mSubsetInfoList.size(); for (UINT j = 0;j < meshSubsetCount;j++) { //subset info UINT currSubsetIndicesCount = pMesh->mSubsetInfoList.at(j).primitiveCount * 3; UINT currSubsetStartIndex = pMesh->mSubsetInfoList.at(j).startPrimitiveID * 3; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //ATTENTION!! : each subset might have different materials, hences different //texture combinations. In consideration of efficiency, texture operations will be //turned on/off by UNIFORM bool in shader(so each mapping will be turn on/off //in shader compilation stage). N switches of multiple mapping will produce 2^N //passes for the c++ host program to choose. //'passID' will be computed to choose appropriate pass. ID3DX11EffectPass* pPass = mFunction_RenderMeshInList_UpdatePerSubset(pMesh,j); pPass->Apply(0, g_pImmediateContext); g_pImmediateContext->DrawIndexed(currSubsetIndicesCount, currSubsetStartIndex, 0); } } } void IRenderModuleForMesh::AddToRenderQueue(IMesh* obj) { mRenderList_Mesh.push_back(obj); } /*********************************************************** PROTECTED ************************************************************/ void IRenderModuleForMesh::ClearRenderList() { mRenderList_Mesh.clear(); } bool IRenderModuleForMesh::Initialize(IRenderInfrastructure * pRI, IShaderVariableManager * pShaderVarMgr) { m_pRefRI = pRI; m_pRefShaderVarMgr = pShaderVarMgr; m_pFX_Tech_DrawMesh = g_pFX->GetTechniqueByName("DrawMesh"); return true; } /*********************************************************** PRIVATE ***********************************************************/ void IRenderModuleForMesh::mFunction_RenderMeshInList_UpdateRarely() { //From 2018.1.14 on, static lights are used to bake static lights(light maps) //and not sent to GPU for lighting }; void IRenderModuleForMesh::mFunction_RenderMeshInList_UpdatePerFrame() { //-------Update Dynamic Light------- ILightManager* tmpLightMgr = GetScene()->GetLightMgr(); UINT dirLightCount = tmpLightMgr->GetLightCount(NOISE_LIGHT_TYPE_DYNAMIC_DIR); UINT pointLightCount = tmpLightMgr->GetLightCount(NOISE_LIGHT_TYPE_DYNAMIC_POINT); UINT spotLightCount = tmpLightMgr->GetLightCount(NOISE_LIGHT_TYPE_DYNAMIC_SPOT); m_pRefShaderVarMgr->SetInt(IShaderVariableManager::NOISE_SHADER_VAR_SCALAR::DYNAMIC_LIGHT_ENABLED, tmpLightMgr->IsDynamicLightingEnabled()); m_pRefShaderVarMgr->SetInt(IShaderVariableManager::NOISE_SHADER_VAR_SCALAR::DYNAMIC_DIRLIGHT_COUNT, dirLightCount); m_pRefShaderVarMgr->SetInt(IShaderVariableManager::NOISE_SHADER_VAR_SCALAR::DYNAMIC_POINTLIGHT_COUNT, pointLightCount); m_pRefShaderVarMgr->SetInt(IShaderVariableManager::NOISE_SHADER_VAR_SCALAR::DYNAMIC_SPOTLIGHT_COUNT, spotLightCount); for (UINT i = 0; i<(dirLightCount); i++) { m_pRefShaderVarMgr->SetDynamicDirLight(i, tmpLightMgr->GetDirLightD(i)->GetDesc()); } for (UINT i = 0; i<(pointLightCount); i++) { m_pRefShaderVarMgr->SetDynamicPointLight(i, tmpLightMgr->GetPointLightD(i)->GetDesc()); } for (UINT i = 0; i<(spotLightCount); i++) { m_pRefShaderVarMgr->SetDynamicSpotLight(i, tmpLightMgr->GetSpotLightD(i)->GetDesc()); } }; ID3DX11EffectPass* IRenderModuleForMesh::mFunction_RenderMeshInList_UpdatePerSubset(IMesh* const pMesh,UINT subsetID) { //we dont accept invalid material ,but accept invalid texture IScene* pScene = GetScene(); ITextureManager* pTexMgr = pScene->GetTextureMgr(); IMaterialManager* pMatMgr = pScene->GetMaterialMgr(); IMeshManager* pMeshMgr = pScene->GetMeshMgr(); //Get Material ID by unique name N_UID currSubsetMatName = pMesh->mSubsetInfoList.at(subsetID).matName; bool IsMatNameValid = pMatMgr->ValidateUID(currSubsetMatName); //if material ID == INVALID_MAT_ID , then we should use default mat defined in mat mgr //then we should check if its child textureS are valid too N_MaterialDesc tmpMat; if (IsMatNameValid== false) { WARNING_MSG("IRenderer : material UID not valid !"); pMatMgr->GetDefaultMaterial()->GetDesc(tmpMat); } else { pMatMgr->GetMaterial(currSubsetMatName)->GetDesc(tmpMat); } //update basic material info m_pRefShaderVarMgr->SetMaterial(tmpMat); //Validate textures ID3D11ShaderResourceView* tmp_pSRV = nullptr; ITexture* pDiffMap = pTexMgr->GetTexture(tmpMat.diffuseMapName); ITexture* pNormalMap = pTexMgr->GetTexture(tmpMat.normalMapName); ITexture* pSpecMap = pTexMgr->GetTexture(tmpMat.specularMapName); ITexture* pEnvMap = pTexMgr->GetTexture(tmpMat.environmentMapName); bool isDiffuseMapValid = false; bool isNormalMapValid = false; bool isSpecularMapValid = false; bool isEnvMapValid = false; //first validate if ID is valid (within range / valid ID) valid== return original texID if(pDiffMap) isDiffuseMapValid = pDiffMap->IsTextureType(NOISE_TEXTURE_TYPE_COMMON); else isDiffuseMapValid = false; if (pNormalMap) isNormalMapValid = pNormalMap->IsTextureType(NOISE_TEXTURE_TYPE_COMMON); else isNormalMapValid = false; if (pSpecMap) isSpecularMapValid = pSpecMap->IsTextureType(NOISE_TEXTURE_TYPE_COMMON); else isSpecularMapValid = false; if (pEnvMap) isEnvMapValid = pEnvMap->IsTextureType(NOISE_TEXTURE_TYPE_CUBEMAP); else isEnvMapValid = false; //update textures, bound corresponding ShaderResourceView to the pipeline //if tetxure is valid ,then set diffuse map if (isDiffuseMapValid) { auto pSRV = m_pRefRI->GetTextureSRV(pDiffMap); m_pRefShaderVarMgr->SetTexture(IShaderVariableManager::NOISE_SHADER_VAR_TEXTURE::DIFFUSE_MAP, pSRV); } //if texture is valid ,then set normal map if (isNormalMapValid) { auto pSRV = m_pRefRI->GetTextureSRV(pNormalMap); m_pRefShaderVarMgr->SetTexture(IShaderVariableManager::NOISE_SHADER_VAR_TEXTURE::NORMAL_MAP, pSRV); } //if texture is valid ,then set specular map if (isSpecularMapValid) { auto pSRV = m_pRefRI->GetTextureSRV(pSpecMap); m_pRefShaderVarMgr->SetTexture(IShaderVariableManager::NOISE_SHADER_VAR_TEXTURE::SPECULAR_MAP, pSRV); } //if texture is valid ,then set environment map (cube map) if (isEnvMapValid) { auto pSRV = m_pRefRI->GetTextureSRV(pEnvMap); m_pRefShaderVarMgr->SetTexture(IShaderVariableManager::NOISE_SHADER_VAR_TEXTURE::CUBE_MAP, pSRV); } //return ID3DX11EffectPass interface to choose appropriate shader //each bit for each switch, then bitwise-AND all the switches ID3DX11EffectPass* pPass = nullptr; //NOTE that: special reneder technique like NORMAL MAPPING can only be //implemented in TANGENT SPACE bool isPerVertexLighting = (pMesh->GetShadeMode() == NOISE_SHADEMODE_GOURAUD); if (isPerVertexLighting) { if (isDiffuseMapValid) { pPass = m_pFX_Tech_DrawMesh->GetPassByName("perVertex_enableDiffMap"); return pPass; } else { pPass = m_pFX_Tech_DrawMesh->GetPassByName("perVertex_disableDiffMap"); return pPass; } } //determine per-pixel drawing pass (2^switchCount shaders are caches) constexpr int perPixelRenderSwitchCount = 4; int renderEffectSwitches[perPixelRenderSwitchCount] = { isDiffuseMapValid, isNormalMapValid, isSpecularMapValid, isEnvMapValid }; uint32_t passID = 0; for (uint32_t switchID = 0; switchID < perPixelRenderSwitchCount; ++switchID) { passID |= (renderEffectSwitches[switchID] << switchID); } pPass = m_pFX_Tech_DrawMesh->GetPassByIndex(passID);//name "perPixel_xxx" return pPass; }; void IRenderModuleForMesh::mFunction_RenderMeshInList_UpdatePerObject(IMesh* const pMesh) { //update world/worldInv matrix NMATRIX worldMat,worldInvTransposeMat; pMesh->GetWorldMatrix(worldMat, worldInvTransposeMat); m_pRefShaderVarMgr->SetMatrix(IShaderVariableManager::NOISE_SHADER_VAR_MATRIX::WORLD, worldMat); m_pRefShaderVarMgr->SetMatrix(IShaderVariableManager::NOISE_SHADER_VAR_MATRIX::WORLD_INV_TRANSPOSE, worldInvTransposeMat); };
#ifndef IMAGE_ALGORITHM_H #define IMAGE_ALGORITHM_H #include <QList> #include <QMap> #include <QVariant> #include <QString> #include <opencv2/core/core.hpp> class ImageAlgorithm { public: virtual Mat exec(const QList<Mat> &images, const QMap<QString, QVariant> &params) = 0; }; #endif
#include <iostream> #include <vector> void vect_elem(std::vector<int> &myvector) { myvector.push_back(4); for (int i = 0; i < myvector.size(); i++) { std::cout << myvector[i] << " \t "; //<< std::endl; } std::cout << "\n"; } int main() { std::vector<int> myvector = {1,2,3}; vect_elem(myvector); vect_elem(myvector); vect_elem(myvector); vect_elem(myvector); vect_elem(myvector); //myvector.pop_back(); //std::cout << myvector.data() << ""; }
/* * License does not expire. * Can be distributed in infinitely projects * Can be distributed and / or packaged as a code or binary product (sublicensed) * * Commercial use allowed under the following conditions : * - Crediting the Author * * Can modify source-code */ /* * File: Water.cpp * Author: Suirad <darius-suirad@gmx.de> * * Created on 23. Juni 2018, 20:59 */ #include "Water.h" #include "Window.h" Water::Water(float quality) { reflectionFbo = new Fbo(Dimension(window::getWindowSize().x * quality, window::getWindowSize().y * quality), false); refractionFbo = new Fbo(Dimension(window::getWindowSize().x * quality, window::getWindowSize().y * quality), false); } Water::~Water() { delete reflectionFbo; delete refractionFbo; }
#ifndef GENERATE_BINDINGS #include <functional> #include <string> #include <utility> #include <vector> #endif class capture_groups { public: capture_groups(); int size(); const char* get_match(int index); #ifndef GENERATE_BINDINGS bool search(std::string, std::regex); private: std::smatch d_matches; #endif }; typedef void (*callback_function)(capture_groups*, void*); typedef void (*default_callback)(const char*, void*); #ifndef GENERATE_BINDINGS using cb_func = std::function<void(capture_groups*, void*)>; using default_func = std::function<void(const char*, void*)>; using path_object = std::pair<std::string, cb_func>; #endif class uri_router { public: uri_router(); void register_path(const char* rgx_str, callback_function cb); void register_default(default_callback cb); bool match_path(const char* path, void* response); #ifndef GENERATE_BINDINGS void register_path(std::string, cb_func); void register_default(default_func); bool match_path(std::string, void*); private: void default_default_cb(const char*, void*); std::vector<path_object> d_map; default_func d_default_handler; #endif };
#pragma once #include <Poco/Timespan.h> #include <Poco/Timestamp.h> namespace BeeeOn { /** * Interval between two timestamps. The start must always be * less or equal to end. The duration of the interval is * defined as: * * m_end - m_start * * The m_end is not part of the interval. */ class TimeInterval { public: TimeInterval(const Poco::Timestamp &start, const Poco::Timestamp &end); ~TimeInterval(); /** * Create interval for past range from the given end reference * timepoint. Examples: * * <pre> * TimeInterval last5Min = TimeInterval::past(5 * Timespan::MINUTES); * TimeInterval lastHourOfYear = TimeInterval::past( * 1 * TimeInterval::HOURS, * Timestamp::fromEpochTime(1483225200)); * <pre> * * The last5Min is interval lasting 5 minutes just before now. * The lastHourOfYear is an interval representing the last hour of year 2016. */ static TimeInterval past(const Poco::Timespan &range, const Poco::Timestamp &end = Poco::Timestamp()); /** * The time interval is empty (start == end). */ bool isEmpty() const; /** * The time interval both starts and ends before * the given timestampt at. */ bool isBefore(const Poco::Timestamp &at) const; Poco::Timestamp start() const; Poco::Timestamp end() const; const Poco::Timestamp &start(); const Poco::Timestamp &end(); private: Poco::Timestamp m_start; Poco::Timestamp m_end; }; }
#include "FluViruss.h" #include <iostream> #include <cstdlib> #include <ctime> #include <list> using namespace std; int bl = 0x0000ff; int red = 0xff0000; FluViruss::FluViruss() { DoBorn(); this->m_resistance = InitResistance(); } FluViruss::FluViruss(int color, char * dna, int resistance) : Viruss(dna, resistance) { this->m_color = color; this->m_dna = dna; this->m_resistance = resistance; } FluViruss::FluViruss(const FluViruss * fluviruss) { this->m_color = fluviruss->m_color; this->m_dna = fluviruss->m_dna; this->m_resistance = fluviruss->m_resistance; } FluViruss::~FluViruss() { cout << "Destroy Flu Virus" << endl; } void FluViruss::SetColor(int color) { this->m_color = color; } int FluViruss::GetColor() { return this->m_color; } void FluViruss::DoBorn() { LoadADNInformation(); cout << "ADN: " << this->m_dna << endl; int ran = rand() % 2 + 1; cout << "COLOR: "; if (ran == 1) { this->m_color = bl; cout << "Blue" << endl; } else { this->m_color = red; cout << "Red" << endl; } } list<Viruss*> FluViruss::DoClone() { list<Viruss*> vrclone; Viruss *vr = new FluViruss(this); vrclone.push_back(vr); cout << "==> Clone Flu Virus" << endl; return vrclone; } void FluViruss::DoDie() { //delete[] this->m_dna; delete this; cout << "==> Flu Virus die" << endl; } int FluViruss::InitResistance() { int min = 10; if (this->m_color == bl) { int max = 15; this->m_resistance = rand() % (max - min + 1) + min; cout << "RESISTANCE (10-15): " << this->m_resistance << endl; } else if (this->m_color == red) { int max = 20; this->m_resistance = rand() % (max - min + 1) + min; cout << "RESISTANCE (10-20): " << this->m_resistance << endl; } else { cout << "Error!" << endl; } return this->m_resistance; }
/* * Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com> * Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com> * Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com> * Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com> * Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net> * Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com> * Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "dtoin/InstanceReaderHumanReadable.hh" #include <map> #include <sstream> #include <string> #include <vector> #include <boost/foreach.hpp> #include <gtest/gtest.h> using namespace std; //Fixture qui permet de d'acceder aux methode protected class InstanceReaderHumanReadableFixture : public InstanceReaderHumanReadable, public testing::Test {}; TEST_F(InstanceReaderHumanReadableFixture, getNextLine){ ostringstream oss_l; string ligne1_l("Ma premiere ligne"), ligne2_l("seconde ligne"); oss_l << ligne1_l << endl << " " << endl << ligne2_l; istringstream iss_l(oss_l.str()); EXPECT_EQ(ligne1_l, getNextLine(iss_l)); EXPECT_EQ(ligne2_l, getNextLine(iss_l)); EXPECT_EQ("", getNextLine(iss_l)); EXPECT_EQ("", getNextLine(iss_l)); } TEST_F(InstanceReaderHumanReadableFixture, checkSectionTitle){ vector<pair<string, string> > vLignesPourries_l; map<string, string> mLignesOk_l; mLignesOk_l["===== titreA ======"] = "titreA"; mLignesOk_l["===== titreA ======"] = "TitreA"; mLignesOk_l["=====TitreB====== "] = "titreB"; vLignesPourries_l.push_back(make_pair("==== titre=====", "titre")); //Pas assez de = en tete vLignesPourries_l.push_back(make_pair("=====titre5=====", "titre5")); //contient un chiffre vLignesPourries_l.push_back(make_pair(" ===== mon titre====", "mon titre")); //contient une espace vLignesPourries_l.push_back(make_pair("=====titreC====", "titreD")); vLignesPourries_l.push_back(make_pair("=====titreC====", "titreA")); for ( map<string, string>::iterator it_l=mLignesOk_l.begin() ; it_l != mLignesOk_l.end() ; it_l++ ){ EXPECT_NO_THROW(checkSectionTitle(it_l->first, it_l->second)) << it_l->first << " vs " << it_l->second; } for ( vector<pair<string, string> >::iterator it_l=vLignesPourries_l.begin() ; it_l != vLignesPourries_l.end() ; it_l++ ){ EXPECT_ANY_THROW(checkSectionTitle(it_l->first, it_l->second)) << it_l->first << " vs " << it_l->second; } } TEST_F(InstanceReaderHumanReadableFixture, checkSubTitle){ EXPECT_NO_THROW(checkSubTitle("====Ressource 1/666====", "Ressource", 1, 666)); EXPECT_NO_THROW(checkSubTitle("==== macHine 3 / 7 ===", "MAchine", 3, 7)); //Limite de la permissivite EXPECT_ANY_THROW(checkSubTitle("===Ressource 1/666====", "Ressource", 1, 666)); EXPECT_ANY_THROW(checkSubTitle("====Ressource 1/666====", "Machine", 1, 666)); EXPECT_ANY_THROW(checkSubTitle("====Ressource 1/666====", "Ressource", 2, 666)); EXPECT_ANY_THROW(checkSubTitle("====Ressource 1/666====", "Ressource", 1, 42)); } TEST_F(InstanceReaderHumanReadableFixture, readQuantite){ EXPECT_EQ(2, readQuantite("quantite : 2")); EXPECT_EQ(4, readQuantite(" quantite: 4 ")); EXPECT_ANY_THROW(readQuantite("uantite : 4")); EXPECT_ANY_THROW(readQuantite("quantite : 4 2")); EXPECT_ANY_THROW(readQuantite("quantite 4")); } TEST_F(InstanceReaderHumanReadableFixture, readCarac){ EXPECT_EQ(69, readCarac(" * myValue : 69", "myValue")); EXPECT_EQ(69, readCarac(" * myValue : 69 ", "myvalue")); EXPECT_EQ(1337, readCarac(" * myValue : 1337", "myValue")); EXPECT_ANY_THROW(readCarac(" * myValue : 69", "myValu")); EXPECT_ANY_THROW(readCarac(" * myValue : ", "myValue")); EXPECT_ANY_THROW(readCarac(" * myValue : 42 37", "myValue")); } TEST_F(InstanceReaderHumanReadableFixture, readListe){ vector<int> v1_l; v1_l.push_back(19); v1_l.push_back(85); EXPECT_EQ(v1_l, readListe(" * mesValos : 19 85", "mesvalos")); EXPECT_ANY_THROW(readListe(" * mesValos : 19 85", "myvalue")); }
#include "Lance.h" Lance::Lance(string name, int damages, int hit, int range, int crit, int worth, int uses, WeaponType type):PhysicalWeapon(name, damages, hit, range, crit, worth, uses , type) { //ctor } Lance::~Lance() { //dtor } Lance::Lance(const Lance& other):PhysicalWeapon(other) { //copy ctor } Lance& Lance::operator=(const Lance& rhs) { if (this == &rhs) return *this; // handle self assignment PhysicalWeapon::operator=(rhs); return *this; } Lance* Lance::clone()const { return new Lance(*this); } //Methode qui determine la chance que possede le premiere caractere de toucher le second float Lance::strategyAccuracy(const Character& att, const Character& def)const { //basic formula float accuracy = PhysicalWeapon::strategyAccuracy(att, def); //Weapon Triangle Advantage if(def.getWeapon()->TYPE == WeaponType::sword) accuracy+=5; //Weapon Triangle Disadvantage else if(def.getWeapon()->TYPE == WeaponType::axe) accuracy-=5; return accuracy; }
#ifndef WIDGETCONTAINER_HH_ #define WIDGETCONTAINER_HH_ #include <pgwidget.h> /** This class is used to create word containers in the scrolling hypothesis * view. This way all morphemes are in the same unite rectangle and it also * enables the possibility to force word breaks. */ class WidgetContainer : public PG_Widget { public: /** Constructs a container widget. * \param parent Parent widget. * \param x X coordinate of the left border of the widget. * \param y Y coordinate of the top border of the widget. * \param background Background color of the container. */ WidgetContainer(PG_Widget *parent, Sint16 x, Sint16 y, const PG_Color &background); virtual ~WidgetContainer() { }; /** Adds a child into the widget. Resizes so that all widgets fit in the * container. * \param item Widget to add to the container. */ virtual void AddChild(PG_Widget *item); /** Removes a widget from the container. Resizes so that all widgets fit in * the container but isn't too big. * \param item Widget to remove. */ virtual bool RemoveChild(PG_Widget *item); private: /** Resizes the container. */ void resize(Uint16 width, Uint16 height); /** Calculates and resizes the container so that all widgets fit in it but it * isn't oo big. */ void calculate_size(); Uint32 m_background_color; //!< Background color. }; #endif /*WIDGETCONTAINER_HH_*/
// Created on: 1994-03-18 // Created by: Bruno DUMORTIER // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomAPI_ExtremaCurveCurve_HeaderFile #define _GeomAPI_ExtremaCurveCurve_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <Extrema_ExtCC.hxx> #include <GeomAdaptor_Curve.hxx> #include <gp_Pnt.hxx> class Geom_Curve; //! Describes functions for computing all the extrema //! between two 3D curves. //! An ExtremaCurveCurve algorithm minimizes or //! maximizes the distance between a point on the first //! curve and a point on the second curve. Thus, it //! computes start and end points of perpendiculars //! common to the two curves (an intersection point is //! not an extremum unless the two curves are tangential at this point). //! Solutions consist of pairs of points, and an extremum //! is considered to be a segment joining the two points of a solution. //! An ExtremaCurveCurve object provides a framework for: //! - defining the construction of the extrema, //! - implementing the construction algorithm, and //! - consulting the results. //! Warning //! In some cases, the nearest points between two //! curves do not correspond to one of the computed //! extrema. Instead, they may be given by: //! - a limit point of one curve and one of the following: //! - its orthogonal projection on the other curve, //! - a limit point of the other curve; or //! - an intersection point between the two curves. class GeomAPI_ExtremaCurveCurve { public: DEFINE_STANDARD_ALLOC //! Constructs an empty algorithm for computing //! extrema between two curves. Use an Init function //! to define the curves on which it is going to work. Standard_EXPORT GeomAPI_ExtremaCurveCurve(); //! Computes the extrema between the curves C1 and C2. Standard_EXPORT GeomAPI_ExtremaCurveCurve(const Handle(Geom_Curve)& C1, const Handle(Geom_Curve)& C2); //! Computes the portion of the curve C1 limited by the two //! points of parameter (U1min,U1max), and //! - the portion of the curve C2 limited by the two //! points of parameter (U2min,U2max). //! Warning //! Use the function NbExtrema to obtain the number //! of solutions. If this algorithm fails, NbExtrema returns 0. Standard_EXPORT GeomAPI_ExtremaCurveCurve(const Handle(Geom_Curve)& C1, const Handle(Geom_Curve)& C2, const Standard_Real U1min, const Standard_Real U1max, const Standard_Real U2min, const Standard_Real U2max); //! Initializes this algorithm with the given arguments //! and computes the extrema between the curves C1 and C2 Standard_EXPORT void Init (const Handle(Geom_Curve)& C1, const Handle(Geom_Curve)& C2); //! Initializes this algorithm with the given arguments //! and computes the extrema between : //! - the portion of the curve C1 limited by the two //! points of parameter (U1min,U1max), and //! - the portion of the curve C2 limited by the two //! points of parameter (U2min,U2max). //! Warning //! Use the function NbExtrema to obtain the number //! of solutions. If this algorithm fails, NbExtrema returns 0. Standard_EXPORT void Init (const Handle(Geom_Curve)& C1, const Handle(Geom_Curve)& C2, const Standard_Real U1min, const Standard_Real U1max, const Standard_Real U2min, const Standard_Real U2max); //! Returns the number of extrema computed by this algorithm. //! Note: if this algorithm fails, NbExtrema returns 0. Standard_EXPORT Standard_Integer NbExtrema() const; Standard_EXPORT operator Standard_Integer() const; //! Returns the points P1 on the first curve and P2 on //! the second curve, which are the ends of the //! extremum of index Index computed by this algorithm. //! Exceptions //! Standard_OutOfRange if Index is not in the range [ //! 1,NbExtrema ], where NbExtrema is the //! number of extrema computed by this algorithm. Standard_EXPORT void Points (const Standard_Integer Index, gp_Pnt& P1, gp_Pnt& P2) const; //! Returns the parameters U1 of the point on the first //! curve and U2 of the point on the second curve, which //! are the ends of the extremum of index Index computed by this algorithm. //! Exceptions //! Standard_OutOfRange if Index is not in the range [ //! 1,NbExtrema ], where NbExtrema is the //! number of extrema computed by this algorithm. Standard_EXPORT void Parameters (const Standard_Integer Index, Standard_Real& U1, Standard_Real& U2) const; //! Computes the distance between the end points of the //! extremum of index Index computed by this algorithm. //! Exceptions //! Standard_OutOfRange if Index is not in the range [ //! 1,NbExtrema ], where NbExtrema is the //! number of extrema computed by this algorithm. Standard_EXPORT Standard_Real Distance (const Standard_Integer Index) const; //! Returns True if the two curves are parallel. Standard_Boolean IsParallel() const { return myExtCC.IsParallel(); } //! Returns the points P1 on the first curve and P2 on //! the second curve, which are the ends of the shortest //! extremum computed by this algorithm. //! Exceptions StdFail_NotDone if this algorithm fails. Standard_EXPORT void NearestPoints (gp_Pnt& P1, gp_Pnt& P2) const; //! Returns the parameters U1 of the point on the first //! curve and U2 of the point on the second curve, which //! are the ends of the shortest extremum computed by this algorithm. //! Exceptions StdFail_NotDone if this algorithm fails. Standard_EXPORT void LowerDistanceParameters (Standard_Real& U1, Standard_Real& U2) const; //! Computes the distance between the end points of the //! shortest extremum computed by this algorithm. //! Exceptions StdFail_NotDone if this algorithm fails. Standard_EXPORT Standard_Real LowerDistance() const; Standard_EXPORT operator Standard_Real() const; //! return the algorithmic object from Extrema const Extrema_ExtCC& Extrema() const; //! set in <P1> and <P2> the couple solution points //! such a the distance [P1,P2] is the minimum. taking in account //! extremity points of curves. Standard_EXPORT Standard_Boolean TotalNearestPoints (gp_Pnt& P1, gp_Pnt& P2); //! set in <U1> and <U2> the parameters of the couple //! solution points which represents the total nearest //! solution. Standard_EXPORT Standard_Boolean TotalLowerDistanceParameters (Standard_Real& U1, Standard_Real& U2); //! return the distance of the total nearest couple solution //! point. //! if <myExtCC> is not done Standard_EXPORT Standard_Real TotalLowerDistance(); private: Standard_EXPORT void TotalPerform(); Standard_Boolean myIsDone; Standard_Integer myIndex; Extrema_ExtCC myExtCC; GeomAdaptor_Curve myC1; GeomAdaptor_Curve myC2; Standard_Boolean myTotalExt; Standard_Boolean myIsInfinite; Standard_Real myTotalDist; gp_Pnt myTotalPoints[2]; Standard_Real myTotalPars[2]; }; #include <GeomAPI_ExtremaCurveCurve.lxx> #endif // _GeomAPI_ExtremaCurveCurve_HeaderFile
#include "startdialog.hh" #include "ui_startdialog.h" #include "gamewindow.hh" extern gameWindow *gWindow; startDialog::startDialog(QWidget *parent) : QDialog(parent), ui(new Ui::startDialog) { ui->setupUi(this); } startDialog::~startDialog() { delete ui; } //void startDialog::startGameWindow() //{ // newGameWindow = new gameWindow; // newGameWindow->show(); // this->hide(); //} void startDialog::on_exitButton_clicked() { QCoreApplication::quit(); } void startDialog::on_startButton_clicked() { numberOfPawns = ui->pawnsSpinBox->value(); gWindow = new gameWindow(); gWindow->show(); this->hide(); }
#include "service_thread.hpp" #include "utils/exception.hpp" #include "utils/time_utils.hpp" #include "utils/log.hpp" #include "utils/assert.hpp" using namespace std; using namespace chrono; namespace nora { mutex service_thread::timer_counts_lock_; map<string, int> service_thread::timer_counts_; service_thread::service_thread(const string& name) : name_(name), isw_(make_unique<ba::io_service::work>(is_)), stop_(false) { } void service_thread::start() { t_ = make_unique<thread>( [this, self = shared_from_this()] { ILOG << "thread for " << *this; while (!stop_.load()) { run(); } }); } void service_thread::run() { tid_ = this_thread::get_id(); while (!stop_.load()) { try { is_.run(); } catch (const std::exception& e) { ELOG << *this << " got exception: " << e.what(); continue; } break; } } void service_thread::stop() { if (stop_.load()) { return; } stop_.store(true); isw_.reset(); is_.stop(); if (t_) { if (!check_in_thread()) { if (t_->joinable()) { t_->join(); t_.reset(); } } else { t_->detach(); t_.reset(); } } } service_thread::~service_thread() { stop(); } void service_thread::async_call(const function<void()>& func) { // ASSERT(!is_.stopped()); is_.post(func); } void service_thread::call_in_thread(const function<void()>& func) { if (check_in_thread()) { func(); } else { async_call(func); } } shared_ptr<timer_type> service_thread::new_timer() { return make_shared<timer_type>(is_); } shared_ptr<timer_type> service_thread::add_timer(const string& tag, const function<void(bool, const shared_ptr<timer_type>&)>& cb, const system_clock::time_point& tp) { if (system_clock::to_time_t(tp) < system_clock::to_time_t(system_clock::now())) { ELOG << "timer expires in the past\n" << "now: " << clock::instance().time_str(system_clock::to_time_t(system_clock::now())) << "\n" << "timer: " << clock::instance().time_str(system_clock::to_time_t(tp)); return add_timer(tag, cb, 0s); } else { return add_timer(tag, cb, tp - system_clock::now()); } } shared_ptr<timer_type> service_thread::add_timer(const string& tag, const function<void(bool, const shared_ptr<timer_type>&)>& cb, const system_clock::duration& du) { shared_ptr<timer_type> timer = new_timer(); { lock_guard<mutex> lock(timer_counts_lock_); timer_counts_[tag] += 1; } timer->expires_from_now(du); timer->async_wait( [this, self = shared_from_this(), tag, timer, cb] (const auto& ec) { ASSERT(this->check_in_thread()); { lock_guard<mutex> lock(timer_counts_lock_); timer_counts_[tag] -= 1; if (timer_counts_[tag] == 0) { timer_counts_.erase(tag); } } if (!ec) { cb(false, timer); } else if (ec == ba::error::operation_aborted) { cb(true, timer); } else { ELOG << ec.message(); } }); return timer; } map<string, int> service_thread::timer_counts() { lock_guard<mutex> lock(timer_counts_lock_); return timer_counts_; } string service_thread::to_string() const { return name_; } ostream& operator<<(ostream& os, const service_thread& st) { return os << st.name_; } }
/// /// @file SieveOfEratosthenes.cpp /// @brief Implementation of the segmented sieve of Eratosthenes. /// /// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/config.hpp> #include <primesieve/SieveOfEratosthenes.hpp> #include <primesieve/PreSieve.hpp> #include <primesieve/EratSmall.hpp> #include <primesieve/EratMedium.hpp> #include <primesieve/EratBig.hpp> #include <primesieve/pmath.hpp> #include <primesieve/primesieve_error.hpp> #include <stdint.h> #include <memory> namespace primesieve { const uint_t SieveOfEratosthenes::bitValues_[8] = { 7, 11, 13, 17, 19, 23, 29, 31 }; /// De Bruijn bitscan table const uint_t SieveOfEratosthenes::bruijnBitValues_[64] = { 7, 47, 11, 49, 67, 113, 13, 53, 89, 71, 161, 101, 119, 187, 17, 233, 59, 79, 91, 73, 133, 139, 163, 103, 149, 121, 203, 169, 191, 217, 19, 239, 43, 61, 109, 83, 157, 97, 181, 229, 77, 131, 137, 143, 199, 167, 211, 41, 107, 151, 179, 227, 127, 197, 209, 37, 173, 223, 193, 31, 221, 29, 23, 241 }; /// @start: Sieve primes >= start /// @stop: Sieve primes <= stop /// @sieveSize: Sieve size in kilobytes /// @preSieve: Pre-sieve primes <= preSieve.getLimit() /// SieveOfEratosthenes::SieveOfEratosthenes(uint64_t start, uint64_t stop, uint_t sieveSize, const PreSieve& preSieve) : start_(start), stop_(stop), preSieve_(preSieve), limitPreSieve_(preSieve.getLimit()), sieve_(nullptr) { if (start_ < 7) throw primesieve_error("SieveOfEratosthenes: start must be >= 7"); if (start_ > stop_) throw primesieve_error("SieveOfEratosthenes: start must be <= stop"); // sieveSize_ must be a power of 2 sieveSize_ = inBetween(1, floorPowerOf2(sieveSize), 2048); sieveSize_ *= 1024; // convert to bytes uint64_t dist = sieveSize_ * NUMBERS_PER_BYTE + 1; segmentLow_ = start_ - getByteRemainder(start_); segmentHigh_ = checkedAdd(segmentLow_, dist); sqrtStop_ = (uint_t) isqrt(stop_); allocate(); } void SieveOfEratosthenes::allocate() { deleteSieve_.reset(new byte_t[sieveSize_]); sieve_ = deleteSieve_.get(); limitEratSmall_ = (uint_t)(sieveSize_ * config::FACTOR_ERATSMALL); limitEratMedium_ = (uint_t)(sieveSize_ * config::FACTOR_ERATMEDIUM); if (sqrtStop_ > limitPreSieve_) eratSmall_.reset(new EratSmall (stop_, sieveSize_, limitEratSmall_)); if (sqrtStop_ > limitEratSmall_) eratMedium_.reset(new EratMedium(stop_, sieveSize_, limitEratMedium_)); if (sqrtStop_ > limitEratMedium_) eratBig_.reset(new EratBig (stop_, sieveSize_, sqrtStop_)); } uint_t SieveOfEratosthenes::getSqrtStop() const { return sqrtStop_; } uint64_t SieveOfEratosthenes::getByteRemainder(uint64_t n) { uint64_t r = n % NUMBERS_PER_BYTE; if (r <= 1) r += NUMBERS_PER_BYTE; return r; } /// Pre-sieve multiples of small primes e.g. <= 19 /// to speed up the sieve of Eratosthenes /// void SieveOfEratosthenes::preSieve() { preSieve_.copy(sieve_, sieveSize_, segmentLow_); // unset bits (numbers) < start if (segmentLow_ <= start_) { if (start_ <= limitPreSieve_) sieve_[0] = 0xff; for (int i = 0; bitValues_[i] < getByteRemainder(start_); i++) sieve_[0] &= 0xfe << i; } } void SieveOfEratosthenes::crossOffMultiples() { if (eratSmall_) eratSmall_->crossOff(sieve_, &sieve_[sieveSize_]); if (eratMedium_) eratMedium_->crossOff(sieve_, sieveSize_); if (eratBig_) eratBig_->crossOff(sieve_); } void SieveOfEratosthenes::sieveSegment() { preSieve(); crossOffMultiples(); generatePrimes(sieve_, sieveSize_); // update for next segment uint64_t dist = sieveSize_ * NUMBERS_PER_BYTE; segmentLow_ = checkedAdd(segmentLow_, dist); segmentHigh_ = checkedAdd(segmentHigh_, dist); } /// Sieve the remaining segments, most segments /// are sieved in addSievingPrime() /// void SieveOfEratosthenes::sieve() { while (segmentHigh_ < stop_) sieveSegment(); uint64_t remainder = getByteRemainder(stop_); uint64_t dist = (stop_ - remainder) - segmentLow_; sieveSize_ = ((uint_t) dist) / NUMBERS_PER_BYTE + 1; dist = sieveSize_ * NUMBERS_PER_BYTE + 1; segmentHigh_ = checkedAdd(segmentLow_, dist); // sieve the last segment preSieve(); crossOffMultiples(); int i; // unset bits (numbers) > stop_ for (i = 0; i < 8; i++) if (bitValues_[i] > remainder) break; int unsetBits = ~(0xff << i); sieve_[sieveSize_ - 1] &= unsetBits; // unset bytes (numbers) > stop_ for (uint_t j = sieveSize_; j % 8 != 0; j++) sieve_[j] = 0; generatePrimes(sieve_, sieveSize_); } } // namespace
// Lab 1 Q1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <ctime> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int x=0, y=0; int* p=nullptr; int* q=nullptr; srand(time(0)); x=rand()%100; y=rand()%100; p=&x; q=&y; cout<<"The Values of the variables are:"<<endl; cout<<"x: "<<x<<endl; cout<<"y: "<<y<<endl; cout<<"p: "<<p<<endl; cout<<"q: "<<q<<endl; cout<<"*p: "<<*p<<endl; cout<<"*q: "<<*q<<endl<<endl; int swap=0; swap=x; x=y; y=swap; cout<<"The Values of the variables after swapping are:"<<endl; cout<<"x: "<<x<<endl; cout<<"y: "<<y<<endl; cout<<"p: "<<p<<endl; cout<<"q: "<<q<<endl; cout<<"*p: "<<*p<<endl; cout<<"*q: "<<*q<<endl<<endl; int* swapptr=nullptr; swapptr=p; p=q; q=swapptr; cout<<"The Values of the variables after address swapping are:"<<endl; cout<<"x: "<<x<<endl; cout<<"y: "<<y<<endl; cout<<"p: "<<p<<endl; cout<<"q: "<<q<<endl; cout<<"*p: "<<*p<<endl; cout<<"*q: "<<*q<<endl<<endl; return 0; }
#include "mainwindow.h" #include "ui_mainwindow.h" #include "opencv2/opencv.hpp" #include "colorretouch.h" #include "imagehsv.h" #include "../Tools/imageoperation.h" #include "../Tools/colorOperation.h" using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); /*float HSV[3]; HSV[0] = 100; HSV[1] = 0.4; HSV[2] = 0.1; colorRetouch cr(HSV);*/ cv::Mat s_image = cv::imread("C:/Users/Tom/Downloads/fondecran.jpg"); int B = getPixel(s_image, 0,0, 0); int G = getPixel(s_image, 0,0, 1); int R = getPixel(s_image, 0,0, 2); cout << endl << "B: " << B << " G: " << G << " R: " << R << endl; int H; int S,V; rgb2hsv(R,G,B,H,S,V); cout << "H: " << H << " S: " << S << " V: " << V << endl <<endl; int H2,S2,V2; imageHSV a(s_image); H2 = getPixel(a._s_hsv, 0, 0, HUE); S2 = getPixel(a._s_hsv, 0, 0, SAT); V2 = getPixel(a._s_hsv, 0, 0, VAL); cout << "cvcvtcolor" << endl; cout << "H: " << H2 << " S: " << S2 << " V: " << V2 << endl; } MainWindow::~MainWindow() { delete ui; }
/******<CODE NEVER DIE>******/ #include<bits/stdc++.h> using namespace std; #define ll long long #define FastIO ios_base::sync_with_stdio(0) #define IN cin.tie(0) #define OUT cout.tie(0) #define CIG cin.ignore() #define pb push_back #define pa pair<int,int> #define f first #define s second #define FOR(i,n,m) for(int i=n;i<=m;i++) #define FORD(i,n,m) for(int i=m;i>=n;i--) #define reset(A) memset(A,0,sizeof(A)) #define FILEIN freopen("inputDTL.txt","r",stdin) #define FILEOUT freopen("outputDTL.txt","w",stdout) /**********DTL**********/ long long const mod=1e9+7; int const MAX=1e5+5; /**********DTL**********/ /**********DTL**********/ ll Solution(string str){ ll n=str.length(); ll odd=0, eve=0; for(ll i=0;i<n;i++){ if(i%2==0){ odd+=(str[i]-'0'); }else{ eve+=(str[i]-'0'); } } return ((odd-eve)%11==0); } /**********main function**********/ int main(){ FastIO; IN; OUT; int test; cin >> test; while(test--){ string str; cin >> str; if(Solution(str)){ cout << "1"; }else{ cout << "0"; } cout << endl; } return 0; }
// Author : Abdullah Baron #include <iostream> #include <string> #include <vector> #include "bitmap.h" using namespace std; // Function to check the size of two images int checkSize(Bitmap ,Bitmap ); // Function to combine images void makePic(Bitmap & , Bitmap [] ,int ); int main() { Bitmap images[10]; Bitmap imageFinal; vector <vector <Pixel> > bmp; Pixel rgb; string name; int files = 0; bool BmpImage; int check = 0; do{ // Get the file names from the users cout<< "Enter 10 files name (notice the file need to be in BMP format) or DONE if you have entered enough files \n"; cin>> name; // if the user inputs "DONE" the program will break from the loop if(name == "DONE") { break; } images[files].open(name); // Check if the image is valid BmpImage = images[files].isImage(); if(BmpImage)// If the Bmp is valid { check = checkSize(images[files],images[0]); if(check == 1) { files++; } else { cout <<"Bitmap files should be the same size" << endl; } } }while(files<10); if(files>1) { makePic(imageFinal,images,files); imageFinal.save("composite-abaron3.bmp"); } else{ cout <<"Need More than 1 image to create the composite" << endl; } return 0 ; } int checkSize (Bitmap image, Bitmap imagefirst) { vector <vector <Pixel> > bmp; vector <vector <Pixel> > bmp2; bmp = image.toPixelMatrix(); bmp2 = imagefirst.toPixelMatrix(); if(bmp.size() == bmp2.size()) { if(bmp[0].size() == bmp2[0].size()) { return 1; } } return 0; } void makePic(Bitmap &image, Bitmap images[],int files) { cout <<"files : "<<files <<endl; vector <vector <Pixel> > bmp; vector <vector <Pixel> > bmp2; Pixel rgb; Pixel rgb2; int red[10]; int green[10]; int blue[10]; int aver = 0; image = images[0]; bmp2 = image.toPixelMatrix(); for(int file = 0;file<files;file++) { bmp = images[file].toPixelMatrix(); for(int h = 0; h<bmp2.size(); h++) //h = hight { for(int w = 0; w<bmp2[0].size(); w++) // w = width { if(file >0) { rgb = bmp[h][w]; rgb2 = bmp2[h][w]; aver = (rgb.red+rgb2.red) / 2; rgb2.red = aver; aver = (rgb.green + rgb2.green) /2; rgb2.green = aver; aver = (rgb.blue + rgb2.blue) /2; rgb2.blue = aver; bmp2[h][w] = rgb2; } } } cout <<"Image "<< file+1 << " Out of "<< files<< " Completed" << endl; } image.fromPixelMatrix(bmp2); } //first ask for the file name // keep asking ( by using loop) until they write "DONE" or they goes to the maximum files number which is 10 // we need to use .isImage() to make sure that the image is a bmp image // use matrix to compine the valid images together and get the averege values of RGB // we take the average vlaue to make sure that we can see all images when we combine them. // make a cout to show the total of the pictures and how many picture are done. // finally we need to save the combined pic.
#include <iostream> using namespace std; int main () { const int MAX_ARRAY = 5; string nama[MAX_ARRAY]={}; for(int i=0;i<MAX_ARRAY;++i){ cout<<"Masukan Nama : ";cin>>nama[i]; } cout<<endl<<"=== Daftar Nama ==="<<endl; for(int i=0;i<MAX_ARRAY;++i){ cout<<(i+1)<<". "<<nama[i]<<endl; } return 0; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; int f[50][3],n; int a[50],b[50],c[50]; bool can(int k1,int t1,int k2,int t2) { int h1,d1,h2,d2; if (t1 == 0) {h1 = a[k1];d1 = b[k1];} if (t1 == 1) {h1 = a[k1];d1 = c[k1];} if (t1 == 2) {h1 = b[k1];d1 = c[k1];} if (t2 == 0) {h2 = a[k2];d2 = b[k2];} if (t2 == 1) {h2 = a[k2];d2 = c[k2];} if (t2 == 2) {h2 = b[k2];d2 = c[k2];} if (h1 < h2 && d1 < d2) return true; if (h1 < d2 && d1 < h2) return true; return false; } int dfs(int k,int t) { if (f[k][t]) return f[k][t]; int h; if (t == 0) h = c[k]; if (t == 1) h = b[k]; if (t == 2) h = a[k]; f[k][t] = 0; for (int i = 1;i <= n; i++) { for (int j = 0;j < 3; j++) if (can(i,j,k,t)) f[k][t] = max(f[k][t],dfs(i,j)); } f[k][t] += h; return f[k][t]; } int main() { int ca = 1; while (scanf("%d",&n) != EOF && n) { memset(f,0,sizeof(f)); for (int i = 1;i <= n; i++) { scanf("%d%d%d",&a[i],&b[i],&c[i]); } int ans = 0; for (int i = 1;i <= n; i++) { for (int j = 0;j < 3; j++) { int k = dfs(i,j); ans = max(ans,k); } } printf("Case %d: maximum height = %d\n",ca++,ans); } return 0; }
#include "mainwindow.h" #include <QApplication> #include <QDebug> #include <librealsense/rs.hpp> #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> bool _loop = true; int main(int argc, char *argv[]) { QApplication a(argc, argv); Mainwindow w; w.show(); if( !w.initialize_streaming()) { qDebug() << "Unable to locate a camera "; return EXIT_FAILURE; } cv::namedWindow("Depth Image", 0); cv::namedWindow("RGB Image", 0); cv::namedWindow("Infrared Image", 0); while( _loop ){ if( w._rs_camera.is_streaming() ) { w._rs_camera.wait_for_frames(); w.display_next_frame(); } } w._rs_camera.stop(); cv::destroyAllWindows(); return EXIT_SUCCESS; return a.exec(); } static void onMouse( int event, int x, int y, int, void* window_name ) { if( event == cv::EVENT_LBUTTONDOWN ) { _loop = false; } }
/* * File: AIC.cpp * Author: Corrado Pezzato, TU Delft, DCSC * Edited: Kristijonas Atkociunas, DTU * * Created on April 14th, 2019 * * Class to perform active inference control of the 7DOF Franka Emika Panda robot. * Definition of the methods contained in AIC.h * */ #include "AIC.h" // Constructor which takes as argument the publishers and initialises the private ones in the class AIC::AIC(int whichRobot){ // Initialize publishers on the topics /robot1/panda_joint*_controller/command for the joint efforts tauPub1 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint1_controller/command", 20); tauPub2 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint2_controller/command", 20); tauPub3 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint3_controller/command", 20); tauPub4 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint4_controller/command", 20); tauPub5 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint5_controller/command", 20); tauPub6 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint6_controller/command", 20); tauPub7 = nh.advertise<std_msgs::Float64>("/robot1/panda_joint7_controller/command", 20); sensorSub = nh.subscribe("/robot1/joint_states", 1, &AIC::jointStatesCallback, this); trigSub = nh.subscribe("/trig", 1, &AIC::trigCallback, this); // Publisher for the free-energy and sensory prediction errors IFE_pub = nh.advertise<std_msgs::Float64>("panda_free_energy", 10); SPE_pub = nh.advertise<std_msgs::Float64MultiArray>("panda_SPE", 10); // Publishers for beliefs beliefs_mu_pub = nh.advertise<std_msgs::Float64MultiArray>("beliefs_mu", 10); beliefs_mu_p_pub = nh.advertise<std_msgs::Float64MultiArray>("beliefs_mu_p", 10); beliefs_mu_pp_pub = nh.advertise<std_msgs::Float64MultiArray>("beliefs_mu_pp", 10); // Publishers for beliefs beliefs_mu_pub = nh.advertise<std_msgs::Float64MultiArray>("beliefs_mu", 10); beliefs_mu_p_pub = nh.advertise<std_msgs::Float64MultiArray>("beliefs_mu_p", 10); beliefs_mu_pp_pub = nh.advertise<std_msgs::Float64MultiArray>("beliefs_mu_pp", 10); // Initialize the variables for thr AIC AIC::initVariables(); } AIC::~AIC(){} void AIC::jointStatesCallback(const sensor_msgs::JointState::ConstPtr& msg) { // Save joint values for( int i = 0; i < 7; i++ ) { jointPos(i) = msg->position[i]; jointVel(i) = msg->velocity[i]; } // If this is the first time we read the joint states then we set the current beliefs if (dataReceived == 0){ // Track the fact that the encoders published dataReceived = 1; // The first time we retrieve the position we define the initial beliefs about the states mu = jointPos; mu_p = jointVel; } } void AIC::trigCallback(const std_msgs::UInt8::ConstPtr& msg) { trig = msg->data; } void AIC::initVariables(){ // Support variable dataReceived = 0; // Variances associated with the beliefs and the sensory inputs var_mu = 5.0; var_muprime = 10.0; var_q = 1; var_qdot = 1; // Learning rates for the gradient descent (found that a ratio of 60 works good) k_mu = 11.67; k_a = 700; // Precision matrices (first set them to zero then populate the diagonal) SigmaP_yq0 = Eigen::Matrix<double, 7, 7>::Zero(); SigmaP_yq1 = Eigen::Matrix<double, 7, 7>::Zero(); SigmaP_mu = Eigen::Matrix<double, 7, 7>::Zero(); SigmaP_muprime = Eigen::Matrix<double, 7, 7>::Zero(); for( int i = 0; i < SigmaP_yq0.rows(); i = i + 1 ) { SigmaP_yq0(i,i) = 1/var_q; SigmaP_yq1(i,i) = 1/var_qdot; SigmaP_mu(i,i) = 1/var_mu; SigmaP_muprime(i,i) = 1/var_muprime; } // Initialize control actions u << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0; // Initialize prior beliefs about the second ordet derivatives of the states of the robot mu_pp << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0; // Integration step h = 0.001; // Resize Float64MultiArray messages AIC_mu.data.resize(7); AIC_mu_p.data.resize(7); AIC_mu_pp.data.resize(7); SPE.data.resize(2); } void AIC::minimiseF(){ // Compute single sensory prediction errors SPEq = (jointPos.transpose()-mu.transpose())*SigmaP_yq0*(jointPos-mu); SPEdq = (jointVel.transpose()-mu_p.transpose())*SigmaP_yq1*(jointVel-mu_p); SPEmu_p = (mu_p.transpose()+mu.transpose()-mu_d.transpose())*SigmaP_mu*(mu_p+mu-mu_d); SPEmu_pp = (mu_pp.transpose()+mu_p.transpose())*SigmaP_muprime*(mu_pp+mu_p); // Free-energy as a sum of squared values (i.e. sum the SPE) F.data = SPEq + SPEdq + SPEmu_p + SPEmu_pp; // Free-energy minimization using gradient descent and beliefs update mu_dot = mu_p - k_mu*(-SigmaP_yq0*(jointPos-mu)+SigmaP_mu*(mu_p+mu-mu_d)); mu_dot_p = mu_pp - k_mu*(-SigmaP_yq1*(jointVel-mu_p)+SigmaP_mu*(mu_p+mu-mu_d)+SigmaP_muprime*(mu_pp+mu_p)); mu_dot_pp = - k_mu*(SigmaP_muprime*(mu_pp+mu_p)); // Belifs update mu = mu + h*mu_dot; // Belief about the position mu_p = mu_p + h*mu_dot_p; // Belief about motion of mu mu_pp = mu_pp + h*mu_dot_pp; // Belief about motion of mu' // Publish beliefs as Float64MultiArray for (int i=0;i<7;i++){ AIC_mu.data[i] = mu(i); AIC_mu_p.data[i] = mu_p(i); AIC_mu_pp.data[i] = mu_pp(i); } // Define SPE message SPE.data[0] = SPEq; SPE.data[1] = SPEdq; // Calculate and send control actions AIC::computeActions(); // Publish free-energy IFE_pub.publish(F); // Sensory prediction error publisher SPE_pub.publish(SPE); // Publish beliefs beliefs_mu_pub.publish(AIC_mu); beliefs_mu_p_pub.publish(AIC_mu_p); beliefs_mu_pp_pub.publish(AIC_mu_pp); } void AIC::computeActions(){ // Compute control actions through gradient descent of F u = u-h*k_a*(SigmaP_yq1*(jointVel-mu_p)+SigmaP_yq0*(jointPos-mu)); // Set the toques from u and publish tau1.data = u(0); tau2.data = u(1); tau3.data = u(2); tau4.data = u(3); tau5.data = u(4); tau6.data = u(5); tau7.data = u(6); // Publishing tauPub1.publish(tau1); tauPub2.publish(tau2); tauPub3.publish(tau3); tauPub4.publish(tau4); tauPub5.publish(tau5); tauPub6.publish(tau6); tauPub7.publish(tau7); } int AIC::dataReady(){ // Method to control if the joint states have been received already, // used in the main function if(dataReceived==1) return 1; else return 0; } void AIC::setGoal(std::vector<double> desiredPos){ for(int i=0; i<desiredPos.size(); i++){ mu_d(i) = desiredPos[i]; } } std_msgs::Float64MultiArray AIC::getSPE(){ return(SPE); } int AIC::trigReturn(){ if(trig==1) return 1; else return 0; }
#ifndef BIT_UTILS_INCLUDED #define BIT_UTILS_INCLUDED #include "bitBoard.hpp" #if defined(__GNUC__) inline int lsb(BitBoard32 bb) { return __builtin_ctzl(bb); } #else #define NO_BSF const int BitTable32[32] = {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; inline int lsb(BitBoard32 bb) { return BitTable32[((uint32_t)((bb & -bb) * 0x077cb531u)) >> 27]; } #endif inline int pop_bit_32(BitBoard32 *bb) { int pos = lsb(*bb); *bb &= (*bb - 1); return pos; } inline int pop_bit_81(BitBoard81 *bb) { if (bb->bits27[0]) { return pop_bit_32(bb->bits27); } else if (bb->bits27[1]) { return 27 + pop_bit_32(bb->bits27 + 1); } else { return 54 + pop_bit_32(bb->bits27 + 2); } } inline int count_bits_32(BitBoard32 bb) { int r; for (r = 0; bb; r++, bb &= bb - 1) ; return r; } inline int count_bits_81(BitBoard81 bb) { return count_bits_32(bb.bits27[0]) + count_bits_32(bb.bits27[1]) + count_bits_32(bb.bits27[2]); } #endif // #ifndef BIT_UTILS_INCLUDED
// // Keyboard.h // Odin.MacOSX // // Created by Daniel on 04/06/15. // Copyright (c) 2015 DG. All rights reserved. // #ifndef __Odin_MacOSX__Keyboard__ #define __Odin_MacOSX__Keyboard__ #include "KeysGLFW.h" namespace odin { namespace io { class Keyboard { public: /// \brief Default Constructor Keyboard(); /// \brief Set the state of a keyboard key /// \param button Button to set /// \param pressed Is it pressed? void setButtonState(int button, bool pressed); /// \brief Get the state of a button key /// \param button Keyboard button /// \return Is it pressed? bool getButtonState(int button) const; private: bool m_keyStates[ODIN_KEY_LAST]; }; } } #endif /* defined(__Odin_MacOSX__Keyboard__) */
#include "ShortTestInfo.h" #include <QString> // :: Constructors :: const QString ID_JSON_KEY = "id"; const QString NAME_JSON_KEY = "name"; // :: Implementation :: struct ShortTestInfo::Implementation { QString name = ""; }; // :: Lifecycle :: // :: Constructors :: ShortTestInfo::ShortTestInfo(int id/*= 0*/, const QString &name/*= ""*/) : Entity(id), pimpl(new Implementation()) { setName(name); } // :: Copy :: ShortTestInfo::ShortTestInfo(const ShortTestInfo &other) : Entity(other), pimpl(new Implementation(*other.pimpl)) { } ShortTestInfo &ShortTestInfo::operator=(const ShortTestInfo &other) { *pimpl = *other.pimpl; return *this; } // :: Move :: ShortTestInfo::ShortTestInfo(ShortTestInfo &&other) : Entity(other), pimpl(other.pimpl.take()) { } ShortTestInfo &ShortTestInfo::operator=(ShortTestInfo &&other) { pimpl.swap(other.pimpl); return *this; } // :: Destructor :: ShortTestInfo::~ShortTestInfo() {} // :: Accessors :: QString ShortTestInfo::getName() const { return pimpl->name; } void ShortTestInfo::setName(const QString &name) { pimpl->name = name; } // :: Serializable :: QJsonObject ShortTestInfo::toJson() const { QJsonObject json; json[ID_JSON_KEY] = getId(); json[NAME_JSON_KEY] = getName(); return json; } void ShortTestInfo::initWithJsonObject(const QJsonObject &json) { if (json.contains(ID_JSON_KEY) && json[ID_JSON_KEY].isDouble()) { setId(json[ID_JSON_KEY].toInt()); } if (json.contains(NAME_JSON_KEY) && json[NAME_JSON_KEY].isString()) { setName(json[NAME_JSON_KEY].toString()); } }